diff --git a/mosfet/commands.py b/mosfet/commands.py index bd3163b..f870471 100644 --- a/mosfet/commands.py +++ b/mosfet/commands.py @@ -472,6 +472,11 @@ class Commands: self.g.game.respawn() reply = 'ok' + ## 1combat - attacks mobs within 16 blocks + if command == 'combat': + self.g.job.state = self.g.job.combat + reply = 'ok' + ## 1sleep [new] - use a bed; `new` forces bed placement if command == 'sleep': self.g.job.sleep_with_bed_states.force_new_bed = ( diff --git a/mosfet/game.py b/mosfet/game.py index 19b9b1f..5e8cb4d 100644 --- a/mosfet/game.py +++ b/mosfet/game.py @@ -26,8 +26,8 @@ from mosfet.protocol.packets import ( from mosfet.protocol.types import Slot from mosfet.protocol.modern import ( - ClientCommandPacket, PlayerCommandPacket, PlayerInputPacket, - UpdateTimePacket, UseItemPacket, + AttackEntityPacket, ClientCommandPacket, PlayerCommandPacket, + PlayerInputPacket, UpdateTimePacket, UseItemPacket, ) from mosfet import utils @@ -1008,6 +1008,11 @@ class Game(LegacyGame): """Ask the 26.3 server to broadcast a main-hand punch animation.""" self._send_action(PunchPacket()) + def attack_entity(self, entity_id): + """Attack an entity with the main-hand item, then swing visibly.""" + self._send_action(AttackEntityPacket(entity_id=int(entity_id))) + self.animate() + def break_block(self, location): location = tuple(int(value) for value in location) block_id = self.g.chunks.get_block_at(*location) diff --git a/mosfet/info/items.py b/mosfet/info/items.py index 08b068e..458c7cc 100644 --- a/mosfet/info/items.py +++ b/mosfet/info/items.py @@ -45,6 +45,10 @@ BED_IDS = get_set(BEDS) SHOVEL_IDS = get_set(SHOVELS) AXE_IDS = get_set(AXES) FOOD_IDS = get_set(FOOD) +SWORD_IDS = { + item['protocol_id'] for name, item in ITEMS.items() + if name.endswith('_sword') +} SAPLING_IDS = get_set(SAPLINGS) LOG_IDS = get_set(LOGS) _LOG_FAMILY_ITEM_IDS = {} diff --git a/mosfet/info/mobs.py b/mosfet/info/mobs.py index 1d16f2e..89dd701 100644 --- a/mosfet/info/mobs.py +++ b/mosfet/info/mobs.py @@ -46,3 +46,32 @@ EVIL_IDS = { } MOB_NAMES = {entity['protocol_id']: name.removeprefix('minecraft:') for name, entity in MOBS.items()} + +# Entity registry entries that are not living mobs and cannot be valid melee +# targets (projectiles can otherwise remain in the entity map after launch). +_BOAT_TYPES = ( + 'acacia', 'bamboo', 'birch', 'cherry', 'dark_oak', 'jungle', + 'mangrove', 'oak', 'pale_oak', 'poplar', 'spruce', +) +NON_MOB_ENTITY_NAMES = { + *(name + suffix for name in _BOAT_TYPES + for suffix in ('_boat', '_chest_boat')), + 'bamboo_raft', 'bamboo_chest_raft', + 'area_effect_cloud', 'armor_stand', 'arrow', 'block_display', + 'breeze_wind_charge', 'chest_minecart', 'command_block_minecart', + 'dragon_fireball', 'egg', 'end_crystal', 'ender_pearl', 'evoker_fangs', + 'experience_bottle', 'experience_orb', 'eye_of_ender', 'falling_block', + 'fireball', 'firework_rocket', 'fishing_bobber', 'furnace_minecart', + 'glow_item_frame', 'hopper_minecart', 'interaction', 'item', + 'item_display', 'item_frame', 'leash_knot', 'lightning_bolt', + 'lingering_potion', 'llama_spit', 'mannequin', 'marker', 'minecart', + 'ominous_item_spawner', 'painting', 'player', 'shulker_bullet', + 'small_fireball', 'snowball', 'spawner_minecart', 'spectral_arrow', + 'splash_potion', 'text_display', 'tnt', 'tnt_minecart', 'trident', + 'wind_charge', 'wither_skull', +} +NON_MOB_ENTITY_IDS = { + MOBS['minecraft:' + name]['protocol_id'] + for name in NON_MOB_ENTITY_NAMES + if 'minecraft:' + name in MOBS +} diff --git a/mosfet/job.py b/mosfet/job.py index 4a39742..e176c44 100644 --- a/mosfet/job.py +++ b/mosfet/job.py @@ -18,6 +18,7 @@ from mosfet.info import mobs from mosfet.jobs import ( cache_items, clear_leaves, + combat, eat_food, fill_blocks, find_gapple, @@ -35,6 +36,7 @@ from mosfet.jobs import ( for module in [ cache_items, clear_leaves, + combat, eat_food, fill_blocks, find_gapple, @@ -263,6 +265,7 @@ class JobStates(LegacyJobStates): """26.3 facade for migrated gathering and farming workflows.""" def __init__(self, global_state): self.g = global_state + self.combat_states = combat.CombatStates(global_state) self.gather_wood_states = gather_wood.GatherWoodStates(global_state) self.gather_crop_states = gather_crop.GatherCropStates(global_state) self.gather_wart_states = gather_wart.GatherWartStates(global_state) @@ -327,6 +330,9 @@ class JobStates(LegacyJobStates): self.cache_items_states ] + def combat(self): + return [self.combat_states] + def eat(self): return [self.eat_food_states] @@ -354,6 +360,8 @@ class JobStates(LegacyJobStates): self.g.yaw_target_override = None if self.sleep_with_bed_states.state == self.sleep_with_bed_states.sleep_bed: self.g.game.leave_bed() + self.combat_states.state = self.combat_states.idle + self.combat_states.target_id = None self.gather_wood_states.state = self.gather_wood_states.idle self.gather_crop_states.state = self.gather_crop_states.idle self.gather_sand_states.state = self.gather_sand_states.idle diff --git a/mosfet/jobs/check_threats.py b/mosfet/jobs/check_threats.py index b352c36..7e6aa04 100644 --- a/mosfet/jobs/check_threats.py +++ b/mosfet/jobs/check_threats.py @@ -248,6 +248,11 @@ class ThreatMonitor: if job is None or job.state == job.idle: self.next_scan_at = 0.0 return + if getattr(job.state, '__name__', None) == 'combat': + # Combat deliberately engages hostile mobs, so evacuation must not + # suspend the combat job before it can attack them. + self.next_scan_at = 0.0 + return now = time.monotonic() if now < self.next_scan_at: return diff --git a/mosfet/jobs/combat.py b/mosfet/jobs/combat.py new file mode 100644 index 0000000..9600488 --- /dev/null +++ b/mosfet/jobs/combat.py @@ -0,0 +1,338 @@ +"""Close-range melee combat against loaded mobs.""" +import time + +from mosfet import utils +from mosfet.info import blocks, items, mobs + + +class CombatStates: + ACQUIRE_RADIUS = 16.0 + ATTACK_REACH = 3.8 + ATTACK_INTERVAL = 0.7 + PATH_RETRY_INTERVAL = 1.0 + PATH_SEARCH_TIMEOUT = 0.1 + TARGET_GROUND_SEARCH_DEPTH = 8 + + def idle(self): + return None + + def _log(self, message): + elapsed = (time.monotonic() - self.started_at + if self.started_at is not None else 0.0) + print('[combat +{:.2f}s] {}'.format(elapsed, message), flush=True) + + def _log_target_end(self, reason): + if self.target_id is None: + return + elapsed = (time.monotonic() - self.target_started_at + if self.target_started_at is not None else 0.0) + self._log('{} {}#{} after {:.2f}s ({} attack attempts)'.format( + reason, self.target_name, self.target_id, elapsed, + self.target_attacks)) + + def init(self): + self.target_id = None + self.path_target = None + self.next_path_at = 0.0 + self.next_attack_at = 0.0 + self.failed_paths = 0 + self.skipped_ids = set() + self.started_at = time.monotonic() + self.targets_engaged = 0 + self.total_attacks = 0 + self.target_started_at = None + self.target_name = None + self.target_attacks = 0 + self.last_attack_at = None + self.best_distance = None + self.last_progress_at = None + self.last_los_report_at = 0.0 + + main_hand_sword = any( + 9 <= slot <= 44 and getattr(stack, 'present', False) and + stack.item_id in items.SWORD_IDS + for slot, stack in self.g.inv.items()) + if main_hand_sword: + self.g.game.select_item(items.SWORD_IDS) + self._log('selected sword') + else: + self._log('no main-hand sword available; fighting unarmed') + self.state = self.find_target + + def _coordinates(self, mob): + return (float(mob.x), float(mob.y), float(mob.z)) + + def _distance(self, mob): + return utils.phyp(self.g.pos, self._coordinates(mob)) + + def _standable_foot_block(self, x, feet_y, z): + world = self.g.world + support = world.block_at(x, feet_y - 1, z) + foot = world.block_at(x, feet_y, z) + head = world.block_at(x, feet_y + 1, z) + return ( + support is not None and support not in blocks.NON_SOLID_IDS and + support not in blocks.AVOID_IDS and + foot in blocks.NON_SOLID_IDS and foot not in blocks.AVOID_IDS and + head in blocks.NON_SOLID_IDS and head not in blocks.AVOID_IDS + ) + + def _grounded_target_block(self, mob): + """Use the target's supporting surface instead of its jump height.""" + x, y, z = utils.pint(self._coordinates(mob)) + for feet_y in range(y, y - self.TARGET_GROUND_SEARCH_DEPTH - 1, -1): + if self._standable_foot_block(x, feet_y, z): + return (x, feet_y, z) + return (x, y, z) + + def _grounded_approach_block(self, x, z, reference_y): + vertical_offsets = (0, 1, -1, 2, -2, 3, -3, -4, -5, -6, -7, -8) + for offset in vertical_offsets: + feet_y = reference_y + offset + if self._standable_foot_block(x, feet_y, z): + return (x, feet_y, z) + return None + + def _distance_from_path_target(self, mob): + if self.path_target is None: + return float('inf') + approach = tuple(value + 0.5 for value in self.path_target) + x, feet_y, z = self._grounded_target_block(mob) + grounded_target = (mob.x, float(feet_y), mob.z) + return utils.phyp(approach, grounded_target) + + def _describe(self, mob): + return mobs.MOB_NAMES.get(mob.get('type'), 'unknown mob') + + def find_target(self): + search_started = time.monotonic() + candidates = [] + for entity_id, mob in self.g.get('mobs', {}).items(): + if entity_id in self.skipped_ids: + continue + mob_type = mob.get('type') + if (mob_type not in mobs.MOB_NAMES or + mob_type in mobs.NON_MOB_ENTITY_IDS): + continue + distance = self._distance(mob) + if distance <= self.ACQUIRE_RADIUS: + candidates.append((distance, entity_id, mob)) + + search_elapsed = time.monotonic() - search_started + if not candidates: + self._log('no mobs within 16 blocks (scan {:.3f}s)'.format( + search_elapsed)) + self.cleanup() + return + + distance, self.target_id, target = min(candidates) + self.failed_paths = 0 + self.path_target = None + self.next_path_at = 0.0 + self.next_attack_at = 0.0 + self.target_started_at = time.monotonic() + self.target_name = self._describe(target) + self.target_attacks = 0 + self.last_attack_at = None + self.best_distance = distance + self.last_progress_at = self.target_started_at + self.last_los_report_at = 0.0 + self.targets_engaged += 1 + self._log('targeting {}#{} at {:.1f} blocks (scan {:.3f}s)'.format( + self.target_name, self.target_id, distance, search_elapsed)) + self.state = self.engage + + def _line_of_sight(self, target): + check = getattr(self.g.world, '_has_cache_line_of_sight', None) + if not callable(check): + return True + player = self.g.pos + eye = (player.x, player.y + 1.62, player.z) + x, y, z = self._coordinates(target) + return check(eye, (x, y + 0.9, z), utils.pint((x, y, z))) + + def _path_to_target(self, target): + mob_block = utils.pint(self._coordinates(target)) + target_block = self._grounded_target_block(target) + if target_block[1] != mob_block[1]: + self._log('target is airborne at y={:.2f}; using ground level ' + 'y={} for approach planning'.format( + target.y, target_block[1])) + start = utils.pint(self.g.pos) + offsets = ( + (1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1), + (1, 0, 1), (1, 0, -1), (-1, 0, 1), (-1, 0, -1), + ) + routes = [] + slowest_call = (0.0, None) + search_started = time.monotonic() + deadline = search_started + self.PATH_SEARCH_TIMEOUT + offsets_checked = 0 + grounded_candidates = 0 + candidates_checked = 0 + for offset in offsets: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + offsets_checked += 1 + destination = self._grounded_approach_block( + target_block[0] + offset[0], target_block[2] + offset[2], + target_block[1]) + if destination is None: + continue + grounded_candidates += 1 + call_started = time.monotonic() + route = self.g.world.path_to_place( + start, destination, timeout=remaining) + call_elapsed = time.monotonic() - call_started + candidates_checked += 1 + if call_elapsed > slowest_call[0]: + slowest_call = (call_elapsed, destination) + if route is not None: + routes.append((len(route), destination, route)) + search_elapsed = time.monotonic() - search_started + self._log('path search: {}/{} approach spots grounded, {} paths ' + 'searched in {:.3f}s (budget {:.3f}s), slowest {:.3f}s at ' + '{}, {}/{} reachable'.format( + grounded_candidates, offsets_checked, + candidates_checked, search_elapsed, + self.PATH_SEARCH_TIMEOUT, slowest_call[0], + slowest_call[1], len(routes), candidates_checked)) + if routes: + route_length, self.path_target, self.g.path = min(routes) + self.failed_paths = 0 + self._log('approaching {}#{} via {} nodes to {}'.format( + self._describe(target), self.target_id, route_length, + self.path_target)) + else: + self.failed_paths += 1 + self.g.path = [] + self.path_target = None + if self.failed_paths >= 5: + self._log('cannot reach {}#{}; skipping after {} searches'.format( + self._describe(target), self.target_id, self.failed_paths)) + self.skipped_ids.add(self.target_id) + self.target_id = None + self.state = self.find_target + return + self._log('no path to {}#{}; retry {}/5'.format( + self._describe(target), self.target_id, self.failed_paths)) + self.next_path_at = time.monotonic() + self.PATH_RETRY_INTERVAL + + def engage(self): + target = self.g.get('mobs', {}).get(self.target_id) + if target is None: + self._log_target_end('lost target entity') + self.target_id = None + self.g.path = [] + self.state = self.find_target + return + + distance = self._distance(target) + now = time.monotonic() + if distance > self.ACQUIRE_RADIUS: + self._log_target_end('target left the 16-block radius') + self.target_id = None + self.g.path = [] + self.state = self.find_target + return + + if self.best_distance is None or distance < self.best_distance - 0.5: + self.best_distance = distance + self.last_progress_at = now + elif (self.last_progress_at is not None and + now - self.last_progress_at >= 5.0): + self._log('no approach progress for {:.1f}s (distance {:.1f}, ' + '{} path nodes)'.format( + now - self.last_progress_at, distance, + len(self.g.path))) + self.last_progress_at = now + + x, y, z = self._coordinates(target) + self.g.look_at = (x - 0.5, y + 0.4, z - 0.5) + has_line_of_sight = False + if distance <= self.ATTACK_REACH: + has_line_of_sight = self._line_of_sight(target) + if has_line_of_sight: + self.g.path = [] + if now >= self.next_attack_at: + self.g.game.attack_entity(self.target_id) + self.target_attacks += 1 + self.total_attacks += 1 + gap = (None if self.last_attack_at is None else + now - self.last_attack_at) + gap_text = ('first' if gap is None else + '{:.3f}s since previous'.format(gap)) + self._log('attack attempt #{} on {}#{} at {:.1f} blocks ' + '({} since previous, target age {:.2f}s)'.format( + self.target_attacks, self.target_name, + self.target_id, distance, gap_text, + now - self.target_started_at)) + self.last_attack_at = now + self.next_attack_at = now + self.ATTACK_INTERVAL + return + if now - self.last_los_report_at >= 2.0: + self._log('within attack reach ({:.1f}) but line of sight is ' + 'blocked; path has {} nodes'.format( + distance, len(self.g.path))) + self.last_los_report_at = now + + approach_distance = self._distance_from_path_target(target) + if (self.path_target is not None and + approach_distance > self.ATTACK_REACH): + self._log('target moved {:.1f} blocks from planned strike point; ' + 'replanning'.format(approach_distance)) + self.g.path = [] + self.path_target = None + self.next_path_at = 0.0 + + if (not self.g.path and now >= self.next_path_at and + (self.path_target is None or + distance > self.ATTACK_REACH or not has_line_of_sight)): + self._path_to_target(target) + + def cleanup(self): + total_elapsed = (time.monotonic() - self.started_at + if self.started_at is not None else 0.0) + self._log('combat finished after {:.2f}s: {} targets, {} attack ' + 'attempts'.format(total_elapsed, self.targets_engaged, + self.total_attacks)) + self.g.path = [] + self.g.look_at = None + self.target_id = None + self.state = self.done + job = self.g.get('job') + if job is not None and getattr(job.state, '__name__', None) == 'combat': + job.state = job.idle + + def done(self): + return None + + def run(self): + state = self.state + started = time.monotonic() + state() + duration = time.monotonic() - started + if duration >= 0.25: + self._log('state {} took {:.3f}s'.format( + getattr(state, '__name__', 'unknown'), duration)) + + def __init__(self, global_state): + self.g = global_state + self.state = self.idle + self.target_id = None + self.path_target = None + self.next_path_at = 0.0 + self.next_attack_at = 0.0 + self.failed_paths = 0 + self.skipped_ids = set() + self.started_at = None + self.targets_engaged = 0 + self.total_attacks = 0 + self.target_started_at = None + self.target_name = None + self.target_attacks = 0 + self.last_attack_at = None + self.best_distance = None + self.last_progress_at = None + self.last_los_report_at = 0.0 diff --git a/mosfet/path.py b/mosfet/path.py index aa59af7..bb8990b 100644 --- a/mosfet/path.py +++ b/mosfet/path.py @@ -116,11 +116,13 @@ HALF_PARKOUR = { # larger started being slower BLOCK_CACHE_SIZE = 2**14 +DEFAULT_PATH_TIMEOUT = 2.0 class Pathfinder(AStar): - def __init__(self, g): + def __init__(self, g, timeout=DEFAULT_PATH_TIMEOUT): self.g = g self.chunks = g.chunks + self.timeout = max(0.0, float(timeout)) self.start_time = time.monotonic() @functools.lru_cache(maxsize=BLOCK_CACHE_SIZE) @@ -322,7 +324,7 @@ class Pathfinder(AStar): return True, None def neighbors(self, node): - if time.monotonic() - self.start_time > 2.0: + if time.monotonic() - self.start_time > self.timeout: raise AStarTimeout results = [] diff --git a/mosfet/protocol/modern.py b/mosfet/protocol/modern.py index 6983d0a..d02ab4b 100644 --- a/mosfet/protocol/modern.py +++ b/mosfet/protocol/modern.py @@ -32,6 +32,13 @@ class UpdateTimePacket(Packet): }) +class AttackEntityPacket(Packet): + """Attack an entity using the selected main-hand item (protocol 777).""" + id = 0x01 + packet_name = 'attack entity' + definition = [{'entity_id': VarInt}] + + class PlayerInputPacket(Packet): """Serverbound key state, including sneak for container-safe placement.""" id = 0x2B diff --git a/mosfet/world.py b/mosfet/world.py index 514523e..f76dd9f 100644 --- a/mosfet/world.py +++ b/mosfet/world.py @@ -668,7 +668,7 @@ class World: result.append(utils.padd(tree, offset)) return result - def path_to_place(self, start, place): + def path_to_place(self, start, place, timeout=path.DEFAULT_PATH_TIMEOUT): policies = self._active_work_policies() for policy in policies: if not self._inside_sign_policy(place, policy): @@ -677,7 +677,7 @@ class World: policy['position']), flush=True) return None - maze_solver = path.Pathfinder(self.g) + maze_solver = path.Pathfinder(self.g, timeout=timeout) try: solution = maze_solver.astar(start, place) if not solution: diff --git a/tests/test_attack_packet.py b/tests/test_attack_packet.py new file mode 100644 index 0000000..d8445c8 --- /dev/null +++ b/tests/test_attack_packet.py @@ -0,0 +1,44 @@ +import unittest + +from munch import Munch +from minecraft.networking.modern import ClientTickEnd, PunchPacket +from minecraft.networking.packets import PacketBuffer + +from mosfet.game import Game +from mosfet.protocol.modern import AttackEntityPacket + + +class FakeConnection: + def __init__(self): + self.packets = [] + + def write_packet(self, packet, force=False): + self.packets.append((packet, force)) + + +class AttackPacketTests(unittest.TestCase): + def test_attack_packet_encodes_protocol_777_entity_id(self): + packet = AttackEntityPacket(entity_id=300) + payload = PacketBuffer() + + packet.write_fields(payload) + + self.assertEqual(packet.id, 0x01) + self.assertEqual(payload.get_writable(), bytes.fromhex('ac02')) + + def test_game_attack_sends_attack_and_visible_main_hand_swing(self): + connection = FakeConnection() + game = Game.__new__(Game) + game.g = Munch(connection=connection) + + game.attack_entity(17) + + self.assertEqual( + [type(packet) for packet, _force in connection.packets], + [AttackEntityPacket, ClientTickEnd, PunchPacket, ClientTickEnd]) + self.assertEqual(connection.packets[0][0].entity_id, 17) + self.assertTrue(all(force for _packet, force in connection.packets)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_door_navigation.py b/tests/test_door_navigation.py index bd4e585..0ecc4ea 100644 --- a/tests/test_door_navigation.py +++ b/tests/test_door_navigation.py @@ -5,7 +5,8 @@ from munch import Munch from mosfet.bot import _recover_invalid_path from mosfet.game import Game from mosfet.info import blocks -from mosfet.path import Pathfinder +from mosfet.path import AStarTimeout, Pathfinder +from mosfet.world import World class FakeChunks: @@ -44,6 +45,37 @@ class DoorNavigationTests(unittest.TestCase): finder = Pathfinder(g) self.assertFalse(finder.bair((1, 64, 0))) + def test_world_pathfinder_receives_custom_timeout(self): + calls = [] + + class FakePathfinder: + def __init__(self, global_state, timeout): + calls.append((global_state, timeout)) + + @staticmethod + def astar(start, destination): + return [start, destination] + + world = World.__new__(World) + world.g = Munch(job=None) + with patch('mosfet.world.path.Pathfinder', FakePathfinder): + route = world.path_to_place( + (0, 64, 0), (1, 64, 0), timeout=0.1) + + self.assertEqual(route, [(0, 64, 0), (1, 64, 0)]) + self.assertEqual(calls, [(world.g, 0.1)]) + + def test_pathfinder_honors_custom_search_timeout(self): + g = Munch(chunks=FakeChunks({}), crawling=False, + unopenable_doors=set()) + with patch('mosfet.path.time.monotonic', return_value=10.0): + finder = Pathfinder(g, timeout=0.1) + + self.assertEqual(finder.timeout, 0.1) + with patch('mosfet.path.time.monotonic', return_value=10.101): + with self.assertRaises(AStarTimeout): + finder.neighbors((0, 64, 0)) + def test_path_prefix_detects_new_obstacles_and_missing_support(self): class TerrainChunks: def __init__(self):