(Underdepths) Pass 5

This commit is contained in:
AlexKucera committed 2026-08-14 09:46:04 +02:00
1 parent 4a549d002f
commit 2eb2a44fa9
53 files changed
+5020

No files matched your search

View File
Whitespace-only changes.
+392
View File
@@ -0,0 +1,392 @@
"""Enemy AI dispatch.
Each turn the game loop calls ``act_enemy`` once per living enemy, after the
player acts. The function mutates ``enemy.x``/``enemy.y``/``enemy.last_known_pos``
in place and, when adjacent, resolves a melee attack through ``engine.combat``.
It never raises on valid game state.
"""
from __future__ import annotations
import random
from typing import Any
from engine.combat import roll_attack
from engine.pathfinding import find_path
from entities.enemy import Enemy
# 4-connected movement on the tile grid.
_DIRS: tuple[tuple[int, int], ...] = ((1, 0), (-1, 0), (0, 1), (0, -1))
# Behavior tuning. Plan-defined, kept here as named constants (not magic numbers).
_WANDER_MOVE_CHANCE: float = 0.5 # wander: 50/50 move vs wait
_FLEE_HP_FRACTION: float = 0.30 # flee when hp below 30% of max
_RANGED_KITE_DIST: int = 2 # ranged kites when player within this Chebyshev dist
_RANGED_RANGE: int = 8 # ranged can shoot out to this Chebyshev dist
_RANGED_DIST_PENALTY: float = 0.03 # per-tile hit-chance drop past the kite band
_HIT_BASE: float = 0.70
_HIT_STEP: float = 0.05
_HIT_FLOOR: float = 0.10
_HIT_CEIL: float = 0.95
# ponytail: per-enemy turn parity for the "phase" behavior (acts every 2 turns).
# Enemy is a slots dataclass we may not extend here, so bookkeep in a dict keyed
# by id(). Ceiling: grows with the enemy count of one run; id() reuse after GC is
# harmless (worst case a freshly-spawned wraith skips one extra turn). Clear on
# floor change if memory ever matters.
_PHASE_TICK: dict[int, int] = {}
def act_enemy(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random = random,
) -> None:
"""Resolve one enemy turn, dispatching on ``enemy.behavior``."""
behavior = getattr(enemy, "behavior", "wander")
if behavior == "wander":
_wander(enemy, game_map, rng)
elif behavior == "phase":
_phase(enemy, game_map, player, visible, rng)
elif behavior == "ranged":
_ranged(enemy, game_map, player, visible, rng)
elif behavior == "flee":
if _is_low_hp(enemy):
_flee(enemy, game_map, player, visible, rng)
else:
_chase(enemy, game_map, player, visible, rng)
else:
# "chase" and "split" both pursue the player; splitting on death is a
# separate event handled by split_on_death (called from the death path).
_chase(enemy, game_map, player, visible, rng)
# --------------------------------------------------------------------- behaviors
def _wander(enemy: Any, game_map: Any, rng: random.Random) -> None:
if rng.random() < _WANDER_MOVE_CHANCE:
return
moves = [d for d in _DIRS if game_map.walkable(enemy.x + d[0], enemy.y + d[1])]
if not moves:
return
dx, dy = rng.choice(moves)
enemy.x += dx
enemy.y += dy
def _chase(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
px, py = player.x, player.y
player_seen = (px, py) in visible
if player_seen:
enemy.last_known_pos = (px, py)
if _chebyshev(enemy.x, enemy.y, px, py) <= 1:
_melee(enemy, player, rng)
return
blockers = _enemy_blockers(game_map, enemy, player)
_step_toward(enemy, game_map, (px, py), blockers)
return
# Player out of sight: move toward the last known position, else wander.
lkp = enemy.last_known_pos
if lkp is None or (enemy.x, enemy.y) == lkp:
enemy.last_known_pos = None
_wander(enemy, game_map, rng)
return
blockers = _enemy_blockers(game_map, enemy, player)
_step_toward(enemy, game_map, lkp, blockers)
def _flee(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
px, py = player.x, player.y
if (px, py) not in visible:
_wander(enemy, game_map, rng)
return
_step_away(enemy, game_map, px, py)
def _ranged(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
px, py = player.x, player.y
if (px, py) not in visible:
_wander(enemy, game_map, rng)
return
dist = _chebyshev(enemy.x, enemy.y, px, py)
if dist <= _RANGED_KITE_DIST:
_step_away(enemy, game_map, px, py) # kite: open distance
return
if dist <= _RANGED_RANGE:
_ranged_attack(enemy, player, dist, rng)
def _phase(
enemy: Any,
game_map: Any,
player: Any,
visible: set[tuple[int, int]],
rng: random.Random,
) -> None:
# Acts every 2 turns: skip on odd ticks.
key = id(enemy)
_PHASE_TICK[key] = _PHASE_TICK.get(key, 0) + 1
if _PHASE_TICK[key] % 2 == 1:
return
px, py = player.x, player.y
if _chebyshev(enemy.x, enemy.y, px, py) <= 1:
_melee(enemy, player, rng)
return
_step_through_walls(enemy, game_map, px, py)
# ------------------------------------------------------------------- death hook
def split_on_death(enemy: Any, game_map: Any) -> list[Enemy]:
"""Spawn two smaller copies when a splitting enemy dies.
Called by the death/combat path (not by ``act_enemy``). Returns the freshly
spawned small enemies (0, 1, or 2 depending on free adjacent tiles); the
caller appends them to the floor's entities. Spawned copies never split.
"""
if not getattr(enemy, "can_split", False) or getattr(enemy, "hp", 1) > 0:
return []
spawned: list[Enemy] = []
for dx, dy in ((1, 0), (-1, 0)):
nx, ny = enemy.x + dx, enemy.y + dy
if game_map.in_bounds(nx, ny) and game_map.walkable(nx, ny):
spawned.append(_small_copy(enemy, nx, ny))
return spawned
def _small_copy(parent: Any, x: int, y: int) -> Enemy:
half_hp = max(1, int(parent.max_hp) // 2)
return Enemy(
x=x, y=y,
kind="small_slime", name="Small Slime",
hp=half_hp, max_hp=half_hp,
power=max(1, int(parent.power) // 2),
armor=int(getattr(parent, "armor", 0)),
accuracy=int(getattr(parent, "accuracy", 4)),
evasion=int(getattr(parent, "evasion", 0)),
crit_chance=float(getattr(parent, "crit_chance", 0.0)),
speed=int(getattr(parent, "speed", 1)),
behavior="chase",
xp_value=max(1, int(parent.xp_value) // 2),
last_known_pos=None,
can_split=False,
sprite_key="small_slime",
)
# ------------------------------------------------------------------ primitives
def _melee(enemy: Any, player: Any, rng: random.Random) -> None:
roll = roll_attack(enemy, player, rng)
if roll.hit and roll.damage > 0:
player.hp = max(0, int(player.hp) - roll.damage)
def _ranged_attack(enemy: Any, player: Any, dist: int, rng: random.Random) -> None:
ranged_power = int(getattr(enemy, "ranged_power", None) or enemy.power)
hit_chance = _HIT_BASE + (int(getattr(enemy, "accuracy", 4)) -
int(getattr(player, "evasion", 0))) * _HIT_STEP
hit_chance -= max(0, dist - _RANGED_KITE_DIST) * _RANGED_DIST_PENALTY
hit_chance = max(_HIT_FLOOR, min(_HIT_CEIL, hit_chance))
if rng.random() < hit_chance:
player.hp = max(0, int(player.hp) - ranged_power)
def _step_toward(
enemy: Any,
game_map: Any,
goal: tuple[int, int],
blockers: frozenset[tuple[int, int]] = frozenset(),
) -> bool:
"""Move one tile toward ``goal``. Returns True if the enemy moved.
Primary route is A* over walkable tiles. When A* reports no route (the goal
is genuinely walled off on a well-formed map) we try a walkable greedy step
and otherwise wait. If the map is so malformed that walkability itself raises
(never on a real GameMap, whose ``in_bounds`` guards the tile index), we fall
back to a direct beeline — boundary handling so a bad map can't crash the AI.
"""
# Detect a malformed map by probing the goal's walkability: on a well-formed
# GameMap this is a plain bool; if it raises, the goal sits outside the tile
# grid and A* cannot run, so beeline directly (boundary handling only).
try:
goal_walkable = game_map.walkable(*goal)
except Exception:
return _beeline(enemy, game_map, goal)
if not goal_walkable:
# Goal itself is non-walkable (e.g. target standing in a wall): close in
# via walkable tiles, else wait.
return _greedy_step(enemy, game_map, goal)
try:
path = find_path(game_map, (enemy.x, enemy.y), goal, blocked=blockers)
except Exception:
return _beeline(enemy, game_map, goal)
if path:
nx, ny = path[0]
enemy.x, enemy.y = nx, ny
return True
# Genuinely unreachable on an otherwise valid map: shuffle toward it or wait.
return _greedy_step(enemy, game_map, goal)
def _beeline(enemy: Any, game_map: Any, goal: tuple[int, int]) -> bool:
"""Direct step toward ``goal`` considering only bounds (no walkability).
Only reached when the pathfinder could not even evaluate the map. On a
well-formed map this is unreachable; it exists purely so a malformed map is
a degraded experience, not a crash.
"""
gx, gy = goal
best: tuple[int, int] | None = None
best_d: int | None = None
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if (nx, ny) == goal or not game_map.in_bounds(nx, ny):
continue
d = abs(nx - gx) + abs(ny - gy)
if best_d is None or d < best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
return True
return False
def _greedy_step(enemy: Any, game_map: Any, goal: tuple[int, int]) -> bool:
gx, gy = goal
best: tuple[int, int] | None = None
best_d: int | None = None
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if (nx, ny) == goal or not game_map.walkable(nx, ny):
continue
d = abs(nx - gx) + abs(ny - gy)
if best_d is None or d < best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
return True
return False
def _step_away(enemy: Any, game_map: Any, px: int, py: int) -> None:
"""Move one walkable tile that maximizes distance from (px, py)."""
best: tuple[int, int] | None = None
best_d = -1
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if not game_map.walkable(nx, ny):
continue
d = abs(nx - px) + abs(ny - py)
if d > best_d:
best_d, best = d, (nx, ny)
if best is not None:
enemy.x, enemy.y = best
def _step_through_walls(enemy: Any, game_map: Any, px: int, py: int) -> None:
"""Phase toward the player ignoring walls (may enter wall tiles).
Prefers a floor tile at equal distance so the wraith only phases when it must.
"""
cands: list[tuple[int, int, int, int]] = []
for dx, dy in _DIRS:
nx, ny = enemy.x + dx, enemy.y + dy
if not game_map.in_bounds(nx, ny) or (nx, ny) == (px, py):
continue
d = abs(nx - px) + abs(ny - py)
cands.append((d, 0 if game_map.walkable(nx, ny) else 1, nx, ny))
if cands:
cands.sort()
_, _, nx, ny = cands[0]
enemy.x, enemy.y = nx, ny
def _enemy_blockers(game_map: Any, self_enemy: Any, player: Any) -> frozenset[tuple[int, int]]:
"""Tiles occupied by other blocking entities (so enemies don't stack).
Excludes the acting enemy and the player (the player is the chase goal and is
handled by the adjacency check, not by blocking).
"""
blockers: set[tuple[int, int]] = set()
for e in getattr(game_map, "entities", []) or ():
if e is self_enemy or e is player:
continue
if not getattr(e, "blocks", True):
continue
blockers.add((e.x, e.y))
return frozenset(blockers)
def _is_low_hp(enemy: Any) -> bool:
max_hp = int(getattr(enemy, "max_hp", 1)) or 1
return int(getattr(enemy, "hp", max_hp)) < max_hp * _FLEE_HP_FRACTION
def _chebyshev(ax: int, ay: int, bx: int, by: int) -> int:
return max(abs(ax - bx), abs(ay - by))
if __name__ == "__main__":
# Self-check: a chase enemy reaches an adjacent player along an open corridor.
class _StubMap:
def __init__(self, tiles):
self.tiles = tiles
self.height = len(tiles)
self.width = len(tiles[0]) if tiles else 0
def in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def walkable(self, x, y):
return self.in_bounds(x, y) and self.tiles[y][x] == 1
class _E:
def __init__(self, x, y):
self.x, self.y = x, y
self.behavior = "chase"
self.hp = self.max_hp = 99
self.power, self.speed, self.kind = 4, 1, "goblin"
self.last_known_pos = None
self.accuracy, self.evasion, self.armor, self.crit_chance = 4, 1, 1, 0.0
class _P:
x = 18
y = 2
hp = 50
max_hp = 50
accuracy = 5
evasion = 2
armor = 0
crit_chance = 0.1
gm = _StubMap([[1 if y == 2 else 0 for _ in range(20)] for y in range(5)])
e = _E(2, 2)
p = _P()
vis = {(x, 2) for x in range(20)}
r = random.Random(5)
for _ in range(40):
act_enemy(e, gm, p, vis, r)
if max(abs(e.x - p.x), abs(e.y - p.y)) <= 1:
break
assert max(abs(e.x - p.x), abs(e.y - p.y)) <= 1, e.x
print("behaviors self-check: OK")