Files
minecraft-bot/mosfet/jobs/combat.py
T
2026-11-19 01:06:19 +00:00

711 lines
29 KiB
Python

"""Close-range melee combat against loaded mobs and players."""
import math
import time
from mosfet import utils
from mosfet.info import blocks, items, mobs
class CombatStates:
ACQUIRE_RADIUS = 32.0
ATTACK_REACH = 3.0
ATTACK_INTERVAL = 0.7
PATH_RETRY_INTERVAL = 1.0
PATH_SEARCH_TIMEOUT = 0.1
TARGET_GROUND_SEARCH_DEPTH = 8
EVASION_PATH_TIMEOUT = 0.1
EVASION_INTERVAL = 0.9
PROJECTILE_LOOKAHEAD = 0.7
PROJECTILE_MISS_DISTANCE = 1.35
RUSH_DURATION = 1.0
RUSH_COOLDOWN = 0.9
RECENT_SHOT_WINDOW = 0.8
PROJECTILE_SOURCE_RADIUS = 3.0
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.monitor_only = False
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
self.evading = False
self.next_evasion_at = 0.0
self.evasion_side = 1
self.evasion_count = 0
self.rushing = False
self.rush_until = 0.0
self.next_rush_at = 0.0
self.rush_count = 0
self.seen_projectile_ids = set()
if self.sleep_first:
sleep = self.g.job.sleep_with_bed_states
sleep.refuge_sign = None
sleep.force_new_bed = False
sleep.state = sleep.init
self._log('night detected; trying to sleep before combat')
self.state = self.sleep_before_combat
return
self._select_sword()
self.state = self.find_target
def _select_sword(self):
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')
def sleep_before_combat(self):
sleep = self.g.job.sleep_with_bed_states
sleep.run()
if sleep.state == sleep.done:
self._log('sleep attempt finished; starting combat')
sleep.state = sleep.idle
self.sleep_first = False
self._select_sword()
self.state = self.find_target
def _target_entities(self):
key = 'players' if self.target_players else 'mobs'
return self.g.get(key, {})
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):
if self.target_players:
player_uuid = str(mob.get('player_uuid', ''))
return self.g.get('player_names', {}).get(player_uuid, 'player')
return mobs.MOB_NAMES.get(mob.get('type'), 'unknown mob')
def find_target(self):
search_started = time.monotonic()
candidates = []
ranged_watch_candidates = []
for entity_id, mob in self._target_entities().items():
if entity_id in self.skipped_ids:
continue
if (self.allowed_target_ids is not None and
entity_id not in self.allowed_target_ids):
continue
if self.target_players:
if entity_id == self.g.get('eid'):
continue
else:
mob_type = mob.get('type')
if (mob_type not in mobs.MOB_NAMES or
mob_type in mobs.NON_MOB_ENTITY_IDS or
(self.hostile_only and
mob_type not in mobs.EVIL_IDS)):
continue
distance = self._distance(mob)
if distance <= self.ACQUIRE_RADIUS:
candidates.append((distance, entity_id, mob))
elif (self.allowed_target_ids is None and
self._has_ranged_weapon(mob)):
ranged_watch_candidates.append((distance, entity_id, mob))
search_elapsed = time.monotonic() - search_started
self.monitor_only = False
if not candidates and ranged_watch_candidates:
candidates = ranged_watch_candidates
self.monitor_only = True
if not candidates:
noun = 'players' if self.target_players else 'mobs'
self._log('no {} or ranged threats in loaded entities '
'(scan {:.3f}s)'.format(noun, search_elapsed))
self.cleanup()
return
distance, self.target_id, target = min(candidates)
self.monitor_only = distance > self.ACQUIRE_RADIUS
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.evading = False
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 _has_ranged_weapon(self, target):
if target.get('main_hand_item_id') in items.RANGED_WEAPON_IDS:
return True
if self.target_players:
return any(
stack.item_id in items.RANGED_WEAPON_IDS
for slot, stack in (target.get('equipment') or {}).items()
if slot in (0, 1) and stack.present)
return target.get('type') in mobs.RANGED_ATTACKER_IDS
def _aiming_at_player(self, target):
yaw = target.get('yaw')
if yaw is None:
return False
player = self.g.pos
dx, dz = player.x - target.x, player.z - target.z
if math.hypot(dx, dz) < 0.01:
return True
desired_yaw = math.degrees(math.atan2(-dx, dz))
yaw_delta = (float(yaw) - desired_yaw + 180.0) % 360.0 - 180.0
return abs(yaw_delta) <= 40.0
def _incoming_projectile(self, target=None):
player = self.g.pos
now = time.monotonic()
best = None
for entity_id, projectile in self.g.get('mobs', {}).items():
if projectile.get('type') not in mobs.RANGED_PROJECTILE_IDS:
continue
spawned_at = projectile.get('spawned_at')
spawn = tuple(projectile.get('spawn_' + axis)
for axis in ('x', 'y', 'z'))
if (target is not None and
entity_id not in self.seen_projectile_ids and
self._has_ranged_weapon(target) and
self._aiming_at_player(target) and
spawned_at is not None and
0.0 <= now - spawned_at <= self.RECENT_SHOT_WINDOW and
all(value is not None for value in spawn) and
utils.phyp((target.x, target.y + 1.0, target.z), spawn)
<= self.PROJECTILE_SOURCE_RADIUS):
self.seen_projectile_ids.add(entity_id)
return projectile, 0.0, 0.0
px, py, pz = self._coordinates(projectile)
relative = (player.x - px, player.y + 0.9 - py, player.z - pz)
velocity_time = projectile.get('velocity_updated_at')
velocity = tuple(projectile.get('velocity_' + axis)
for axis in ('x', 'y', 'z'))
if (velocity_time is None or now - velocity_time > 0.5 or
any(component is None for component in velocity)):
distance = utils.hypot(*relative)
if distance <= 2.0:
candidate = (projectile, 0.0, distance)
if best is None or candidate[2] < best[2]:
best = candidate
continue
speed_squared = sum(component * component for component in velocity)
if speed_squared < 1e-6:
continue
time_to_closest = sum(relative[i] * velocity[i]
for i in range(3)) / speed_squared
if not 0.0 <= time_to_closest <= self.PROJECTILE_LOOKAHEAD:
continue
miss = utils.hypot(*(
relative[i] - velocity[i] * time_to_closest
for i in range(3)))
if miss <= self.PROJECTILE_MISS_DISTANCE and (
best is None or miss < best[2]):
best = (projectile, time_to_closest, miss)
return best
def _recent_target_shot(self, target, now):
if not self._has_ranged_weapon(target):
return None
shooter = (target.x, target.y + 1.0, target.z)
for entity_id, projectile in self.g.get('mobs', {}).items():
if (entity_id in self.seen_projectile_ids or
projectile.get('type') not in mobs.RANGED_PROJECTILE_IDS):
continue
spawned_at = projectile.get('spawned_at')
if (spawned_at is None or
not 0.0 <= now - spawned_at <= self.RECENT_SHOT_WINDOW):
continue
spawn = tuple(projectile.get('spawn_' + axis)
for axis in ('x', 'y', 'z'))
if (any(value is None for value in spawn) or
utils.phyp(shooter, spawn) > self.PROJECTILE_SOURCE_RADIUS):
continue
self.seen_projectile_ids.add(entity_id)
return projectile
return None
def _start_rush(self, target, projectile, now):
self.rushing = True
self.rush_until = now + self.RUSH_DURATION
self.next_rush_at = now + self.RUSH_COOLDOWN
self.rush_count += 1
self.evading = False
self.g.path = []
self.path_target = None
self.next_path_at = 0.0
self.g.game.set_sprinting(True)
projectile_name = mobs.MOB_NAMES.get(
projectile.get('type'), 'projectile')
self._log('{}#{} fired {}; rushing for {:.1f}s'.format(
self._describe(target), self.target_id, projectile_name,
self.RUSH_DURATION))
self._path_to_target(target)
def _stop_rush(self):
if not self.rushing:
return
self.rushing = False
self.rush_until = 0.0
connection = self.g.get('connection')
if connection is not None and connection.connected:
self.g.game.set_sprinting(False)
else:
self.g.sprinting = False
self._log('rush window ended')
def _try_evasion(self, target, now, advance=True,
projectile_only=False):
if self.rushing and now < self.rush_until:
return False
if self.evading and self.g.path:
return False
if now < self.next_evasion_at:
return False
projectile = self._incoming_projectile(target)
ranged_weapon = (not projectile_only and
self._has_ranged_weapon(target))
facing = ranged_weapon and self._aiming_at_player(target)
aiming_with_sight = facing and self._line_of_sight(target)
if projectile is None and not aiming_with_sight:
return False
player = self.g.pos
if projectile is not None:
threat, eta, miss = projectile
velocity = (threat.get('velocity_x'), threat.get('velocity_z'))
if (any(component is None for component in velocity) or
math.hypot(*velocity) < 0.01):
velocity = (player.x - threat.x, player.z - threat.z)
reason = 'incoming {}#{} in {:.2f}s (closest {:.2f})'.format(
mobs.MOB_NAMES.get(threat.get('type'), 'projectile'),
threat.get('entity_id', '?'), eta, miss)
else:
velocity = (player.x - target.x, player.z - target.z)
reason = '{}#{} aiming with ranged weapon'.format(
self._describe(target), self.target_id)
magnitude = math.hypot(*velocity)
if magnitude < 0.01:
return False
perpendicular = (-velocity[1] / magnitude, velocity[0] / magnitude)
toward = (target.x - player.x, target.z - player.z)
toward_length = math.hypot(*toward)
if toward_length < 0.01:
return False
toward = (toward[0] / toward_length, toward[1] / toward_length)
start = utils.pint(player)
deadline = time.monotonic() + self.EVASION_PATH_TIMEOUT
routes = []
seen = set()
maneuvers = (
((2.0, 2.0, self.evasion_side),
(2.0, 3.5, -self.evasion_side),
(2.75, 2.0, -self.evasion_side),
(2.75, 3.5, self.evasion_side)) if advance else
((0.0, 2.5, self.evasion_side),
(0.0, 3.5, -self.evasion_side),
(0.0, 4.0, self.evasion_side))
)
for forward_step, lateral, side in maneuvers:
x = math.floor(
player.x + toward[0] * forward_step +
perpendicular[0] * lateral * side)
z = math.floor(
player.z + toward[1] * forward_step +
perpendicular[1] * lateral * side)
destination = self._grounded_approach_block(
x, z, start[1])
if destination is None or destination == start or destination in seen:
continue
seen.add(destination)
remaining = deadline - time.monotonic()
if remaining <= 0:
break
route = self.g.world.path_to_place(
start, destination, timeout=remaining)
if not route or len(route) <= 1:
continue
cover = False
check = getattr(
self.g.world, '_has_cache_line_of_sight', None)
if callable(check):
source = (target.x, target.y + 1.5, target.z)
endpoint = (destination[0] + 0.5,
destination[1] + 1.0,
destination[2] + 0.5)
cover = not check(source, endpoint, destination)
after_distance = math.hypot(
target.x - (destination[0] + 0.5),
target.z - (destination[2] + 0.5))
progress = toward_length - after_distance
if advance and progress <= 0.4:
continue
rank = (0 if cover else 1, -progress if advance else 0,
len(route))
routes.append((rank, destination, route, cover, progress))
if not routes:
self.next_evasion_at = now + 0.5
self._log('ranged threat detected ({}) but no advancing dodge '
'route found within {:.2f}s'.format(
reason, self.EVASION_PATH_TIMEOUT))
return False
(_rank, destination, route, has_cover, advance) = min(routes)
self.g.path = route
self.path_target = None
self.evading = True
self.evasion_count += 1
self.evasion_side *= -1
self.next_evasion_at = now + self.EVASION_INTERVAL
self.best_distance = self._distance(target)
self.last_progress_at = now
self._log('evasive advance from {} to {} ({} nodes, {:.1f} blocks '
'closer, cover={})'.format(
reason, destination, len(route), advance, has_cover))
return True
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._target_entities().get(self.target_id)
if target is None:
self._log_target_end('lost target entity')
self._stop_rush()
self.target_id = None
self.g.path = []
self.evading = False
self.state = self.find_target
return
distance = self._distance(target)
now = time.monotonic()
if distance > self.ACQUIRE_RADIUS:
if self._has_ranged_weapon(target):
if not self.monitor_only:
self._log('target outside 32 blocks; monitoring ranged '
'threats without pursuing')
self._stop_rush()
self.monitor_only = True
self.g.path = []
self.path_target = None
self.evading = False
if self.evading and self.g.path:
return
if self.evading:
self.evading = False
if self._try_evasion(
target, now, advance=False, projectile_only=True):
return
self.g.path = []
self.path_target = None
return
self._log_target_end('target left the 32-block radius')
self._stop_rush()
self.target_id = None
self.g.path = []
self.evading = False
self.state = self.find_target
return
if self.monitor_only:
self._log('target back within 32 blocks; resuming pursuit')
self.monitor_only = False
self.g.path = []
self.path_target = None
self.next_path_at = 0.0
if self.rushing and now >= self.rush_until:
self._stop_rush()
if (distance > self.ATTACK_REACH and now >= self.next_rush_at):
shot = self._recent_target_shot(target, now)
if shot is not None:
self._start_rush(target, shot, now)
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._stop_rush()
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
if self.evading:
if self.g.path:
return
self.evading = False
self.path_target = None
self.next_path_at = 0.0
if (distance > self.ATTACK_REACH and
self._try_evasion(target, now)):
return
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._stop_rush()
self._log('combat finished after {:.2f}s: {} targets, {} attack '
'attempts, {} evasions, {} rushes'.format(
total_elapsed, self.targets_engaged,
self.total_attacks, self.evasion_count, self.rush_count))
self.g.path = []
self.g.look_at = None
self.target_id = None
self.evading = False
self.hostile_only = False
self.sleep_first = False
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, target_players=False):
self.g = global_state
self.target_players = target_players
self.allowed_target_ids = None
self.hostile_only = False
self.sleep_first = False
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
self.evading = False
self.next_evasion_at = 0.0
self.evasion_side = 1
self.evasion_count = 0
self.rushing = False
self.rush_until = 0.0
self.next_rush_at = 0.0
self.rush_count = 0
self.seen_projectile_ids = set()