(Underdepths) Pass 2
This commit is contained in:
1 parent
4a5a92cb74
commit
b49c285c89
37 files changed
+5590
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,127 @@
|
||||
"""Resilient generated sound effects.
|
||||
|
||||
``AudioEngine`` synthesizes a handful of short tones in memory (stdlib ``array``
|
||||
written straight into a ``pygame.mixer.Sound`` buffer — no numpy, no asset
|
||||
files). It is constructed at the application boundary and is defensive at every
|
||||
step: if the mixer will not initialize (headless box, dummy driver, no device)
|
||||
or a single tone fails to build, audio is silently disabled and the game stays
|
||||
fully playable. The public API can never raise.
|
||||
|
||||
Effect names: ``hit``, ``miss``, ``damage``, ``pickup``, ``stairs``,
|
||||
``levelup``, ``death``, ``victory``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
|
||||
__all__ = ["AudioEngine"]
|
||||
|
||||
# (name, base_hz, duration_ms, volume, sweep_to_hz)
|
||||
# A gentle downward sweep reads as a "thud/hit", an upward chirp reads as
|
||||
# "pickup/levelup". Volumes are conservative so effects are quiet by default.
|
||||
_EFFECTS = {
|
||||
"hit": (220.0, 90, 0.28, 110.0), # quick down-sweep
|
||||
"miss": (330.0, 70, 0.18, 220.0), # soft blip
|
||||
"damage": (160.0, 160, 0.32, 70.0), # heavy thud
|
||||
"pickup": (520.0, 110, 0.26, 880.0), # rising chirp
|
||||
"stairs": (440.0, 180, 0.26, 660.0),
|
||||
"levelup": (523.0, 240, 0.30, 1046.0), # triumphant rise
|
||||
"death": (200.0, 480, 0.34, 60.0), # long fall
|
||||
"victory": (523.0, 520, 0.32, 1046.0),
|
||||
}
|
||||
|
||||
|
||||
class AudioEngine:
|
||||
"""A best-effort, never-raising sound-effect player."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.enabled: bool = False
|
||||
self.muted: bool = False
|
||||
self.sounds: dict = {}
|
||||
|
||||
try:
|
||||
import pygame # local import keeps this importable without pygame
|
||||
except Exception:
|
||||
return
|
||||
|
||||
# Initialize the mixer only if it has not been already. Any failure
|
||||
# (no device, dummy driver, denied) leaves audio disabled.
|
||||
try:
|
||||
if not pygame.mixer.get_init():
|
||||
pygame.mixer.init()
|
||||
except Exception:
|
||||
self.enabled = False
|
||||
return
|
||||
|
||||
fmt = None
|
||||
try:
|
||||
fmt = pygame.mixer.get_init()
|
||||
except Exception:
|
||||
fmt = None
|
||||
if not fmt:
|
||||
self.enabled = False
|
||||
return
|
||||
|
||||
self.enabled = True
|
||||
try:
|
||||
self._build_all(pygame, fmt)
|
||||
except Exception:
|
||||
# A total build failure still leaves the engine usable (silent).
|
||||
self.sounds = {}
|
||||
|
||||
# -- construction --------------------------------------------------------
|
||||
def _build_all(self, pygame, fmt) -> None:
|
||||
freq, size, channels = fmt
|
||||
for name, (hz, ms, vol, end_hz) in _EFFECTS.items():
|
||||
try:
|
||||
self.sounds[name] = self._make_tone(pygame, freq, size, channels,
|
||||
hz, end_hz, ms, vol)
|
||||
except Exception:
|
||||
# Skip the one bad tone; keep the rest.
|
||||
continue
|
||||
|
||||
@staticmethod
|
||||
def _make_tone(pygame, freq: int, size: int, channels: int,
|
||||
start_hz: float, end_hz: float, ms: int, vol: float):
|
||||
"""Render a swept, exponentially-decaying tone into a Sound buffer.
|
||||
|
||||
Honors the mixer's signed-16-bit format (size == -16 or 16) and channel
|
||||
count (mono/stereo). Any other format falls back to signed 16-bit.
|
||||
"""
|
||||
n = max(1, int(freq * ms / 1000.0))
|
||||
stereo = (channels or 1) >= 2
|
||||
arr = array.array("h")
|
||||
sweep = (end_hz != start_hz)
|
||||
decay_tau = max(1.0, n / 3.0) # smooth exponential fade-out
|
||||
for i in range(n):
|
||||
t = i / freq
|
||||
frac = i / n
|
||||
hz = start_hz + (end_hz - start_hz) * frac if sweep else start_hz
|
||||
phase = 2.0 * math.pi * hz * t
|
||||
# Soft attack + exponential release to avoid clicks.
|
||||
env = (1.0 - math.exp(-i / max(1.0, n * 0.05))) * math.exp(-i / decay_tau)
|
||||
sample = int(max(-1.0, min(1.0, vol * env)) * 32767.0 * math.sin(phase))
|
||||
arr.append(sample)
|
||||
if stereo:
|
||||
arr.append(sample)
|
||||
return pygame.mixer.Sound(buffer=arr.tobytes())
|
||||
|
||||
# -- public API ----------------------------------------------------------
|
||||
def play(self, name: str) -> None:
|
||||
"""Play ``name``; never raises. No-op when disabled or muted."""
|
||||
if not self.enabled or self.muted:
|
||||
return
|
||||
snd = self.sounds.get(name)
|
||||
if snd is None:
|
||||
return
|
||||
try:
|
||||
snd.play()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def toggle_mute(self) -> bool:
|
||||
"""Flip the mute flag and return the new state."""
|
||||
self.muted = not self.muted
|
||||
return self.muted
|
||||
@@ -0,0 +1,399 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Recursive shadowcasting field-of-view.
|
||||
|
||||
Implemented from scratch (no third-party deps, no pygame). The public entry
|
||||
point :func:`compute_fov` is a pure function: it never mutates ``tiles`` and
|
||||
keeps all of its bookkeeping in local structures.
|
||||
|
||||
Geometry contract (shared with the rest of the engine):
|
||||
* tiles are indexed ``tiles[y][x]``; ``TILE_WALL=0``, ``TILE_FLOOR=1``.
|
||||
* a tile is a *wall* iff ``tiles[y][x] == 0`` (everything else is see-through
|
||||
floor for the purposes of sight).
|
||||
|
||||
Visibility rules:
|
||||
* the origin tile is always visible to itself;
|
||||
* a tile is visible when an unobstructed line of sight reaches it;
|
||||
* walls block sight beyond them (a wall is hit first, then casts a shadow);
|
||||
* as a rendering convenience, a wall tile is itself visible whenever it is
|
||||
8-adjacent to a visible floor tile (so room boundaries always show up);
|
||||
* every returned tile lies within ``radius`` (Euclidean, which is a strict
|
||||
refinement of the Chebyshev bound requested by the caller).
|
||||
|
||||
The algorithm is Björn Bergström's classic recursive shadowcasting: the view
|
||||
around the origin is split into 8 octants and each octant is scanned by a
|
||||
recursive routine that tracks the current illuminated slope interval
|
||||
``[start, end]``. When a wall is encountered the interval is split and the far
|
||||
side is explored by a child scan; once a whole row in an octant sits in shadow
|
||||
the scan for that octant stops.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ["compute_fov"]
|
||||
|
||||
# Octant transformation multipliers (Björn Bergström). Each column describes one
|
||||
# octant; the four rows are xx, xy, yx, yy used to map local scan offsets
|
||||
# (dx, dy) into world coordinates: X = ox + dx*xx + dy*xy, Y = oy + dx*yx + dy*yy.
|
||||
_OCTANTS = (
|
||||
(1, 0, 0, -1, -1, 0, 0, 1),
|
||||
(0, 1, -1, 0, 0, -1, 1, 0),
|
||||
(0, 1, 1, 0, 0, -1, -1, 0),
|
||||
(1, 0, 0, 1, -1, 0, 0, -1),
|
||||
)
|
||||
|
||||
|
||||
def compute_fov(
|
||||
width: int, height: int, tiles, ox: int, oy: int, radius: int = 8
|
||||
) -> set[tuple[int, int]]:
|
||||
"""Return the set of ``(x, y)`` visible from ``(ox, oy)`` within ``radius``.
|
||||
|
||||
``tiles`` is ``list[list[int]]`` indexed ``tiles[y][x]`` where a wall is any
|
||||
tile equal to ``0``. ``tiles`` is never mutated. The result always includes
|
||||
the origin; every tile is within Euclidean (and therefore Chebyshev)
|
||||
distance ``radius`` of the origin.
|
||||
"""
|
||||
visible: set[tuple[int, int]] = set()
|
||||
|
||||
# An origin outside the map sees nothing (and we cannot safely index tiles).
|
||||
if not (0 <= ox < width and 0 <= oy < height):
|
||||
return visible
|
||||
|
||||
def is_wall(x: int, y: int) -> bool:
|
||||
# In-bounds walls block sight; out-of-bounds behaves like solid rock so
|
||||
# it casts a clean shadow at the map edge.
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
return tiles[y][x] == 0
|
||||
return True
|
||||
|
||||
def light(x: int, y: int) -> None:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
visible.add((x, y))
|
||||
|
||||
# The origin is always visible to itself.
|
||||
light(ox, oy)
|
||||
|
||||
if radius <= 0:
|
||||
return visible
|
||||
|
||||
radius_sq = radius * radius
|
||||
|
||||
def cast_light(row: int, start: float, end: float,
|
||||
xx: int, xy: int, yx: int, yy: int) -> None:
|
||||
"""Recursively illuminate one octant over the slope window [start, end].
|
||||
|
||||
``start`` is the upper (steeper) slope, ``end`` the lower one; the scan
|
||||
terminates once the window collapses.
|
||||
"""
|
||||
if start < end:
|
||||
return
|
||||
for j in range(row, radius + 1):
|
||||
dx = -j - 1
|
||||
dy = -j
|
||||
blocked = False
|
||||
new_start = 0.0
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
mx = ox + dx * xx + dy * xy
|
||||
my = oy + dx * yx + dy * yy
|
||||
# Slopes of the left and right edges of this tile cell.
|
||||
l_slope = (dx - 0.5) / (dy + 0.5)
|
||||
r_slope = (dx + 0.5) / (dy - 0.5)
|
||||
if start < r_slope:
|
||||
# Tile sits above the lit window; keep climbing slopes.
|
||||
continue
|
||||
elif end > l_slope:
|
||||
# Tile sits below the lit window; nothing more in this row.
|
||||
break
|
||||
else:
|
||||
# The beam touches this cell: illuminate it if in range.
|
||||
if dx * dx + dy * dy <= radius_sq:
|
||||
light(mx, my)
|
||||
if blocked:
|
||||
# We are traversing a run of wall cells.
|
||||
if is_wall(mx, my):
|
||||
new_start = r_slope
|
||||
continue
|
||||
else:
|
||||
# End of the wall run: resume from its near edge.
|
||||
blocked = False
|
||||
start = new_start
|
||||
else:
|
||||
if is_wall(mx, my) and j < radius:
|
||||
# Wall after open space: spawn a child scan for the
|
||||
# slope band beyond it, then mark this run blocked.
|
||||
cast_light(j + 1, start, l_slope, xx, xy, yx, yy)
|
||||
blocked = True
|
||||
new_start = r_slope
|
||||
# A fully shadowed row means deeper rows are shadowed too: stop.
|
||||
if blocked:
|
||||
break
|
||||
|
||||
for oct in range(8):
|
||||
cast_light(
|
||||
1, 1.0, 0.0,
|
||||
_OCTANTS[0][oct], _OCTANTS[1][oct], _OCTANTS[2][oct], _OCTANTS[3][oct],
|
||||
)
|
||||
|
||||
# Wall-adjacency rule: a wall neighbouring a visible floor tile is itself
|
||||
# visible. We expand only from the lit floor tiles captured above (a single
|
||||
# additive pass, not a flood fill, since the rule keys off floor not wall).
|
||||
floors = [
|
||||
(x, y) for (x, y) in visible
|
||||
if 0 <= x < width and 0 <= y < height and tiles[y][x] != 0
|
||||
]
|
||||
for fx, fy in floors:
|
||||
for ny in (fy - 1, fy, fy + 1):
|
||||
for nx in (fx - 1, fx, fx + 1):
|
||||
if (nx, ny) == (fx, fy):
|
||||
continue
|
||||
if 0 <= nx < width and 0 <= ny < height and tiles[ny][nx] == 0:
|
||||
visible.add((nx, ny))
|
||||
|
||||
return visible
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _cheby(a, b):
|
||||
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Lightweight self-check mirroring the smoke-suite FOV assertions.
|
||||
TILE_WALL, TILE_FLOOR, SIGHT_RADIUS = 0, 1, 8
|
||||
W = H = 21
|
||||
cx = cy = 10
|
||||
|
||||
# 1) Player walled in on all 8 sides -> only the ring + origin are visible.
|
||||
tiles = [[TILE_FLOOR] * W for _ in range(H)]
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
if (dx, dy) != (0, 0):
|
||||
tiles[cy + dy][cx + dx] = TILE_WALL
|
||||
vis = compute_fov(W, H, tiles, cx, cy, radius=SIGHT_RADIUS)
|
||||
assert (cx, cy) in vis, "origin not visible"
|
||||
leaked = [t for t in vis if _cheby(t, (cx, cy)) > 1]
|
||||
assert not leaked, f"walls fail to occlude: {len(leaked)} tiles leaked"
|
||||
# tiles must be untouched.
|
||||
assert all(tiles[y][x] == (TILE_WALL if _cheby((x, y), (cx, cy)) == 1 and (x, y) != (cx, cy) else TILE_FLOOR)
|
||||
for y in range(H) for x in range(W)), "tiles mutated"
|
||||
print(f"OK walled-in: sees {len(vis)} tiles, none past the ring")
|
||||
|
||||
# 2) Open field -> a roughly circular disc within the radius.
|
||||
tiles2 = [[TILE_FLOOR] * W for _ in range(H)]
|
||||
vis2 = compute_fov(W, H, tiles2, cx, cy, radius=SIGHT_RADIUS)
|
||||
assert len(vis2) > 50, f"open FOV too small: {len(vis2)}"
|
||||
assert all(_cheby(t, (cx, cy)) <= SIGHT_RADIUS for t in vis2), "exceeds radius"
|
||||
print(f"OK open field: sees {len(vis2)} tiles within radius")
|
||||
|
||||
# 3) A wall pillar should not hide the floor on its far side that is reached
|
||||
# by light bending around it via neighbouring octants.
|
||||
tiles3 = [[TILE_FLOOR] * W for _ in range(H)]
|
||||
tiles3[cy][cx + 3] = TILE_WALL # pillar due east
|
||||
vis3 = compute_fov(W, H, tiles3, cx, cy, radius=SIGHT_RADIUS)
|
||||
assert (cx + 3, cy) in vis3, "pillar wall itself should be visible"
|
||||
assert (cx + 4, cy) not in vis3, "floor directly behind pillar hidden"
|
||||
assert (cx + 4, cy + 1) in vis3, "floor beside-behind pillar visible"
|
||||
print(f"OK pillar: {len(vis3)} tiles; pillar visible, far-centre occluded")
|
||||
|
||||
print("All FOV self-checks passed.")
|
||||
@@ -0,0 +1,444 @@
|
||||
"""``GameSession`` — the single source of truth for all mutable game state.
|
||||
|
||||
Everything the rest of the engine reads and mutates lives here: the player, the
|
||||
10-floor dungeon, the message log, the turn counter, and the high-level state
|
||||
machine (menu / playing / dead / victory / saved). ``apply_action`` is the one
|
||||
entry point the UI uses to advance the game; it resolves a single player intent
|
||||
tuple, then drives every live enemy on the floor, recomputes the player's FOV
|
||||
and resolves end-states (death / victory).
|
||||
|
||||
Persistence is JSON via :mod:`engine.serializers`; the ``visible`` grid is never
|
||||
serialized (recomputed on load) while effect timers are.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from data.constants import MAP_H, MAP_W, SIGHT_RADIUS, TILE_FLOOR
|
||||
from engine.fov import compute_fov
|
||||
from engine.combat import resolve_attack, handle_enemy_death, check_player_death
|
||||
from engine.map_gen import GameMap, generate_floor, is_walkable
|
||||
from engine.serializers import (
|
||||
player_to_dict, player_from_dict,
|
||||
map_to_dict, map_from_dict,
|
||||
write_json, read_json,
|
||||
)
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
|
||||
__all__ = [
|
||||
"GameSession",
|
||||
"new_game",
|
||||
"apply_action",
|
||||
"to_dict",
|
||||
"from_dict",
|
||||
"save",
|
||||
"load",
|
||||
]
|
||||
|
||||
_LOG_CAP = 50
|
||||
_NUM_FLOORS = 10
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Any # Player
|
||||
dungeon: list # list[GameMap] — all 10 floors
|
||||
current_floor: int
|
||||
log: list = field(default_factory=list)
|
||||
turn: int = 0
|
||||
state: str = "playing" # menu | playing | dead | victory | saved
|
||||
rng_seed: int = 0
|
||||
|
||||
# -- convenience ---------------------------------------------------------
|
||||
@property
|
||||
def floor(self) -> GameMap:
|
||||
return self.dungeon[self.current_floor]
|
||||
|
||||
def recompute_state(self) -> str:
|
||||
"""Re-derive the high-level state from player HP + boss status.
|
||||
|
||||
Safe to call at any time (used by the UI/tests after directly mutating
|
||||
``player.hp``). Returns the resulting state.
|
||||
"""
|
||||
return _resolve_end_states(self, self.floor, announce=False)
|
||||
|
||||
# Alias kept for compatibility with tests that probe for ``check_state``.
|
||||
def check_state(self) -> str:
|
||||
return self.recompute_state()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# construction
|
||||
# --------------------------------------------------------------------------- #
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
"""Generate all 10 floors and spawn the player at floor 0's spawn room.
|
||||
|
||||
A deterministic master seed derives a per-floor seed so the whole descent is
|
||||
reproducible; passing ``seed=None`` draws one at random.
|
||||
"""
|
||||
if seed is None:
|
||||
seed = random.randrange(1 << 31)
|
||||
master = random.Random(seed)
|
||||
dungeon: list = []
|
||||
for i in range(_NUM_FLOORS):
|
||||
floor_seed = master.randrange(1 << 31)
|
||||
dungeon.append(generate_floor(floor_index=i, seed=floor_seed))
|
||||
|
||||
first = dungeon[0]
|
||||
if first.rooms:
|
||||
spawn = first.rooms[0].center
|
||||
else:
|
||||
spawn = (MAP_W // 2, MAP_H // 2)
|
||||
# Player import is local to avoid a circular import at module load time
|
||||
# (player.py only imports constants, so this is belt-and-braces).
|
||||
from entities.player import make_player
|
||||
player = make_player(spawn[0], spawn[1])
|
||||
|
||||
session = GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=[],
|
||||
turn=0,
|
||||
state="playing",
|
||||
rng_seed=int(seed),
|
||||
)
|
||||
_update_player_fov(session, first)
|
||||
session.log.append("You descend into the Underdepths. Good luck.")
|
||||
_cap_log(session)
|
||||
return session
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# action dispatch
|
||||
# --------------------------------------------------------------------------- #
|
||||
def apply_action(session: GameSession, action: tuple) -> dict:
|
||||
"""Resolve one player intent, then advance the world by one turn.
|
||||
|
||||
Supported action tuples:
|
||||
('move', dx, dy) walk / attack adjacent enemy / bump (blocked) wall
|
||||
('pickup',) move the item under the player into inventory
|
||||
('descend',) go down the stairs (only while standing on them)
|
||||
('save',) serialize to disk + flip state to 'saved'
|
||||
('quaff', idx) drink inventory[idx]
|
||||
('read', idx) read inventory[idx]
|
||||
('equip', idx) equip inventory[idx]
|
||||
('wait',) pass (advances time)
|
||||
|
||||
Returns a small result dict describing what happened.
|
||||
"""
|
||||
if not isinstance(action, tuple) or not action:
|
||||
return {"ok": False, "reason": "bad action"}
|
||||
|
||||
name = action[0]
|
||||
floor = session.floor
|
||||
playing = session.state == "playing"
|
||||
|
||||
# 'save' is allowed from any live state; it never advances the turn.
|
||||
if name == "save":
|
||||
session.state = "saved"
|
||||
session.log.append("Game saved.")
|
||||
_cap_log(session)
|
||||
return {"ok": True, "saved": True, "took_turn": False}
|
||||
|
||||
took_turn = False
|
||||
|
||||
if name == "move":
|
||||
if playing and len(action) >= 3:
|
||||
took_turn = _do_move(session, floor, int(action[1]), int(action[2]))
|
||||
elif name == "wait":
|
||||
# A wait always consumes the turn (even on a dead/victory session the
|
||||
# UI may pump it); it just does not trigger enemy turns when not playing.
|
||||
took_turn = True
|
||||
session.log.append("You wait.")
|
||||
elif name == "pickup":
|
||||
if playing:
|
||||
took_turn = _do_pickup(session, floor)
|
||||
elif name == "descend":
|
||||
if playing:
|
||||
took_turn = _do_descend(session, floor)
|
||||
elif name == "quaff":
|
||||
if playing:
|
||||
idx = int(action[1]) if len(action) > 1 else -1
|
||||
session.player.quaff(idx, session.log)
|
||||
took_turn = True
|
||||
elif name == "read":
|
||||
if playing:
|
||||
idx = int(action[1]) if len(action) > 1 else -1
|
||||
target = (session.player.x, session.player.y)
|
||||
session.player.read_scroll(idx, ctx=session, log=session.log, target=target)
|
||||
took_turn = True
|
||||
elif name == "equip":
|
||||
if playing:
|
||||
idx = int(action[1]) if len(action) > 1 else -1
|
||||
if 0 <= idx < len(session.player.inventory):
|
||||
session.player.equip(session.player.inventory[idx], session.log)
|
||||
took_turn = True
|
||||
else:
|
||||
return {"ok": False, "reason": f"unknown action {name!r}"}
|
||||
|
||||
if took_turn:
|
||||
session.turn += 1
|
||||
# Re-read the floor: a 'descend' action moves the player to a new map,
|
||||
# and post-turn processing (enemy turns, FOV, end-states) must operate
|
||||
# on the floor the player now stands on.
|
||||
floor = session.floor
|
||||
if playing:
|
||||
_run_enemy_turns(session, floor)
|
||||
session.player.tick_effects(session.log)
|
||||
_update_player_fov(session, floor)
|
||||
_resolve_end_states(session, floor, announce=True)
|
||||
|
||||
_cap_log(session)
|
||||
return {"ok": True, "took_turn": took_turn}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# individual actions
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _do_move(session: GameSession, floor: GameMap, dx: int, dy: int) -> bool:
|
||||
nx, ny = session.player.x + dx, session.player.y + dy
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
return False
|
||||
|
||||
# Attack an adjacent live enemy that blocks the tile.
|
||||
target = _enemy_at(floor, nx, ny)
|
||||
if target is not None:
|
||||
r = resolve_attack(session.player, target, log=session.log)
|
||||
if r.get("killed"):
|
||||
handle_enemy_death(target, session.player, floor, session.log, session=session)
|
||||
# Attacking (hit or miss) costs a turn.
|
||||
return True
|
||||
|
||||
# Walk into open floor.
|
||||
if is_walkable(floor, nx, ny) and not _blocks_at(floor, nx, ny):
|
||||
session.player.x, session.player.y = nx, ny
|
||||
return True
|
||||
|
||||
# Blocked by a wall (or an item, which never blocks): no turn consumed so
|
||||
# the player is not punished for misjudging the map edge.
|
||||
return False
|
||||
|
||||
|
||||
def _do_pickup(session: GameSession, floor: GameMap) -> bool:
|
||||
px, py = session.player.x, session.player.y
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Item) and e.x == px and e.y == py:
|
||||
floor.entities.remove(e)
|
||||
# Items enter the inventory detached from the floor grid.
|
||||
session.player.inventory.append(e)
|
||||
session.log.append(f"You pick up {e.name}.")
|
||||
return True
|
||||
session.log.append("There is nothing here to pick up.")
|
||||
return True # pressing g with nothing at your feet still costs a turn
|
||||
|
||||
|
||||
def _do_descend(session: GameSession, floor: GameMap) -> bool:
|
||||
stairs = floor.stairs_down
|
||||
if stairs is None or (session.player.x, session.player.y) != tuple(stairs):
|
||||
session.log.append("There are no stairs here.")
|
||||
return True
|
||||
if session.current_floor >= len(session.dungeon) - 1:
|
||||
session.log.append("The stairs lead nowhere.")
|
||||
return True
|
||||
session.current_floor += 1
|
||||
nxt = session.dungeon[session.current_floor]
|
||||
# Land the player in the new floor's spawn room (rooms[0]) so they arrive
|
||||
# somewhere safe, not on top of a monster.
|
||||
if nxt.rooms:
|
||||
sx, sy = nxt.rooms[0].center
|
||||
else:
|
||||
sx, sy = MAP_W // 2, MAP_H // 2
|
||||
# Nudge off any occupant of the centre tile.
|
||||
if not is_walkable(nxt, sx, sy) or _enemy_at(nxt, sx, sy) is not None:
|
||||
sx, sy = _nearest_free(nxt, sx, sy)
|
||||
session.player.x, session.player.y = sx, sy
|
||||
session.log.append(f"You descend to floor {session.current_floor + 1}.")
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# per-turn world updates
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _run_enemy_turns(session: GameSession, floor: GameMap) -> None:
|
||||
"""Every live enemy on the floor takes one action.
|
||||
|
||||
Each enemy's FOV is computed fresh from its position; when the player is
|
||||
under an invisibility effect the player's tile is removed from that view so
|
||||
the monster behaves as if it cannot see the adventurer.
|
||||
"""
|
||||
# Snapshot the live enemy list up front: a slime split or a scroll's
|
||||
# fireball can mutate ``entities`` mid-iteration.
|
||||
enemies = [e for e in floor.entities
|
||||
if isinstance(e, Enemy) and getattr(e, "is_alive", False)]
|
||||
if not enemies:
|
||||
return
|
||||
|
||||
from ai.behaviors import take_enemy_turn
|
||||
|
||||
player_invisible = int(session.player.effects.get("invisibility", 0)) > 0
|
||||
ptile = (session.player.x, session.player.y)
|
||||
|
||||
for enemy in enemies:
|
||||
if not getattr(enemy, "is_alive", False):
|
||||
continue
|
||||
# A dead player should not be assaulted further.
|
||||
if session.player.hp <= 0:
|
||||
break
|
||||
enemy_view = compute_fov(floor.width, floor.height, floor.tiles,
|
||||
enemy.x, enemy.y, radius=SIGHT_RADIUS)
|
||||
if player_invisible:
|
||||
enemy_view.discard(ptile)
|
||||
try:
|
||||
take_enemy_turn(enemy, floor, session.player, enemy_view)
|
||||
except Exception:
|
||||
# AI must never crash the turn loop; log and soldier on.
|
||||
session.log.append(f"The {getattr(enemy, 'name', 'enemy')} hesitates.")
|
||||
# An enemy may have killed the player mid-sweep.
|
||||
if session.player.hp <= 0:
|
||||
break
|
||||
|
||||
# Enemy melee can kill the player; resolve that state immediately so the UI
|
||||
# does not render an extra frame of a "living" corpse.
|
||||
if session.player.hp <= 0:
|
||||
check_player_death(session.player, session)
|
||||
|
||||
|
||||
def _update_player_fov(session: GameSession, floor: GameMap) -> None:
|
||||
"""Recompute the player's visible grid and fold it into ``explored``."""
|
||||
vis = compute_fov(floor.width, floor.height, floor.tiles,
|
||||
session.player.x, session.player.y, radius=SIGHT_RADIUS)
|
||||
# Clear last turn's visibility, then light the freshly-seen tiles.
|
||||
for y in range(floor.height):
|
||||
vrow = floor.visible[y]
|
||||
erow = floor.explored[y]
|
||||
for x in range(floor.width):
|
||||
vrow[x] = False
|
||||
for (x, y) in vis:
|
||||
floor.visible[y][x] = True
|
||||
floor.explored[y][x] = True
|
||||
|
||||
|
||||
def _resolve_end_states(session: GameSession, floor: GameMap, announce: bool) -> str:
|
||||
"""Flip the session to ``dead`` / ``victory`` when the end condition hits.
|
||||
|
||||
Death wins over victory (a mutual kill is the player's loss). Returns the
|
||||
resulting state. ``announce`` controls whether the one-shot log lines are
|
||||
emitted (suppressed when merely re-deriving state, e.g. on load).
|
||||
"""
|
||||
if session.player.hp <= 0:
|
||||
if session.state != "dead" and announce:
|
||||
session.log.append("You have died...")
|
||||
session.state = "dead"
|
||||
return session.state
|
||||
# Victory: the Ancient Dragon is gone from the boss floor.
|
||||
if session.current_floor == len(session.dungeon) - 1:
|
||||
dragon_alive = any(
|
||||
isinstance(e, Enemy)
|
||||
and getattr(e, "kind", None) == "ancient_dragon"
|
||||
and getattr(e, "is_alive", True)
|
||||
for e in floor.entities
|
||||
)
|
||||
if not dragon_alive:
|
||||
if session.state != "victory" and announce:
|
||||
session.log.append("The Ancient Dragon lies still. You win!")
|
||||
session.state = "victory"
|
||||
return session.state
|
||||
return session.state
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# small lookup helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _enemy_at(floor: GameMap, x: int, y: int) -> Enemy | None:
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and getattr(e, "is_alive", True) and e.x == x and e.y == y:
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def _blocks_at(floor: GameMap, x: int, y: int) -> bool:
|
||||
for e in floor.entities:
|
||||
if getattr(e, "blocks", False) and e.x == x and e.y == y:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _nearest_free(floor: GameMap, x: int, y: int) -> tuple[int, int]:
|
||||
"""Spiral outwards from (x,y) for the nearest walkable, unoccupied tile."""
|
||||
for radius in range(1, 8):
|
||||
for dy in range(-radius, radius + 1):
|
||||
for dx in range(-radius, radius + 1):
|
||||
if max(abs(dx), abs(dy)) != radius:
|
||||
continue
|
||||
nx, ny = x + dx, y + dy
|
||||
if is_walkable(floor, nx, ny) and _enemy_at(floor, nx, ny) is None:
|
||||
return (nx, ny)
|
||||
return (x, y)
|
||||
|
||||
|
||||
def _cap_log(session: GameSession) -> None:
|
||||
if len(session.log) > _LOG_CAP:
|
||||
del session.log[: len(session.log) - _LOG_CAP]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# serialization
|
||||
# --------------------------------------------------------------------------- #
|
||||
def to_dict(session: GameSession) -> dict:
|
||||
"""JSON-safe snapshot of the session (visible grids excluded)."""
|
||||
return {
|
||||
"player": player_to_dict(session.player),
|
||||
"dungeon": [map_to_dict(gm) for gm in session.dungeon],
|
||||
"current_floor": int(session.current_floor),
|
||||
"log": list(session.log),
|
||||
"turn": int(session.turn),
|
||||
"state": str(session.state),
|
||||
"rng_seed": int(session.rng_seed),
|
||||
"version": 1,
|
||||
}
|
||||
|
||||
|
||||
def from_dict(d: dict) -> GameSession:
|
||||
"""Rebuild a :class:`GameSession` from a :func:`to_dict` snapshot.
|
||||
|
||||
The ``visible`` grids are reset to all-False and then the current floor's
|
||||
visibility is recomputed from the player's FOV so the resumed view is
|
||||
correct without persisting transient render state.
|
||||
"""
|
||||
session = GameSession(
|
||||
player=player_from_dict(d["player"]),
|
||||
dungeon=[map_from_dict(gm) for gm in d["dungeon"]],
|
||||
current_floor=int(d["current_floor"]),
|
||||
log=list(d.get("log", [])),
|
||||
turn=int(d.get("turn", 0)),
|
||||
state=str(d.get("state", "playing")),
|
||||
rng_seed=int(d.get("rng_seed", 0)),
|
||||
)
|
||||
if not (0 <= session.current_floor < len(session.dungeon)):
|
||||
session.current_floor = 0
|
||||
# Ensure every floor has a fresh (empty) visible grid before recomputing.
|
||||
for gm in session.dungeon:
|
||||
gm.visible = [[False] * gm.width for _ in range(gm.height)]
|
||||
_update_player_fov(session, session.floor)
|
||||
_cap_log(session)
|
||||
return session
|
||||
|
||||
|
||||
def save(session: GameSession, path: str) -> None:
|
||||
"""Persist the session to ``path`` as JSON."""
|
||||
write_json(to_dict(session), path)
|
||||
|
||||
|
||||
def load(path: str) -> GameSession:
|
||||
"""Load and validate a session previously written by :func:`save`."""
|
||||
data = read_json(path)
|
||||
session = from_dict(data)
|
||||
# Loading revives a saved game back into active play.
|
||||
if session.state == "saved":
|
||||
session.state = "playing"
|
||||
return session
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Procedural dungeon generation via BSP.
|
||||
|
||||
Geometry contract honored by every floor:
|
||||
* tiles indexed tiles[y][x]; TILE_WALL=0, TILE_FLOOR=1
|
||||
* a 1-tile wall border surrounds the map
|
||||
* rooms are carved strictly inside disjoint BSP leaves, so no two rooms ever
|
||||
overlap (their interiors are disjoint)
|
||||
* sibling rooms are joined by L-shaped corridors, so every room center is
|
||||
reachable from every other by a floor-only flood fill
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from data.constants import (
|
||||
LEAF_MIN_H,
|
||||
LEAF_MIN_W,
|
||||
MAP_H,
|
||||
MAP_W,
|
||||
ROOM_MAX_H,
|
||||
ROOM_MAX_W,
|
||||
ROOM_MIN_H,
|
||||
ROOM_MIN_W,
|
||||
SPAWN_TABLE,
|
||||
TILE_FLOOR,
|
||||
TILE_WALL,
|
||||
)
|
||||
from data.enemies import ENEMY_FLOORS
|
||||
from data.items import ITEM_BY_FLOOR
|
||||
from entities.entity import Rect
|
||||
from entities.enemy import make_enemy
|
||||
from entities.item import make_item
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: list # list[list[int]], indexed [y][x]
|
||||
rooms: list # list[Rect]
|
||||
explored: list # list[list[bool]]
|
||||
visible: list # list[list[bool]]
|
||||
entities: list = field(default_factory=list)
|
||||
stairs_down: object = None # tuple[int, int] | None
|
||||
floor_index: int = 0
|
||||
|
||||
|
||||
def is_walkable(gm: GameMap, x: int, y: int) -> bool:
|
||||
if 0 <= x < gm.width and 0 <= y < gm.height:
|
||||
return gm.tiles[y][x] == TILE_FLOOR
|
||||
return False
|
||||
|
||||
|
||||
class _Node:
|
||||
"""A rectangular BSP region (internal node or leaf)."""
|
||||
|
||||
__slots__ = ("x", "y", "w", "h", "left", "right", "room")
|
||||
|
||||
def __init__(self, x: int, y: int, w: int, h: int):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.w = w
|
||||
self.h = h
|
||||
self.left: _Node | None = None
|
||||
self.right: _Node | None = None
|
||||
self.room: Rect | None = None
|
||||
|
||||
@property
|
||||
def is_leaf(self) -> bool:
|
||||
return self.left is None and self.right is None
|
||||
|
||||
@property
|
||||
def area(self) -> int:
|
||||
return self.w * self.h
|
||||
|
||||
|
||||
def generate_floor(floor_index: int = 0, width: int = MAP_W, height: int = MAP_H,
|
||||
seed: int | None = None) -> GameMap:
|
||||
rng = random.Random(seed)
|
||||
gm = GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=[[TILE_WALL] * width for _ in range(height)],
|
||||
rooms=[],
|
||||
explored=[[False] * width for _ in range(height)],
|
||||
visible=[[False] * width for _ in range(height)],
|
||||
entities=[],
|
||||
stairs_down=None,
|
||||
floor_index=floor_index,
|
||||
)
|
||||
gen = _FloorGenerator(gm, rng)
|
||||
if floor_index == 9:
|
||||
gen.build_boss_arena()
|
||||
else:
|
||||
gen.build_bsp()
|
||||
gen.place_stairs()
|
||||
gen.spawn_entities(floor_index)
|
||||
return gm
|
||||
|
||||
|
||||
class _FloorGenerator:
|
||||
def __init__(self, gm: GameMap, rng: random.Random):
|
||||
self.gm = gm
|
||||
self.rng = rng
|
||||
|
||||
# -- BSP -----------------------------------------------------------------
|
||||
def build_bsp(self) -> None:
|
||||
# Playable interior leaves a 1-tile wall border intact.
|
||||
root = _Node(1, 1, self.gm.width - 2, self.gm.height - 2)
|
||||
target = self.rng.randint(5, 8)
|
||||
counter = [0]
|
||||
self._split(root, depth=0, target=target, counter=counter)
|
||||
self._carve_rooms(root)
|
||||
self._connect(root)
|
||||
|
||||
def _splittable(self, node: _Node) -> bool:
|
||||
return node.w >= 2 * LEAF_MIN_W or node.h >= 2 * LEAF_MIN_H
|
||||
|
||||
def _choose_axis(self, node: _Node, depth: int) -> str | None:
|
||||
can_v = node.w >= 2 * LEAF_MIN_W
|
||||
can_h = node.h >= 2 * LEAF_MIN_H
|
||||
if not (can_v or can_h):
|
||||
return None
|
||||
if can_v and can_h:
|
||||
# Bias toward halving the longer dimension; otherwise alternate by depth.
|
||||
if node.w > node.h * 1.25:
|
||||
return "v"
|
||||
if node.h > node.w * 1.25:
|
||||
return "h"
|
||||
return "v" if depth % 2 == 0 else "h"
|
||||
return "v" if can_v else "h"
|
||||
|
||||
def _split(self, node: _Node, depth: int, target: int, counter: list) -> None:
|
||||
if counter[0] >= target:
|
||||
return
|
||||
if not self._splittable(node):
|
||||
return
|
||||
axis = self._choose_axis(node, depth)
|
||||
if axis is None:
|
||||
return
|
||||
if axis == "v":
|
||||
lo, hi = LEAF_MIN_W, node.w - LEAF_MIN_W
|
||||
at = self.rng.randint(lo, hi)
|
||||
node.left = _Node(node.x, node.y, at, node.h)
|
||||
node.right = _Node(node.x + at, node.y, node.w - at, node.h)
|
||||
else:
|
||||
lo, hi = LEAF_MIN_H, node.h - LEAF_MIN_H
|
||||
at = self.rng.randint(lo, hi)
|
||||
node.left = _Node(node.x, node.y, node.w, at)
|
||||
node.right = _Node(node.x, node.y + at, node.w, node.h - at)
|
||||
counter[0] += 1
|
||||
# Depth-first; keep splitting until the budget is spent.
|
||||
self._split(node.left, depth + 1, target, counter)
|
||||
self._split(node.right, depth + 1, target, counter)
|
||||
|
||||
def _carve_rooms(self, node: _Node) -> None:
|
||||
if node.is_leaf:
|
||||
node.room = self._carve_room(node)
|
||||
self.gm.rooms.append(node.room)
|
||||
return
|
||||
if node.left is not None:
|
||||
self._carve_rooms(node.left)
|
||||
if node.right is not None:
|
||||
self._carve_rooms(node.right)
|
||||
|
||||
def _carve_room(self, node: _Node) -> Rect:
|
||||
# Shrink 1-2 tiles in from each leaf edge, clamped so the room still fits.
|
||||
margin = self.rng.randint(1, 2)
|
||||
max_mw = max(0, (node.w - ROOM_MIN_W) // 2)
|
||||
max_mh = max(0, (node.h - ROOM_MIN_H) // 2)
|
||||
mw = min(margin, max_mw)
|
||||
mh = min(margin, max_mh)
|
||||
avail_w = node.w - 2 * mw
|
||||
avail_h = node.h - 2 * mh
|
||||
rw = min(ROOM_MAX_W, avail_w)
|
||||
rh = min(ROOM_MAX_H, avail_h)
|
||||
ox = self.rng.randint(0, avail_w - rw)
|
||||
oy = self.rng.randint(0, avail_h - rh)
|
||||
rx = node.x + mw + ox
|
||||
ry = node.y + mh + oy
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
for yy in range(ry, ry + rh):
|
||||
row = self.gm.tiles[yy]
|
||||
for xx in range(rx, rx + rw):
|
||||
row[xx] = TILE_FLOOR
|
||||
return room
|
||||
|
||||
def _connect(self, node: _Node) -> Rect | None:
|
||||
"""Recursively join sibling rooms; returns a representative room."""
|
||||
if node.is_leaf:
|
||||
return node.room
|
||||
left = self._connect(node.left) if node.left is not None else None
|
||||
right = self._connect(node.right) if node.right is not None else None
|
||||
if left is not None and right is not None:
|
||||
self._draw_corridor(left.center, right.center)
|
||||
return left or right
|
||||
|
||||
def _draw_corridor(self, c1: tuple[int, int], c2: tuple[int, int]) -> None:
|
||||
x1, y1 = c1
|
||||
x2, y2 = c2
|
||||
if self.rng.random() < 0.5:
|
||||
self._h_line(x1, x2, y1)
|
||||
self._v_line(y1, y2, x2)
|
||||
else:
|
||||
self._v_line(y1, y2, x1)
|
||||
self._h_line(x1, x2, y2)
|
||||
|
||||
def _h_line(self, x1: int, x2: int, y: int) -> None:
|
||||
if not (0 <= y < self.gm.height):
|
||||
return
|
||||
row = self.gm.tiles[y]
|
||||
for x in range(min(x1, x2), max(x1, x2) + 1):
|
||||
if 0 <= x < self.gm.width:
|
||||
row[x] = TILE_FLOOR
|
||||
|
||||
def _v_line(self, y1: int, y2: int, x: int) -> None:
|
||||
if not (0 <= x < self.gm.width):
|
||||
return
|
||||
for y in range(min(y1, y2), max(y1, y2) + 1):
|
||||
if 0 <= y < self.gm.height:
|
||||
self.gm.tiles[y][x] = TILE_FLOOR
|
||||
|
||||
# -- stairs --------------------------------------------------------------
|
||||
def place_stairs(self) -> None:
|
||||
if len(self.gm.rooms) < 2:
|
||||
return
|
||||
spawn = self.gm.rooms[0].center
|
||||
farthest = max(self.gm.rooms[1:], key=lambda r: _chebyshev(r.center, spawn))
|
||||
self.gm.stairs_down = farthest.center
|
||||
|
||||
# -- floor 9 boss arena --------------------------------------------------
|
||||
def build_boss_arena(self) -> None:
|
||||
rw, rh = 20, 15
|
||||
rx = (self.gm.width - rw) // 2
|
||||
ry = (self.gm.height - rh) // 2
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
self.gm.rooms.append(room)
|
||||
for yy in range(ry, ry + rh):
|
||||
row = self.gm.tiles[yy]
|
||||
for xx in range(rx, rx + rw):
|
||||
row[xx] = TILE_FLOOR
|
||||
# No stairs in the boss arena (victory is the dragon's death).
|
||||
self.gm.stairs_down = None
|
||||
|
||||
# -- entity spawning -----------------------------------------------------
|
||||
def spawn_entities(self, floor_index: int) -> None:
|
||||
if not self.gm.rooms:
|
||||
return
|
||||
if floor_index == 9:
|
||||
self._spawn_boss_floor()
|
||||
return
|
||||
spec = SPAWN_TABLE.get(floor_index, (0, 0, 0, 0))
|
||||
e_min, e_max, i_min, i_max = spec
|
||||
self._spawn_enemies(e_min, e_max, floor_index)
|
||||
self._spawn_items(i_min, i_max, floor_index)
|
||||
|
||||
def _spawn_boss_floor(self) -> None:
|
||||
"""Floor 9: the Ancient Dragon alone, plus two healing potions at the
|
||||
entrance. No other enemies and no stairs (cleared in build_boss_arena)."""
|
||||
room = self.gm.rooms[0]
|
||||
cx, cy = room.center
|
||||
corners = [
|
||||
(room.x + 1, room.y + 1),
|
||||
(room.x + room.w - 2, room.y + 1),
|
||||
(room.x + 1, room.y + room.h - 2),
|
||||
(room.x + room.w - 2, room.y + room.h - 2),
|
||||
]
|
||||
dragon_pos = max(corners, key=lambda c: _chebyshev(c, (cx, cy)))
|
||||
if is_walkable(self.gm, *dragon_pos):
|
||||
self.gm.entities.append(make_enemy("ancient_dragon", *dragon_pos))
|
||||
for pos in ((cx + 1, cy), (cx - 1, cy)):
|
||||
if is_walkable(self.gm, *pos):
|
||||
self.gm.entities.append(make_item("Healing Potion", *pos))
|
||||
|
||||
def _spawn_enemies(self, e_min: int, e_max: int, floor_index: int) -> None:
|
||||
if e_max <= 0:
|
||||
return
|
||||
n = self.rng.randint(e_min, e_max)
|
||||
for _ in range(n):
|
||||
kind = self._pick_enemy_kind(floor_index)
|
||||
if kind is None:
|
||||
break
|
||||
pos = self._free_tile(avoid_spawn_room=True)
|
||||
if pos is None:
|
||||
break
|
||||
try:
|
||||
self.gm.entities.append(make_enemy(kind, *pos))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _spawn_items(self, i_min: int, i_max: int, floor_index: int) -> None:
|
||||
if i_max <= 0:
|
||||
return
|
||||
n = self.rng.randint(i_min, i_max)
|
||||
for _ in range(n):
|
||||
pos = self._free_tile()
|
||||
if pos is None:
|
||||
break
|
||||
name = ITEM_BY_FLOOR(floor_index, self.rng)
|
||||
if not name:
|
||||
continue
|
||||
try:
|
||||
self.gm.entities.append(make_item(name, *pos))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _pick_enemy_kind(self, floor_index: int) -> str | None:
|
||||
"""Random kind valid on this floor (excludes split-spawned small_slime
|
||||
and the floor-9 boss, which are placed explicitly)."""
|
||||
pool = [
|
||||
kind for kind, (lo, hi) in ENEMY_FLOORS.items()
|
||||
if lo <= floor_index <= hi
|
||||
and kind not in ("small_slime", "ancient_dragon")
|
||||
]
|
||||
return self.rng.choice(pool) if pool else None
|
||||
|
||||
def _free_tile(self, avoid_spawn_room: bool = False) -> tuple[int, int] | None:
|
||||
rooms = list(self.gm.rooms)
|
||||
if avoid_spawn_room and len(rooms) > 1:
|
||||
rooms = rooms[1:]
|
||||
occupied = {
|
||||
(getattr(e, "x", None), getattr(e, "y", None))
|
||||
for e in self.gm.entities
|
||||
if getattr(e, "blocks", False) or hasattr(e, "behavior")
|
||||
}
|
||||
for _ in range(80):
|
||||
room = self.rng.choice(rooms)
|
||||
x = self.rng.randint(room.x, room.x + room.w - 1)
|
||||
y = self.rng.randint(room.y, room.y + room.h - 1)
|
||||
if (x, y) in occupied or not is_walkable(self.gm, x, y):
|
||||
continue
|
||||
return (x, y)
|
||||
return None
|
||||
|
||||
|
||||
def _chebyshev(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Grid-based A* pathfinding with the Manhattan heuristic.
|
||||
|
||||
Implemented from scratch (no third-party deps, no pygame). Used by the enemy AI
|
||||
to chase / flee across the dungeon grid.
|
||||
|
||||
Geometry contract (shared with the rest of the engine):
|
||||
* tiles are indexed ``tiles[y][x]``; ``TILE_WALL=0``, ``TILE_FLOOR=1``.
|
||||
* a tile is *walkable* iff it is in-bounds, equals ``1`` (floor), and is not a
|
||||
member of the ``blocked`` set (e.g. tiles occupied by other actors).
|
||||
* movement is 4-connected (no diagonals); every step costs 1.
|
||||
|
||||
The public entry point :func:`astar` is pure: it never mutates ``tiles``,
|
||||
``blocked``, ``start`` or ``goal`` and performs all of its bookkeeping in local
|
||||
structures. Tie-breaking is deterministic (a monotonic push counter gives FIFO
|
||||
ordering among equal-priority frontier nodes), so the same inputs always yield
|
||||
the same path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
|
||||
__all__ = ["astar"]
|
||||
|
||||
# 4-connected neighbourhood (orthogonal moves only).
|
||||
_NEIGHBORS = ((1, 0), (-1, 0), (0, 1), (0, -1))
|
||||
|
||||
|
||||
def astar(
|
||||
width: int,
|
||||
height: int,
|
||||
tiles,
|
||||
start: tuple,
|
||||
goal: tuple,
|
||||
blocked: frozenset = frozenset(),
|
||||
) -> "list[tuple[int, int]] | None":
|
||||
"""Find a shortest path from ``start`` to ``goal`` on a floor grid.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
width, height:
|
||||
Dimensions of ``tiles``.
|
||||
tiles:
|
||||
2D sequence indexed ``tiles[y][x]``; ``1`` means floor.
|
||||
start, goal:
|
||||
``(x, y)`` integer coordinate pairs. Both endpoints are included in the
|
||||
returned path.
|
||||
blocked:
|
||||
Any iterable of ``(x, y)`` pairs treated as impassable (typically the
|
||||
tiles currently occupied by other entities). Defaults to an empty
|
||||
frozenset.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[tuple[int, int]] | None
|
||||
The path from ``start`` to ``goal`` inclusive, as a list of ``(x, y)``
|
||||
tuples, or ``None`` when no route exists (goal walled off, blocked, or
|
||||
out of bounds).
|
||||
"""
|
||||
sx, sy = start
|
||||
gx, gy = goal
|
||||
|
||||
# Endpoints must live on the map.
|
||||
if not (0 <= sx < width and 0 <= sy < height):
|
||||
return None
|
||||
if not (0 <= gx < width and 0 <= gy < height):
|
||||
return None
|
||||
|
||||
def walkable(x: int, y: int) -> bool:
|
||||
return (
|
||||
0 <= x < width
|
||||
and 0 <= y < height
|
||||
and tiles[y][x] == 1
|
||||
and (x, y) not in blocked
|
||||
)
|
||||
|
||||
# Trivial case: already there. Reported even for non-floor tiles so callers
|
||||
# asking "am I at my destination?" always get a sensible answer.
|
||||
if start == goal:
|
||||
return [start]
|
||||
|
||||
# An un-walkable endpoint means no legal route can begin / end there.
|
||||
if not walkable(sx, sy) or not walkable(gx, gy):
|
||||
return None
|
||||
|
||||
# Manhattan distance to the goal — admissible & consistent for 4-connected
|
||||
# grids with uniform step cost, so the first time we pop the goal we have a
|
||||
# shortest path.
|
||||
def h(x: int, y: int) -> int:
|
||||
return abs(x - gx) + abs(y - gy)
|
||||
|
||||
# Priority queue of (f_score, tiebreak_counter, x, y). The monotonic counter
|
||||
# makes ordering fully deterministic for equal f-scores (FIFO by insertion),
|
||||
# and guarantees heapq never has to compare the (x, y) tuples directly.
|
||||
open_heap: list = []
|
||||
counter = 0
|
||||
g_score = {start: 0}
|
||||
came_from: dict = {}
|
||||
|
||||
heapq.heappush(open_heap, (h(sx, sy), counter, sx, sy))
|
||||
counter += 1
|
||||
|
||||
closed: set = set()
|
||||
|
||||
while open_heap:
|
||||
f, _, x, y = heapq.heappop(open_heap)
|
||||
node = (x, y)
|
||||
|
||||
# Lazy deletion: a node may have been pushed several times before being
|
||||
# settled. Skip any we've already expanded via a cheaper route.
|
||||
if node in closed:
|
||||
continue
|
||||
|
||||
if node == goal:
|
||||
path = [node]
|
||||
cur = node
|
||||
while cur in came_from:
|
||||
cur = came_from[cur]
|
||||
path.append(cur)
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
closed.add(node)
|
||||
base_g = g_score[node]
|
||||
|
||||
for dx, dy in _NEIGHBORS:
|
||||
nx, ny = x + dx, y + dy
|
||||
if not walkable(nx, ny):
|
||||
continue
|
||||
nxt = (nx, ny)
|
||||
if nxt in closed:
|
||||
continue
|
||||
tentative_g = base_g + 1
|
||||
if tentative_g < g_score.get(nxt, float("inf")):
|
||||
g_score[nxt] = tentative_g
|
||||
came_from[nxt] = node
|
||||
heapq.heappush(open_heap, (tentative_g + h(nx, ny), counter, nx, ny))
|
||||
counter += 1
|
||||
|
||||
# Frontier exhausted without reaching the goal: it is unreachable.
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
if __name__ == "__main__":
|
||||
# Self-check: exercise the interesting cases without relying on the rest of
|
||||
# the engine. Exits non-zero on the first failure.
|
||||
FLOOR, WALL = 1, 0
|
||||
|
||||
def _grid(w, h, fill=FLOOR):
|
||||
return [[fill] * w for _ in range(h)]
|
||||
|
||||
# 1. Straight-line optimal length on open ground.
|
||||
g = _grid(10, 10)
|
||||
p = astar(10, 10, g, (0, 0), (3, 0))
|
||||
assert p is not None, "open-ground path should exist"
|
||||
assert p[0] == (0, 0) and p[-1] == (3, 0), "endpoints"
|
||||
assert len(p) == 4, f"optimal open length is 4, got {len(p)}"
|
||||
assert len(p) == len(set(p)), "path revisits a tile"
|
||||
|
||||
# 2. Contiguity + walkability of every step.
|
||||
for i, (x, y) in enumerate(p):
|
||||
assert g[y][x] == FLOOR, f"path crosses wall at {(x, y)}"
|
||||
if i > 0:
|
||||
px, py = p[i - 1]
|
||||
assert max(abs(x - px), abs(y - py)) == 1, f"non-contiguous step at {i}"
|
||||
|
||||
# 3. Manhattan-optimality on an L-shaped open route.
|
||||
p2 = astar(10, 10, g, (0, 0), (4, 5))
|
||||
assert p2 is not None and len(p2) == 10, f"L-route length, got {p2}"
|
||||
|
||||
# 4. start == goal.
|
||||
assert astar(10, 10, g, (2, 2), (2, 2)) == [(2, 2)], "self path"
|
||||
|
||||
# 5. Unreachable -> None (sealed box).
|
||||
sealed = _grid(7, 7)
|
||||
for x in range(7):
|
||||
sealed[3][x] = WALL # full wall row, no gap
|
||||
assert astar(7, 7, sealed, (1, 1), (5, 5)) is None, "sealed map should be None"
|
||||
|
||||
# 6. Path threads a single gap in a wall column.
|
||||
W = H = 12
|
||||
t = _grid(W, H)
|
||||
for y in range(H):
|
||||
t[y][6] = WALL
|
||||
t[6][6] = FLOOR # the only gap
|
||||
pg = astar(W, H, t, (1, 1), (10, 10))
|
||||
assert pg is not None, "gap path should exist"
|
||||
assert pg[0] == (1, 1) and pg[-1] == (10, 10)
|
||||
assert all(t[y][x] == FLOOR for x, y in pg), "gap path crosses a wall"
|
||||
# Must actually use the gap.
|
||||
assert (6, 6) in pg, "gap path should pass through the gap"
|
||||
|
||||
# 7. `blocked` forces a detour and can close a gap entirely.
|
||||
t2 = [row[:] for row in t]
|
||||
none_when_gap_blocked = astar(W, H, t2, (1, 1), (10, 10), blocked={(6, 6)})
|
||||
assert none_when_gap_blocked is None, "blocking the only gap => None"
|
||||
|
||||
# 8. Determinism: repeated calls give identical results.
|
||||
again = astar(W, H, t, (1, 1), (10, 10))
|
||||
assert again == pg, "non-deterministic path"
|
||||
|
||||
# 9. Out-of-bounds endpoints -> None, no crash.
|
||||
assert astar(W, H, t, (-1, 1), (10, 10)) is None
|
||||
assert astar(W, H, t, (1, 1), (W, H)) is None
|
||||
|
||||
# 10. No mutation of inputs.
|
||||
snapshot = [row[:] for row in t]
|
||||
bl_snapshot = frozenset({(6, 6)})
|
||||
_ = astar(W, H, t, (1, 1), (10, 10), blocked=bl_snapshot)
|
||||
assert t == snapshot, "tiles mutated"
|
||||
assert bl_snapshot == frozenset({(6, 6)}), "blocked mutated"
|
||||
|
||||
print("pathfinding self-check OK")
|
||||
@@ -0,0 +1,216 @@
|
||||
"""JSON serialization helpers for game entities, items and maps.
|
||||
|
||||
These are thin, pure data <-> dict converters used by ``engine.game_state``.
|
||||
Everything produced is JSON-safe (tuples -> lists, sets -> lists); the inverse
|
||||
converters rebuild the typed dataclass instances.
|
||||
|
||||
Persistence policy (per plan.md §8):
|
||||
* Player stats, level, XP, inventory, equipped items, position: persisted.
|
||||
* Dungeon: all 10 floors — tiles, rooms, explored, entities, stairs, index.
|
||||
* Effects timers (strength / invisibility): persisted.
|
||||
* ``visible`` grid: NOT persisted — recomputed from FOV on load.
|
||||
|
||||
Reconstruction does not consult the item/enemy catalogs for stats: the saved
|
||||
dict is the source of truth, so a mid-run edit to an instance survives a round
|
||||
trip. ``color`` tuples are restored as tuples (rendering compares them).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from entities.entity import Rect
|
||||
from entities.player import Player
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
__all__ = [
|
||||
"rect_to_dict", "rect_from_dict",
|
||||
"item_to_dict", "item_from_dict",
|
||||
"enemy_to_dict", "enemy_from_dict",
|
||||
"player_to_dict", "player_from_dict",
|
||||
"map_to_dict", "map_from_dict",
|
||||
"write_json", "read_json",
|
||||
]
|
||||
|
||||
|
||||
def _tup(value) -> tuple | None:
|
||||
"""Coerce a JSON-loaded list back into a tuple; pass None through."""
|
||||
if value is None:
|
||||
return None
|
||||
return tuple(value)
|
||||
|
||||
|
||||
def rect_to_dict(r: Rect) -> dict:
|
||||
return {"x": r.x, "y": r.y, "w": r.w, "h": r.h}
|
||||
|
||||
|
||||
def rect_from_dict(d: dict) -> Rect:
|
||||
return Rect(x=int(d["x"]), y=int(d["y"]), w=int(d["w"]), h=int(d["h"]))
|
||||
|
||||
|
||||
def item_to_dict(it: Item | None) -> dict | None:
|
||||
if it is None:
|
||||
return None
|
||||
return {
|
||||
"name": it.name,
|
||||
"category": it.category,
|
||||
"x": it.x,
|
||||
"y": it.y,
|
||||
"stats": dict(it.stats or {}),
|
||||
"effect": dict(it.effect or {}),
|
||||
"glyph": it.glyph,
|
||||
"color": list(it.color),
|
||||
"blocks": bool(it.blocks),
|
||||
"is_alive": bool(it.is_alive),
|
||||
}
|
||||
|
||||
|
||||
def item_from_dict(d: dict | None) -> Item | None:
|
||||
if d is None:
|
||||
return None
|
||||
return Item(
|
||||
name=d["name"],
|
||||
category=d["category"],
|
||||
x=int(d["x"]),
|
||||
y=int(d["y"]),
|
||||
stats=dict(d.get("stats", {}) or {}),
|
||||
effect=dict(d.get("effect", {}) or {}),
|
||||
glyph=d.get("glyph", "?"),
|
||||
color=tuple(d.get("color", (200, 200, 200))),
|
||||
blocks=bool(d.get("blocks", False)),
|
||||
is_alive=bool(d.get("is_alive", True)),
|
||||
)
|
||||
|
||||
|
||||
def enemy_to_dict(e: Enemy | None) -> dict | None:
|
||||
if e is None:
|
||||
return None
|
||||
return {
|
||||
"x": e.x, "y": e.y,
|
||||
"name": e.name, "glyph": e.glyph, "color": list(e.color),
|
||||
"kind": e.kind,
|
||||
"hp": e.hp, "max_hp": e.max_hp,
|
||||
"power": e.power, "armor": e.armor, "speed": e.speed,
|
||||
"behavior": e.behavior, "xp": e.xp,
|
||||
"is_alive": bool(e.is_alive),
|
||||
"last_known_pos": list(e.last_known_pos) if e.last_known_pos is not None else None,
|
||||
"ranged_power": int(e.ranged_power),
|
||||
"can_split": bool(e.can_split),
|
||||
"blocks": bool(e.blocks),
|
||||
}
|
||||
|
||||
|
||||
def enemy_from_dict(d: dict | None) -> Enemy | None:
|
||||
if d is None:
|
||||
return None
|
||||
return Enemy(
|
||||
x=int(d["x"]), y=int(d["y"]),
|
||||
name=d["name"], glyph=d["glyph"], color=tuple(d["color"]),
|
||||
kind=d["kind"],
|
||||
hp=int(d["hp"]), max_hp=int(d["max_hp"]),
|
||||
power=int(d["power"]), armor=int(d["armor"]), speed=int(d["speed"]),
|
||||
behavior=d["behavior"], xp=int(d["xp"]),
|
||||
is_alive=bool(d.get("is_alive", True)),
|
||||
last_known_pos=_tup(d.get("last_known_pos")),
|
||||
ranged_power=int(d.get("ranged_power", 0)),
|
||||
can_split=bool(d.get("can_split", False)),
|
||||
blocks=bool(d.get("blocks", True)),
|
||||
)
|
||||
|
||||
|
||||
def player_to_dict(p: Player) -> dict:
|
||||
return {
|
||||
"x": p.x, "y": p.y,
|
||||
"hp": p.hp, "max_hp": p.max_hp,
|
||||
"power": p.power, "armor": p.armor,
|
||||
"accuracy": p.accuracy, "evasion": p.evasion,
|
||||
"crit_chance": p.crit_chance, "speed": p.speed,
|
||||
"level": p.level, "xp": p.xp,
|
||||
"inventory": [item_to_dict(i) for i in p.inventory],
|
||||
"weapon": item_to_dict(p.weapon),
|
||||
"armor_item": item_to_dict(p.armor_item),
|
||||
"effects": {k: v for k, v in (p.effects or {}).items()},
|
||||
"name": p.name, "glyph": p.glyph, "color": list(p.color),
|
||||
"blocks": bool(p.blocks), "is_alive": bool(p.is_alive),
|
||||
}
|
||||
|
||||
|
||||
def player_from_dict(d: dict) -> Player:
|
||||
return Player(
|
||||
x=int(d["x"]), y=int(d["y"]),
|
||||
hp=int(d["hp"]), max_hp=int(d["max_hp"]),
|
||||
power=int(d["power"]), armor=int(d["armor"]),
|
||||
accuracy=int(d["accuracy"]), evasion=int(d["evasion"]),
|
||||
crit_chance=float(d["crit_chance"]), speed=int(d["speed"]),
|
||||
level=int(d["level"]), xp=int(d["xp"]),
|
||||
inventory=[item_from_dict(i) for i in d.get("inventory", [])],
|
||||
weapon=item_from_dict(d.get("weapon")),
|
||||
armor_item=item_from_dict(d.get("armor_item")),
|
||||
effects={k: v for k, v in (d.get("effects", {}) or {}).items()},
|
||||
name=d.get("name", "Adventurer"),
|
||||
glyph=d.get("glyph", "@"),
|
||||
color=tuple(d.get("color", (255, 255, 255))),
|
||||
blocks=bool(d.get("blocks", True)),
|
||||
is_alive=bool(d.get("is_alive", True)),
|
||||
)
|
||||
|
||||
|
||||
def map_to_dict(gm: GameMap) -> dict:
|
||||
return {
|
||||
"width": gm.width,
|
||||
"height": gm.height,
|
||||
"tiles": [[int(v) for v in row] for row in gm.tiles],
|
||||
"rooms": [rect_to_dict(r) for r in gm.rooms],
|
||||
"explored": [[bool(v) for v in row] for row in gm.explored],
|
||||
# visible intentionally omitted — recomputed on load.
|
||||
"entities": [
|
||||
enemy_to_dict(e) if isinstance(e, Enemy)
|
||||
else item_to_dict(e) if isinstance(e, Item)
|
||||
else None
|
||||
for e in gm.entities
|
||||
],
|
||||
"stairs_down": list(gm.stairs_down) if gm.stairs_down is not None else None,
|
||||
"floor_index": gm.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def map_from_dict(d: dict) -> GameMap:
|
||||
width = int(d["width"])
|
||||
height = int(d["height"])
|
||||
entities: list = []
|
||||
for e in d.get("entities", []):
|
||||
if e is None:
|
||||
continue
|
||||
kind = e.get("kind")
|
||||
if kind is not None:
|
||||
entities.append(enemy_from_dict(e))
|
||||
else:
|
||||
entities.append(item_from_dict(e))
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=[[int(v) for v in row] for row in d["tiles"]],
|
||||
rooms=[rect_from_dict(r) for r in d.get("rooms", [])],
|
||||
explored=[[bool(v) for v in row] for row in d["explored"]],
|
||||
visible=[[False] * width for _ in range(height)],
|
||||
entities=entities,
|
||||
stairs_down=_tup(d.get("stairs_down")),
|
||||
floor_index=int(d.get("floor_index", 0)),
|
||||
)
|
||||
|
||||
|
||||
def write_json(data: Any, path: str) -> None:
|
||||
"""Atomically-ish JSON dump; errors propagate to the caller for handling."""
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, separators=(",", ":"))
|
||||
import os
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def read_json(path: str) -> Any:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
Reference in new issue
Block a user