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
@@ -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
+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