Evade ranged weapons and rush target

This commit is contained in:
Tanner committed 2026-11-17 23:45:21 +00:00
1 parent dbd2831dda
commit 0722924263
10 files changed
+474 -14

No files matched your search

+270 -3
View File
@@ -1,4 +1,5 @@
"""Close-range melee combat against loaded mobs."""
"""Close-range melee combat against loaded mobs and players."""
import math
import time
from mosfet import utils
@@ -12,6 +13,14 @@ class CombatStates:
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
@@ -47,6 +56,15 @@ class CombatStates:
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()
main_hand_sword = any(
9 <= slot <= 44 and getattr(stack, 'present', False) and
@@ -149,6 +167,7 @@ class CombatStates:
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))
@@ -163,6 +182,218 @@ class CombatStates:
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):
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
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):
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()
ranged_weapon = 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()
for advance in (2.0, 2.75):
for lateral, side in ((2.0, self.evasion_side),
(3.5, -self.evasion_side)):
x = math.floor(
player.x + toward[0] * advance +
perpendicular[0] * lateral * side)
z = math.floor(
player.z + toward[1] * advance +
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 progress <= 0.4:
continue
routes.append((0 if cover else 1, -progress, len(route),
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
(_cover_rank, _progress_rank, _length, 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)
@@ -235,8 +466,10 @@ class CombatStates:
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
@@ -244,11 +477,21 @@ class CombatStates:
now = time.monotonic()
if distance > self.ACQUIRE_RADIUS:
self._log_target_end('target left the 16-block radius')
self._stop_rush()
self.target_id = None
self.g.path = []
self.evading = False
self.state = self.find_target
return
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
@@ -266,6 +509,7 @@ class CombatStates:
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)
@@ -289,6 +533,17 @@ class CombatStates:
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):
@@ -306,12 +561,15 @@ class CombatStates:
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'.format(total_elapsed, self.targets_engaged,
self.total_attacks))
'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.state = self.done
job = self.g.get('job')
if job is not None and getattr(job.state, '__name__', None) == 'combat':
@@ -349,3 +607,12 @@ class CombatStates:
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()