From 1a7bdb2be4e73886c4b2a62eb758b48c7794c42d Mon Sep 17 00:00:00 2001 From: Tanner Date: Mon, 9 Nov 2026 18:34:19 +0000 Subject: [PATCH] Recover inventory space when gathering supplies --- mosfet/game.py | 15 ++ mosfet/jobs/grab_supplies.py | 208 ++++++++++++++++++++++-- tests/test_inventory_drain.py | 20 ++- tests/test_inventory_supply_recovery.py | 205 +++++++++++++++++++++++ 4 files changed, 435 insertions(+), 13 deletions(-) create mode 100644 tests/test_inventory_supply_recovery.py diff --git a/mosfet/game.py b/mosfet/game.py index 60b99ea..6c2806f 100644 --- a/mosfet/game.py +++ b/mosfet/game.py @@ -1373,6 +1373,21 @@ class Game(LegacyGame): self.g.connection.write_packet(ClientTickEnd(), force=True) return True + def swap_container_slot_with_hotbar(self, container_slot, inventory_slot): + window = self.g.get('window') + if not window or not 36 <= inventory_slot <= 44: + return False + packet = ContainerClickSwapPacket( + container_id=window.window_id, + state_id=self.g.inventory_state_ids.get( + window.window_id, window.state_id), + slot=container_slot, + button=inventory_slot - 36, + ) + self.g.connection.write_packet(packet, force=True) + self.g.connection.write_packet(ClientTickEnd(), force=True) + return True + def close_window(self): window = self.g.get('window') if not window: diff --git a/mosfet/jobs/grab_supplies.py b/mosfet/jobs/grab_supplies.py index e2da9cc..3d5e2f6 100644 --- a/mosfet/jobs/grab_supplies.py +++ b/mosfet/jobs/grab_supplies.py @@ -34,15 +34,13 @@ class GrabSuppliesStates: used_slots = self.g.game.count_inventory_slots() print('used:', used_slots, 'total:', self.g.maximum_supply_slots) - if used_slots >= self.g.maximum_supply_slots: - print('Inventory is too full, aborting') - self.state = self.cleanup - return self.checked_ground_items = set() self.checked_ground_groups = set() self.checked_supply_chests = set() self.ground_stack_counts = {} + self.failed_drop_slots = set() + self.pending_drop_slot = None self.ground_entity_id = None self.ground_position = None if self.supplies: @@ -66,6 +64,94 @@ class GrabSuppliesStates: self._has_nearby_ground_items(item_ids, limits[1]) for item_ids, limits in self.supplies.items()) + def _protected_inventory_slots(self): + needed = set(items.NEEDED_ITEMS) + keep = set() + covered = set() + groups = ( + items.BED_IDS, {items.CHEST_ID}, items.FOOD_IDS, + items.AXE_IDS, items.SHOVEL_IDS, + ) + for group in groups: + group = needed.intersection(group) + if not group: + continue + covered.update(group) + stacks = [(slot, item) for slot, item in self.g.inv.items() + if 9 <= slot <= 45 and item.present and + item.item_id in group] + if stacks: + keep.add(max(stacks, key=lambda pair: pair[1].item_count)[0]) + + for item_id in needed - covered: + stacks = [(slot, item) for slot, item in self.g.inv.items() + if 9 <= slot <= 45 and item.present and + item.item_id == item_id] + if stacks: + keep.add(max(stacks, key=lambda pair: pair[1].item_count)[0]) + + for item_id in items.WANTED_ITEMS: + stacks = [(slot, item) for slot, item in self.g.inv.items() + if 9 <= slot <= 45 and item.present and + item.item_id == item_id] + if stacks: + keep.add(max(stacks, key=lambda pair: pair[1].item_count)[0]) + return keep + + def _inventory_replacement_rank(self, slot): + item = self.g.inv[slot] + important = set(items.NEEDED_ITEMS) | set(items.WANTED_ITEMS) + return (item.item_id in important, -(item.item_count or 0), slot) + + def _least_important_inventory_slot(self, hotbar_only=False, + excluded_item_ids=(), + inventory_range=None): + if hotbar_only: + first_slot, last_slot = 36, 44 + elif inventory_range is not None: + first_slot, last_slot = inventory_range + else: + first_slot, last_slot = 9, 45 + if hotbar_only: + for slot in range(first_slot, last_slot + 1): + item = self.g.inv.get(slot) + if not item or not item.present: + return slot + + protected = self._protected_inventory_slots() + excluded = set(excluded_item_ids) + candidates = [ + (slot, item) for slot, item in self.g.inv.items() + if first_slot <= slot <= last_slot and item.present and + slot not in protected and item.item_id not in excluded and + (not self.g.get('drop_waiting') or + slot != self.g.drop_waiting.get('slot')) and + (hotbar_only or slot not in self.failed_drop_slots) + ] + if not candidates: + return None + + important = set(items.NEEDED_ITEMS) | set(items.WANTED_ITEMS) + candidates.sort(key=lambda pair: ( + pair[1].item_id in important, + -(pair[1].item_count or 0), pair[0])) + return candidates[0][0] + + def _drop_stack_for_ground_pickup(self): + slot = self._least_important_inventory_slot( + excluded_item_ids=self.target_items) + if slot is None: + return False + item = self.g.inv[slot] + print('Dropping lesser-priority stack to make pickup room:', + item.item_id, item.item_count, 'from slot', slot) + if not self.g.game.drop_inventory_slot(slot, whole_stack=True): + return False + self.pending_drop_slot = slot + self.wait_time = 0.0 + self.state = self.wait_for_inventory_space + return True + def _record_ground_pickup(self): self.checked_ground_items.add(self.ground_entity_id) self.ground_stack_counts[self.target_items] = ( @@ -177,8 +263,54 @@ class GrabSuppliesStates: elif (obj is None or utils.pint(self.g.pos) == self.ground_position or utils.phyp(self.g.pos, (obj.x, obj.y, obj.z)) <= 1.25): + if (self.g.game.count_inventory_slots() >= + self.g.maximum_supply_slots): + if not self._drop_stack_for_ground_pickup(): + print('No lesser-priority stack available for ground pickup') + self.checked_ground_items.add(self.ground_entity_id) + self.g.path = [] + self.ground_entity_id = None + self.ground_position = None + self.state = self.find_ground_items + else: + self.wait_time = 1.0 + self.state = self.wait_for_ground_item + + def wait_for_inventory_space(self): + if (self.g.game.count_items(self.target_items) >= + self.ground_required_count): + print('Picked up required ground supplies after freeing inventory space') + self._record_ground_pickup() + self.pending_drop_slot = None + self.state = self.check_supplies + return + + if self.g.get('drop_waiting'): + return + + if (self.g.game.count_inventory_slots() < + self.g.maximum_supply_slots): + self.pending_drop_slot = None self.wait_time = 1.0 self.state = self.wait_for_ground_item + return + + if self.pending_drop_slot is not None: + self.failed_drop_slots.add(self.pending_drop_slot) + self.pending_drop_slot = None + + if self.wait_time > 0: + self.wait_time -= utils.TICK + return + + print('Drop did not free inventory space; trying another stack') + if not self._drop_stack_for_ground_pickup(): + print('No more lesser-priority stacks available') + self.checked_ground_items.add(self.ground_entity_id) + self.g.path = [] + self.ground_entity_id = None + self.ground_position = None + self.state = self.find_ground_items def wait_for_ground_item(self): if (self.g.game.count_items(self.target_items) >= @@ -197,6 +329,11 @@ class GrabSuppliesStates: self.state = self.check_supplies return + if (self.g.game.count_inventory_slots() >= + self.g.maximum_supply_slots): + self.state = self.going_to_ground_item + return + print('Could not pick up ground item; trying another') self.checked_ground_items.add(self.ground_entity_id) self.g.path = [] @@ -328,12 +465,6 @@ class GrabSuppliesStates: return used_slots = self.g.game.count_inventory_slots() print('used:', used_slots, 'total:', self.g.maximum_supply_slots) - if used_slots >= self.g.maximum_supply_slots: - print('Inventory is too full, aborting') - self.g.game.close_window() - self.g.look_at = None - self.state = self.cleanup - return for slot_num in range(w.container_slots): if slot_num not in w.contents: @@ -349,10 +480,61 @@ class GrabSuppliesStates: if self.maximum_stacks and self.count >= self.maximum_stacks: break + if used_slots >= self.g.maximum_supply_slots: + inventory_slot = self._least_important_inventory_slot( + hotbar_only=True, excluded_item_ids=self.target_items) + main_slot = self._least_important_inventory_slot( + excluded_item_ids=self.target_items, + inventory_range=(9, 35)) + hotbar_item = (self.g.inv.get(inventory_slot) + if inventory_slot is not None else None) + use_main_stack = ( + main_slot is not None and + (inventory_slot is None or + (hotbar_item and hotbar_item.present and + self._inventory_replacement_rank(main_slot) < + self._inventory_replacement_rank(inventory_slot)))) + + if use_main_stack: + transit_slot = next((hotbar_slot for hotbar_slot in + range(36, 45) + if (self.g.inv.get(hotbar_slot) and + self.g.inv[hotbar_slot].present and + self.g.inv[hotbar_slot].item_id not in + self.target_items)), None) + if transit_slot is None: + print('No hotbar slot available to stage inventory stack') + self.g.game.close_window() + self.g.look_at = None + self.state = self.cleanup + return + window_slot = w.container_slots + main_slot - 9 + print('Moving lesser-priority stack from inventory slot', + main_slot, 'through hotbar slot', transit_slot) + self.g.item_lock = True + if self.g.game.swap_container_slot_with_hotbar( + window_slot, transit_slot): + return + self.g.item_lock = False + return + + if inventory_slot is None: + print('No replaceable inventory stack; cannot take supply') + self.g.game.close_window() + self.g.look_at = None + self.state = self.cleanup + return + print('Swapping', slot, 'for hotbar slot', inventory_slot) + self.g.item_lock = True + if self.g.game.swap_container_slot_with_hotbar( + slot_num, inventory_slot): + self.count += 1 + return + self.g.item_lock = False + return + self.count += 1 - print('Moving', slot) - self.g.item_lock = True self.g.game.click_window(slot_num, 0, 1, slot) return @@ -395,6 +577,8 @@ class GrabSuppliesStates: self.area = None self.opening = None self.wait_time = 0 + self.failed_drop_slots = set() + self.pending_drop_slot = None def run(self): self._refresh_useless_chests() diff --git a/tests/test_inventory_drain.py b/tests/test_inventory_drain.py index efedf8f..44c1175 100644 --- a/tests/test_inventory_drain.py +++ b/tests/test_inventory_drain.py @@ -2,7 +2,9 @@ import io import unittest from munch import Munch -from minecraft.networking.modern import ClientTickEnd, ContainerOpenPacket +from minecraft.networking.modern import ( + ClientTickEnd, ContainerOpenPacket, ContainerClickSwapPacket, +) from minecraft.networking.packets import PacketBuffer from mosfet.game import ( @@ -52,6 +54,22 @@ class TestInventoryDrain(unittest.TestCase): self.assertEqual(payload.get_writable(), bytes.fromhex( '0007002d00040000')) + def test_swap_container_slot_with_hotbar_uses_current_window_state(self): + connection = FakeConnection() + game = Game.__new__(Game) + game.g = Munch( + connection=connection, + window=Munch(window_id=4, state_id=8), + inventory_state_ids={4: 9}, + ) + + self.assertTrue(game.swap_container_slot_with_hotbar(2, 37)) + packet = connection.packets[0][0] + self.assertIsInstance(packet, ContainerClickSwapPacket) + self.assertEqual((packet.container_id, packet.state_id, + packet.slot, packet.button), (4, 9, 2, 1)) + self.assertIsInstance(connection.packets[1][0], ClientTickEnd) + def test_quick_move_packet_encodes_shift_click(self): packet = ContainerClickQuickMovePacket( container_id=3, state_id=7, slot=42) diff --git a/tests/test_inventory_supply_recovery.py b/tests/test_inventory_supply_recovery.py new file mode 100644 index 0000000..43be361 --- /dev/null +++ b/tests/test_inventory_supply_recovery.py @@ -0,0 +1,205 @@ +import unittest +from munch import Munch + +from mosfet.info import items +from mosfet.jobs.grab_supplies import GrabSuppliesStates +from mosfet.protocol.types import Slot + + +class InventorySupplyRecoveryTests(unittest.TestCase): + def make_inventory(self): + return { + 36: Slot(True, next(iter(items.BED_IDS)), 1), + 37: Slot(True, items.CHEST_ID, 32), + 38: Slot(True, next(iter(items.FOOD_IDS)), 64), + 39: Slot(True, next(iter(items.AXE_IDS)), 1), + 40: Slot(True, items.SAND_ID, 16), + 41: Slot(True, items.get_id('stone'), 64), + 42: Slot(True, items.get_id('dirt'), 4), + 43: Slot(True, items.get_id('stick'), 1), + 44: Slot(True, items.get_id('cobblestone'), 2), + } + + def with_needed_axes(self, callback): + previous_needed = items.NEEDED_ITEMS + try: + items.set_needed(items.AXE_IDS) + callback() + finally: + items.NEEDED_ITEMS = previous_needed + + def test_preserves_essential_stacks_and_selects_largest_junk_stack(self): + def run(): + g = Munch(inv=self.make_inventory(), drop_waiting=None) + state = GrabSuppliesStates(g) + self.assertEqual(state._protected_inventory_slots(), + {36, 37, 38, 39}) + self.assertEqual(state._least_important_inventory_slot( + hotbar_only=True), 41) + self.assertEqual(state._least_important_inventory_slot(), 41) + + self.with_needed_axes(run) + + def test_full_container_transfer_swaps_instead_of_aborting(self): + def run(): + axe_id = next(iter(items.AXE_IDS)) + swaps = [] + + class FakeGame: + def count_inventory_slots(self): + return 33 + + def swap_container_slot_with_hotbar(self, container_slot, + inventory_slot): + swaps.append((container_slot, inventory_slot)) + return True + + g = Munch( + inv=self.make_inventory(), item_lock=False, + window=Munch(container_slots=27, contents={ + 0: Slot(True, axe_id, 1), + }), + maximum_supply_slots=33, game=FakeGame(), + ) + state = GrabSuppliesStates(g) + state.target_items = {axe_id} + state.maximum_stacks = 1 + state.grab_items() + + self.assertEqual(swaps, [(0, 41)]) + self.assertTrue(g.item_lock) + self.assertEqual(state.count, 1) + + self.with_needed_axes(run) + + def test_full_ground_pickup_frees_room_and_waits_for_target(self): + def run(): + class FakeGame: + def __init__(self): + self.inventory_slots = 33 + self.target_count = 0 + self.dropped = [] + + def count_inventory_slots(self): + return self.inventory_slots + + def count_items(self, _item_ids): + return self.target_count + + def drop_inventory_slot(self, slot, whole_stack=True): + self.dropped.append((slot, whole_stack)) + return True + + target_id = items.NETHERWART_ID + obj = Munch(entity_id=99, item_id=target_id, + x=0.5, y=64.0, z=0.5) + game = FakeGame() + g = Munch( + inv=self.make_inventory(), drop_waiting=None, + objects={99: obj}, path=[], pos=(0.5, 64, 0.5), + maximum_supply_slots=33, game=game, + ) + state = GrabSuppliesStates(g) + state.checked_ground_items = set() + state.checked_ground_groups = set() + state.ground_stack_counts = {} + state.target_items = (target_id,) + state.target_minimum = 1 + state.target_maximum_stacks = 1 + state.ground_entity_id = 99 + state.ground_position = (0, 64, 0) + state.ground_required_count = 1 + + state.going_to_ground_item() + self.assertEqual(game.dropped, [(41, True)]) + self.assertIs(state.state.__func__, + state.wait_for_inventory_space.__func__) + + g.drop_waiting = None + game.inventory_slots = 32 + state.wait_for_inventory_space() + self.assertIs(state.state.__func__, + state.wait_for_ground_item.__func__) + + game.target_count = 1 + state.wait_for_ground_item() + self.assertEqual(state.ground_stack_counts[(target_id,)], 1) + self.assertIs(state.state.__func__, state.check_supplies.__func__) + + self.with_needed_axes(run) + + def test_container_swap_can_stage_a_main_inventory_stack_through_hotbar(self): + previous_needed = items.NEEDED_ITEMS + previous_wanted = items.WANTED_ITEMS + try: + items.set_needed(items.AXE_IDS | items.SHOVEL_IDS) + saplings = list(items.SAPLING_IDS)[:4] + items.set_wanted(set(saplings)) + axes = next(iter(items.AXE_IDS)) + inventory = { + 36: Slot(True, next(iter(items.BED_IDS)), 1), + 37: Slot(True, items.CHEST_ID, 1), + 38: Slot(True, next(iter(items.FOOD_IDS)), 64), + 39: Slot(True, axes, 1), + 40: Slot(True, next(iter(items.SHOVEL_IDS)), 1), + 41: Slot(True, saplings[0], 1), + 42: Slot(True, saplings[1], 1), + 43: Slot(True, saplings[2], 1), + 44: Slot(True, saplings[3], 1), + 9: Slot(True, items.get_id('stone'), 64), + } + swaps = [] + + class FakeGame: + def count_inventory_slots(self): + return 33 + + def swap_container_slot_with_hotbar(self, slot, hotbar): + swaps.append((slot, hotbar)) + return True + + target_id = items.PUMPKIN_ID + g = Munch( + inv=inventory, item_lock=False, + window=Munch(container_slots=27, contents={ + 0: Slot(True, target_id, 1), + }), + maximum_supply_slots=33, game=FakeGame(), + ) + state = GrabSuppliesStates(g) + state.target_items = {target_id} + state.maximum_stacks = 1 + state.grab_items() + + self.assertEqual(swaps, [(27, 36)]) + self.assertTrue(g.item_lock) + self.assertEqual(state.count, 0) + finally: + items.NEEDED_ITEMS = previous_needed + items.WANTED_ITEMS = previous_wanted + + def test_full_ground_pickup_drops_largest_nonessential_stack(self): + def run(): + dropped = [] + + class FakeGame: + def drop_inventory_slot(self, slot, whole_stack=True): + dropped.append((slot, whole_stack)) + return True + + g = Munch( + inv=self.make_inventory(), drop_waiting=None, path=[], + game=FakeGame(), + ) + state = GrabSuppliesStates(g) + state.target_items = {items.NETHERWART_ID} + self.assertTrue(state._drop_stack_for_ground_pickup()) + self.assertEqual(dropped, [(41, True)]) + self.assertIs(state.state.__func__, + state.wait_for_inventory_space.__func__) + + self.with_needed_axes(run) + + +if __name__ == '__main__': + unittest.main()