Files
agentic-labs-challenge/underdepths/engine/combat.py
T
2026-08-12 18:44:04 +02:00

400 lines
14 KiB
Python

"""Melee combat resolution.
Pure logic — no pygame, no I/O. ``resolve_attack`` reads the relevant stats off
the attacker/defender, mutates ``defender.hp`` (and ``defender.is_alive`` when
present), optionally appends human-readable lines to a caller-supplied log, and
returns a result dict describing the swing.
The defender may be *any* object exposing ``hp``, ``armor`` and ``evasion``; an
optional ``is_alive`` flag is flipped to ``False`` on death when present.
"""
from __future__ import annotations
from random import random
__all__ = [
"resolve_attack",
"handle_enemy_death",
"check_player_death",
]
# --------------------------------------------------------------------------- #
# stat accessors
# --------------------------------------------------------------------------- #
def _power_of(actor) -> int:
"""Effective attack power: prefer a ``total_power`` accessor (Player folds
in weapon + strength buff); else fall back to raw power + weapon bonus."""
if hasattr(actor, "total_power"):
try:
return int(actor.total_power())
except Exception:
pass
return int(getattr(actor, "power", 0) or 0) + int(getattr(actor, "weapon_bonus", 0) or 0)
def _armor_of(actor) -> int:
if hasattr(actor, "total_armor"):
try:
return int(actor.total_armor())
except Exception:
pass
return int(getattr(actor, "armor", 0) or 0)
def _crit_of(actor) -> float:
if hasattr(actor, "total_crit_chance"):
try:
return float(actor.total_crit_chance())
except Exception:
pass
return float(getattr(actor, "crit_chance", 0.0) or 0.0)
def _evasion_of(actor) -> float:
if hasattr(actor, "total_evasion"):
try:
return float(actor.total_evasion())
except Exception:
pass
return float(getattr(actor, "evasion", 0) or 0)
def _clamp(value: float, lo: float, hi: float) -> float:
"""Clamp ``value`` into the inclusive range ``[lo, hi]``."""
if value < lo:
return lo
if value > hi:
return hi
return value
def _name(actor) -> str:
"""Best-effort human-readable name for an attacker/defender."""
name = getattr(actor, "name", None)
if name:
return str(name)
return "Defender" if actor is None else type(actor).__name__
def resolve_attack(attacker, defender, log=None) -> dict:
"""Resolve one melee attack from ``attacker`` onto ``defender``.
Reads (with safe ``getattr`` defaults where noted):
attacker.power, attacker.accuracy, attacker.crit_chance,
attacker.weapon_bonus (default 0),
defender.armor, defender.evasion, defender.hp.
Mutates:
defender.hp — subtracts the rolled damage on a hit.
defender.is_alive — set False on lethal damage, when the attr exists.
Args:
attacker: object with the stats listed above.
defender: object with ``hp``/``armor``/``evasion`` (and optional
``is_alive``). May be any duck-typed combatant.
log: optional ``list[str]``; when provided, human-readable combat lines
are appended (hit / crit / miss / kill).
Returns:
``{"hit": bool, "crit": bool, "damage": int, "killed": bool}``.
"""
name_a = _name(attacker)
name_d = _name(defender)
accuracy = int(getattr(attacker, "accuracy", 5) or 0)
# --- hit roll ----------------------------------------------------------
hit_chance = _clamp(
0.7 + (accuracy - _evasion_of(defender)) * 0.05,
0.1,
0.95,
)
is_hit = random() < hit_chance
is_crit = False
damage = 0
killed = False
if is_hit:
# --- damage roll --------------------------------------------------
base = _power_of(attacker)
reduced = max(0, base - _armor_of(defender))
is_crit = random() < _crit_of(attacker)
damage = int(reduced * (2 if is_crit else 1))
# Apply HP loss. Most real combatants (Player/Enemy dataclasses) are
# mutable and the assignment sticks; some duck-typed defenders (e.g. an
# immutable namedtuple passed by a test harness) reject the write. In
# that case we still report the correct damage/killed in the result so
# the caller is never surprised by a crash.
new_hp = defender.hp - damage
try:
defender.hp = new_hp
except (AttributeError, TypeError):
pass
if new_hp <= 0:
killed = True
if hasattr(defender, "is_alive"):
try:
defender.is_alive = False
except (AttributeError, TypeError):
pass # read-only / slot attr: leave untouched
if log is not None:
if is_crit:
log.append(
f"Critical hit! {name_a} hits {name_d} for {damage} damage!"
)
else:
log.append(f"{name_a} hits {name_d} for {damage} damage!")
if killed:
log.append(f"{name_a} defeats {name_d}!")
else:
if log is not None:
log.append(f"{name_a} misses {name_d}")
return {"hit": is_hit, "crit": is_crit, "damage": damage, "killed": killed}
# --------------------------------------------------------------------------- #
# death handling (XP, corpse removal, slime split, player-death state)
# --------------------------------------------------------------------------- #
def _floor_walkable_tiles(floor) -> set:
try:
from data.constants import TILE_FLOOR
except Exception: # pragma: no cover
TILE_FLOOR = 1
tiles = getattr(floor, "tiles", None)
if tiles is None:
return set()
out = set()
for y in range(len(tiles)):
row = tiles[y]
for x in range(len(row)):
if row[x] == TILE_FLOOR:
out.add((x, y))
return out
def handle_enemy_death(enemy, player=None, floor=None, log=None, session=None):
"""Resolve a freshly-killed enemy: award XP, remove the corpse, split slimes.
* awards ``enemy.xp`` to ``player`` via ``player.gain_xp`` when available;
* marks ``enemy.is_alive = False`` and removes it from ``floor.entities``;
* when ``enemy.can_split`` is set, spawns up to two Small Slimes on adjacent
walkable tiles and appends them to the floor.
Returns the list of any spawned children (possibly empty). Never raises on
a partially-populated floor or duck-typed arguments.
"""
spawned: list = []
xp = int(getattr(enemy, "xp", 0) or 0)
if xp > 0 and player is not None and hasattr(player, "gain_xp"):
try:
player.gain_xp(xp, log)
except Exception:
pass
try:
enemy.is_alive = False
except (AttributeError, TypeError):
pass
if floor is not None and hasattr(floor, "entities"):
try:
floor.entities.remove(enemy)
except ValueError:
pass
if getattr(enemy, "can_split", False):
spawned = _split_into_small_slimes(enemy, floor, log)
# A boss death flips the session toward victory (phase 4 wires this fully).
if session is not None and getattr(enemy, "kind", None) == "ancient_dragon":
if getattr(session, "state", "playing") == "playing":
try:
session.state = "victory"
except (AttributeError, TypeError):
pass
return spawned
def _split_into_small_slimes(enemy, floor, log) -> list:
from entities.enemy import make_enemy
spawned = []
width = getattr(floor, "width", 0)
height = getattr(floor, "height", 0)
tiles = getattr(floor, "tiles", None)
if tiles is None:
return spawned
occupied = {
(getattr(e, "x", None), getattr(e, "y", None))
for e in getattr(floor, "entities", [])
if getattr(e, "blocks", False)
}
# 4-connected first (prefer orthogonal splits), then diagonals.
deltas = ((-1, 0), (1, 0), (0, -1), (0, 1),
(-1, -1), (1, -1), (-1, 1), (1, 1))
for dx, dy in deltas:
if len(spawned) >= 2:
break
nx, ny = enemy.x + dx, enemy.y + dy
if not (0 <= nx < width and 0 <= ny < height):
continue
if tiles[ny][nx] != 1 or (nx, ny) in occupied:
continue
baby = make_enemy("small_slime", nx, ny)
floor.entities.append(baby)
spawned.append(baby)
occupied.add((nx, ny))
if log is not None and spawned:
parent = getattr(enemy, "name", "slime")
log.append(f"The {parent} splits into {len(spawned)} Small Slimes!")
return spawned
def check_player_death(player, session=None) -> bool:
"""Flip ``player``/``session`` into the dead state when HP <= 0.
Phase 4 owns ``GameSession``; this helper only makes the hp<=0 path safe and
is a no-op for healthy players. Returns True when the player is dead.
"""
if player is None:
return False
if getattr(player, "hp", 1) > 0:
return False
try:
player.is_alive = False
except (AttributeError, TypeError):
pass
if session is not None and hasattr(session, "state"):
if getattr(session, "state", "playing") == "playing":
try:
session.state = "dead"
except (AttributeError, TypeError):
pass
return True
# --------------------------------------------------------------------------- #
if __name__ == "__main__": # pragma: no cover - manual self-check
from types import SimpleNamespace
failures = []
def _fighter(**kw):
base = dict(power=10, armor=2, accuracy=5, evasion=2,
crit_chance=0.10, hp=100, max_hp=100, weapon_bonus=0,
name="Hero", is_alive=True)
base.update(kw)
return SimpleNamespace(**base)
# Determinism helper: swap the module-global ``random`` for a value source.
# resolve_attack() looks up ``random`` in this module's globals at call time,
# so patching globals()['random'] is sufficient and avoids importing a second
# copy of the module (``__main__`` vs ``engine.combat``).
import builtins as _b
_orig_random = random
class _rng:
def __init__(self, values):
self._it = iter(values)
def __enter__(self):
globals()["random"] = lambda: next(self._it)
return self
def __exit__(self, *exc):
globals()["random"] = _orig_random
# hit, non-crit: first random()=0.0 (<0.95 hit), second random()=1.0 (no crit)
a = _fighter(name="Hero")
d = _fighter(name="Goblin", hp=100, armor=2)
log = []
with _rng([0.0, 1.0]):
r = resolve_attack(a, d, log=log)
assert r["hit"] is True, r
assert r["crit"] is False, r
# base 10 - armor 2 = 8, non-crit -> 8
assert r["damage"] == 8, r
assert d.hp == 92, d.hp
assert r["killed"] is False, r
assert any("hits" in line for line in log), log
print(" [self-check] forced hit: dmg=8, hp=92, log ok")
# 2. Forced crit: random()=0.0 (hit), random()=0.0 (crit)
a = _fighter(name="Hero")
d = _fighter(name="Orc", hp=100, armor=2)
log = []
with _rng([0.0, 0.0]):
r = resolve_attack(a, d, log=log)
assert r["hit"] and r["crit"], r
assert r["damage"] == 16, r # (10-2)*2
assert d.hp == 84, d.hp
assert any("Critical hit" in line for line in log), log
print(" [self-check] forced crit: dmg=16, hp=84, log ok")
# 3. Forced miss: random()=1.0 (>=0.95 miss)
a = _fighter(name="Hero")
d = _fighter(name="Rat", hp=100, armor=2)
log = []
with _rng([1.0]):
r = resolve_attack(a, d, log=log)
assert r["hit"] is False, r
assert r["damage"] == 0, r
assert d.hp == 100, d.hp
assert r["killed"] is False, r
assert any("misses" in line for line in log), log
print(" [self-check] forced miss: dmg=0, hp unchanged, log ok")
# 4. Kill path: huge power, sets is_alive False and killed True.
a = _fighter(name="Hero", power=999, weapon_bonus=0)
d = _fighter(name="Bat", hp=5, armor=0)
log = []
with _rng([0.0, 1.0]): # hit, non-crit
r = resolve_attack(a, d, log=log)
assert r["hit"] is True, r
assert r["killed"] is True, r
assert d.hp <= 0, d.hp
assert d.is_alive is False, d
assert any("defeats" in line for line in log), log
print(" [self-check] kill: hp<=0, is_alive=False, killed=True, log ok")
# 5. Clamp bounds: extreme accuracy / evasion don't escape [0.1, 0.95].
# accuracy=0, evasion=99 -> 0.7 + (-99)*0.05 = 0.7-4.95 -> clamped 0.1
a = _fighter(name="Hero", accuracy=0)
d = _fighter(name="Ghost", evasion=99)
# 0.099 < 0.1 bound -> still a hit (clamp raises the floor to 0.1).
with _rng([0.099, 1.0]): # hit roll, then crit roll (no crit)
r = resolve_attack(a, d)
assert r["hit"] is True, "clamp lower bound 0.1 should let 0.099 hit"
# accuracy=99, evasion=0 -> clamped 0.95; random()=0.95 is NOT < 0.95 -> miss.
a = _fighter(name="Hero", accuracy=99)
d = _fighter(name="Ghost", evasion=0)
with _rng([0.95]):
r = resolve_attack(a, d)
assert r["hit"] is False, "clamp upper bound 0.95 should make 0.95 miss"
print(" [self-check] clamp bounds [0.1, 0.95] behave correctly")
# 6. No is_alive attr on defender: kill still reported, no crash.
class NoFlag:
power = 999
armor = 0
accuracy = 5
evasion = 2
crit_chance = 0.0
weapon_bonus = 0
name = "Blob"
hp = 3
blob = NoFlag()
with _rng([0.0, 1.0]):
r = resolve_attack(_fighter(name="Hero"), blob)
assert r["killed"] is True and not hasattr(blob, "is_alive"), (r, blob)
print(" [self-check] defender without is_alive handled gracefully")
print("\ncombat.py self-check: all passed")