Add combat job with safe target filtering

This commit is contained in:
Tanner committed 2026-11-17 22:37:12 +00:00
1 parent 2ecaa9a30a
commit 1b9f973db3
12 files changed
+486 -7

No files matched your search

+5
View File
@@ -472,6 +472,11 @@ class Commands:
self.g.game.respawn() self.g.game.respawn()
reply = 'ok' 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 ## 1sleep [new] - use a bed; `new` forces bed placement
if command == 'sleep': if command == 'sleep':
self.g.job.sleep_with_bed_states.force_new_bed = ( self.g.job.sleep_with_bed_states.force_new_bed = (
+7 -2
View File
@@ -26,8 +26,8 @@ from mosfet.protocol.packets import (
from mosfet.protocol.types import Slot from mosfet.protocol.types import Slot
from mosfet.protocol.modern import ( from mosfet.protocol.modern import (
ClientCommandPacket, PlayerCommandPacket, PlayerInputPacket, AttackEntityPacket, ClientCommandPacket, PlayerCommandPacket,
UpdateTimePacket, UseItemPacket, PlayerInputPacket, UpdateTimePacket, UseItemPacket,
) )
from mosfet import utils from mosfet import utils
@@ -1008,6 +1008,11 @@ class Game(LegacyGame):
"""Ask the 26.3 server to broadcast a main-hand punch animation.""" """Ask the 26.3 server to broadcast a main-hand punch animation."""
self._send_action(PunchPacket()) 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): def break_block(self, location):
location = tuple(int(value) for value in location) location = tuple(int(value) for value in location)
block_id = self.g.chunks.get_block_at(*location) block_id = self.g.chunks.get_block_at(*location)
+4
View File
@@ -45,6 +45,10 @@ BED_IDS = get_set(BEDS)
SHOVEL_IDS = get_set(SHOVELS) SHOVEL_IDS = get_set(SHOVELS)
AXE_IDS = get_set(AXES) AXE_IDS = get_set(AXES)
FOOD_IDS = get_set(FOOD) 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) SAPLING_IDS = get_set(SAPLINGS)
LOG_IDS = get_set(LOGS) LOG_IDS = get_set(LOGS)
_LOG_FAMILY_ITEM_IDS = {} _LOG_FAMILY_ITEM_IDS = {}
+29
View File
@@ -46,3 +46,32 @@ EVIL_IDS = {
} }
MOB_NAMES = {entity['protocol_id']: name.removeprefix('minecraft:') MOB_NAMES = {entity['protocol_id']: name.removeprefix('minecraft:')
for name, entity in MOBS.items()} 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
}
+8
View File
@@ -18,6 +18,7 @@ from mosfet.info import mobs
from mosfet.jobs import ( from mosfet.jobs import (
cache_items, cache_items,
clear_leaves, clear_leaves,
combat,
eat_food, eat_food,
fill_blocks, fill_blocks,
find_gapple, find_gapple,
@@ -35,6 +36,7 @@ from mosfet.jobs import (
for module in [ for module in [
cache_items, cache_items,
clear_leaves, clear_leaves,
combat,
eat_food, eat_food,
fill_blocks, fill_blocks,
find_gapple, find_gapple,
@@ -263,6 +265,7 @@ class JobStates(LegacyJobStates):
"""26.3 facade for migrated gathering and farming workflows.""" """26.3 facade for migrated gathering and farming workflows."""
def __init__(self, global_state): def __init__(self, global_state):
self.g = global_state self.g = global_state
self.combat_states = combat.CombatStates(global_state)
self.gather_wood_states = gather_wood.GatherWoodStates(global_state) self.gather_wood_states = gather_wood.GatherWoodStates(global_state)
self.gather_crop_states = gather_crop.GatherCropStates(global_state) self.gather_crop_states = gather_crop.GatherCropStates(global_state)
self.gather_wart_states = gather_wart.GatherWartStates(global_state) self.gather_wart_states = gather_wart.GatherWartStates(global_state)
@@ -327,6 +330,9 @@ class JobStates(LegacyJobStates):
self.cache_items_states self.cache_items_states
] ]
def combat(self):
return [self.combat_states]
def eat(self): def eat(self):
return [self.eat_food_states] return [self.eat_food_states]
@@ -354,6 +360,8 @@ class JobStates(LegacyJobStates):
self.g.yaw_target_override = None self.g.yaw_target_override = None
if self.sleep_with_bed_states.state == self.sleep_with_bed_states.sleep_bed: if self.sleep_with_bed_states.state == self.sleep_with_bed_states.sleep_bed:
self.g.game.leave_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_wood_states.state = self.gather_wood_states.idle
self.gather_crop_states.state = self.gather_crop_states.idle self.gather_crop_states.state = self.gather_crop_states.idle
self.gather_sand_states.state = self.gather_sand_states.idle self.gather_sand_states.state = self.gather_sand_states.idle
+5
View File
@@ -248,6 +248,11 @@ class ThreatMonitor:
if job is None or job.state == job.idle: if job is None or job.state == job.idle:
self.next_scan_at = 0.0 self.next_scan_at = 0.0
return 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() now = time.monotonic()
if now < self.next_scan_at: if now < self.next_scan_at:
return return
+338
View File
@@ -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
+4 -2
View File
@@ -116,11 +116,13 @@ HALF_PARKOUR = {
# larger started being slower # larger started being slower
BLOCK_CACHE_SIZE = 2**14 BLOCK_CACHE_SIZE = 2**14
DEFAULT_PATH_TIMEOUT = 2.0
class Pathfinder(AStar): class Pathfinder(AStar):
def __init__(self, g): def __init__(self, g, timeout=DEFAULT_PATH_TIMEOUT):
self.g = g self.g = g
self.chunks = g.chunks self.chunks = g.chunks
self.timeout = max(0.0, float(timeout))
self.start_time = time.monotonic() self.start_time = time.monotonic()
@functools.lru_cache(maxsize=BLOCK_CACHE_SIZE) @functools.lru_cache(maxsize=BLOCK_CACHE_SIZE)
@@ -322,7 +324,7 @@ class Pathfinder(AStar):
return True, None return True, None
def neighbors(self, node): def neighbors(self, node):
if time.monotonic() - self.start_time > 2.0: if time.monotonic() - self.start_time > self.timeout:
raise AStarTimeout raise AStarTimeout
results = [] results = []
+7
View File
@@ -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): class PlayerInputPacket(Packet):
"""Serverbound key state, including sneak for container-safe placement.""" """Serverbound key state, including sneak for container-safe placement."""
id = 0x2B id = 0x2B
+2 -2
View File
@@ -668,7 +668,7 @@ class World:
result.append(utils.padd(tree, offset)) result.append(utils.padd(tree, offset))
return result 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() policies = self._active_work_policies()
for policy in policies: for policy in policies:
if not self._inside_sign_policy(place, policy): if not self._inside_sign_policy(place, policy):
@@ -677,7 +677,7 @@ class World:
policy['position']), flush=True) policy['position']), flush=True)
return None return None
maze_solver = path.Pathfinder(self.g) maze_solver = path.Pathfinder(self.g, timeout=timeout)
try: try:
solution = maze_solver.astar(start, place) solution = maze_solver.astar(start, place)
if not solution: if not solution:
+44
View File
@@ -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()
+33 -1
View File
@@ -5,7 +5,8 @@ from munch import Munch
from mosfet.bot import _recover_invalid_path from mosfet.bot import _recover_invalid_path
from mosfet.game import Game from mosfet.game import Game
from mosfet.info import blocks from mosfet.info import blocks
from mosfet.path import Pathfinder from mosfet.path import AStarTimeout, Pathfinder
from mosfet.world import World
class FakeChunks: class FakeChunks:
@@ -44,6 +45,37 @@ class DoorNavigationTests(unittest.TestCase):
finder = Pathfinder(g) finder = Pathfinder(g)
self.assertFalse(finder.bair((1, 64, 0))) 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): def test_path_prefix_detects_new_obstacles_and_missing_support(self):
class TerrainChunks: class TerrainChunks:
def __init__(self): def __init__(self):