(Underdepths) Pass 5
This commit is contained in:
1 parent
05e340dec2
commit
b6d2a058e3
53 files changed
+5020
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,387 @@
|
||||
"""Intent dispatch: translate a logical key into a session mutation.
|
||||
|
||||
``apply_input(session, key)`` is the only entry point the game loop calls. It
|
||||
never raises on valid game state; every combat event, pickup, level-up and
|
||||
status change logs a human-readable message (the log is the feedback channel).
|
||||
|
||||
Turn model: movement, melee, wait, pickup, quaff and read all spend a turn and
|
||||
trigger an enemy turn afterwards (``_end_turn``). Descent changes floors (no
|
||||
enemy turn). Menus / mute / How-to-Play are presentation-layer concerns, so
|
||||
they are graceful no-ops here (main.py owns their on-screen effect).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from engine.combat import roll_attack
|
||||
from engine.fov import compute_fov
|
||||
from engine.serializers import session_to_dict
|
||||
from ai.behaviors import act_enemy, split_on_death
|
||||
from data.constants import SIGHT_RADIUS, SAVE_FILE
|
||||
|
||||
_LOG_MAX = 50
|
||||
_DIRS: dict[str, tuple[int, int]] = {
|
||||
"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- dispatch
|
||||
def apply_input(session: Any, key: str) -> None:
|
||||
"""Apply one logical input to ``session``. Unknown keys are ignored."""
|
||||
if not isinstance(key, str):
|
||||
return
|
||||
if key in _DIRS:
|
||||
dx, dy = _DIRS[key]
|
||||
_move(session, dx, dy)
|
||||
return
|
||||
if key == "g":
|
||||
_pickup(session)
|
||||
elif key == "f":
|
||||
_descend(session)
|
||||
elif key == "q":
|
||||
_quaff(session)
|
||||
elif key == "r":
|
||||
_read(session)
|
||||
elif key == "e":
|
||||
_equip(session)
|
||||
elif key == "i":
|
||||
_inventory_info(session)
|
||||
elif key == "S":
|
||||
_save(session)
|
||||
elif key == "wait":
|
||||
_end_turn(session)
|
||||
elif key in ("?", "m", "escape"):
|
||||
# Overlays / mute live in the presentation layer (main.py); safe no-op.
|
||||
return
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- queries
|
||||
def item_under_player(session: Any) -> Any:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
return next((e for e in gm.entities if _is_item(e) and e.x == p.x and e.y == p.y), None)
|
||||
|
||||
|
||||
def is_on_stairs(session: Any) -> bool:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
return gm.stairs_down is not None and (session.player.x, session.player.y) == gm.stairs_down
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ primitives
|
||||
def _log(session: Any, msg: str) -> None:
|
||||
session.log.append(msg)
|
||||
if len(session.log) > _LOG_MAX:
|
||||
del session.log[: len(session.log) - _LOG_MAX]
|
||||
|
||||
|
||||
def _is_enemy(e: Any) -> bool:
|
||||
return bool(getattr(e, "behavior", "")) and getattr(e, "hp", 1) > 0
|
||||
|
||||
|
||||
def _is_item(e: Any) -> bool:
|
||||
return getattr(e, "category", "") != "" and not getattr(e, "behavior", "")
|
||||
|
||||
|
||||
def _enemy_at(gm: Any, x: int, y: int) -> Any:
|
||||
return next((e for e in gm.entities if _is_enemy(e) and e.x == x and e.y == y), None)
|
||||
|
||||
|
||||
def _recompute_fov(session: Any) -> set[tuple[int, int]]:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
vis = compute_fov(gm, (p.x, p.y), SIGHT_RADIUS)
|
||||
for y in range(gm.height):
|
||||
vrow = gm.visible[y]
|
||||
for x in range(gm.width):
|
||||
vrow[x] = False
|
||||
for (x, y) in vis:
|
||||
gm.visible[y][x] = True
|
||||
gm.explored[y][x] = True
|
||||
return vis
|
||||
|
||||
|
||||
def _end_turn(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
visible = _recompute_fov(session)
|
||||
_advance_enemies(session, visible)
|
||||
if session.state == "playing":
|
||||
_tick_effects(session)
|
||||
session.turn += 1
|
||||
|
||||
|
||||
def _advance_enemies(session: Any, visible: set[tuple[int, int]]) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
vis = visible
|
||||
if p.effect_timers.get("invisibility", 0) > 0:
|
||||
vis = visible - {(p.x, p.y)}
|
||||
for enemy in list(gm.entities):
|
||||
if not _is_enemy(enemy) or session.state != "playing":
|
||||
continue
|
||||
act_enemy(enemy, gm, p, vis, random)
|
||||
if p.hp <= 0:
|
||||
p.hp = 0
|
||||
session.state = "dead"
|
||||
_log(session, "You have been slain. The Underdepths claim another soul.")
|
||||
break
|
||||
|
||||
|
||||
def _tick_effects(session: Any) -> None:
|
||||
timers = session.player.effect_timers
|
||||
for k in list(timers.keys()):
|
||||
timers[k] -= 1
|
||||
if timers[k] <= 0:
|
||||
del timers[k]
|
||||
_log(session, f"Your {k} effect wears off.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- movement
|
||||
def _move(session: Any, dx: int, dy: int) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
gm = session.dungeon[session.current_floor]
|
||||
tx, ty = p.x + dx, p.y + dy
|
||||
enemy = _enemy_at(gm, tx, ty)
|
||||
if enemy is not None:
|
||||
_player_attack(session, enemy)
|
||||
_end_turn(session)
|
||||
return
|
||||
if gm.walkable(tx, ty):
|
||||
p.x, p.y = tx, ty
|
||||
_end_turn(session)
|
||||
return
|
||||
# Bumped a wall: no turn spent (standard roguelike convention).
|
||||
|
||||
|
||||
def _player_attack(session: Any, enemy: Any) -> None:
|
||||
roll = roll_attack(session.player, enemy, random)
|
||||
name = getattr(enemy, "name", "enemy")
|
||||
if not roll.hit:
|
||||
_log(session, f"You miss the {name}.")
|
||||
return
|
||||
enemy.hp -= roll.damage
|
||||
if roll.crit:
|
||||
_log(session, f"Critical! You strike the {name} for {roll.damage} damage!")
|
||||
else:
|
||||
_log(session, f"You hit the {name} for {roll.damage} damage.")
|
||||
if enemy.hp <= 0:
|
||||
_defeat_enemy(session, enemy)
|
||||
|
||||
|
||||
def _defeat_enemy(session: Any, enemy: Any) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
_log(session, f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)")
|
||||
levels = session.player.gain_xp(enemy.xp_value)
|
||||
if levels:
|
||||
_log(session, f"You reach level {session.player.level}! (HP fully restored)")
|
||||
if enemy in gm.entities:
|
||||
gm.entities.remove(enemy)
|
||||
if getattr(enemy, "can_split", False):
|
||||
spawned = split_on_death(enemy, gm)
|
||||
for baby in spawned:
|
||||
gm.entities.append(baby)
|
||||
if spawned:
|
||||
_log(session, f"The {enemy.name} splits into Small Slimes!")
|
||||
if getattr(enemy, "kind", "") == "ancient_dragon" and session.current_floor == 9:
|
||||
session.state = "victory"
|
||||
_log(session, "You slew the Ancient Dragon! Underdepths is conquered.")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- actions
|
||||
def _pickup(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
item = item_under_player(session)
|
||||
if item is None:
|
||||
_log(session, "There is nothing here to pick up.")
|
||||
return
|
||||
gm = session.dungeon[session.current_floor]
|
||||
gm.entities.remove(item)
|
||||
session.player.inventory.append(item)
|
||||
_log(session, f"You pick up the {item.name}.")
|
||||
_end_turn(session)
|
||||
|
||||
|
||||
def _descend(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
gm = session.dungeon[session.current_floor]
|
||||
if gm.stairs_down is None or (p.x, p.y) != gm.stairs_down:
|
||||
_log(session, "Stand on the yellow > stairs, then press F to descend.")
|
||||
return
|
||||
session.current_floor += 1
|
||||
ngm = session.dungeon[session.current_floor]
|
||||
sp = ngm.spawn or (1, 1)
|
||||
p.x, p.y = sp
|
||||
_log(session, f"You descend to floor {session.current_floor + 1}.")
|
||||
_recompute_fov(session)
|
||||
session.turn += 1
|
||||
|
||||
|
||||
def _quaff(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
potion = next((it for it in p.inventory if getattr(it, "category", "") == "potion"), None)
|
||||
if potion is None:
|
||||
_log(session, "You have no potions to quaff.")
|
||||
return
|
||||
p.inventory.remove(potion)
|
||||
eff = potion.stats.get("effect")
|
||||
if eff == "heal":
|
||||
before = p.hp
|
||||
p.hp = min(p.max_hp, p.hp + potion.stats.get("amount", 30))
|
||||
_log(session, f"You quaff a {potion.name}. (+{p.hp - before} HP)")
|
||||
elif eff == "strength":
|
||||
p.effect_timers["strength"] = potion.stats.get("duration", 20)
|
||||
_log(session, f"You quaff a {potion.name}. (+{p.weapon_power - p.power} power)")
|
||||
elif eff == "invisibility":
|
||||
p.effect_timers["invisibility"] = potion.stats.get("duration", 15)
|
||||
_log(session, f"You quaff a {potion.name}. (foes cannot see you)")
|
||||
else:
|
||||
_log(session, f"You quaff a {potion.name}.")
|
||||
_end_turn(session)
|
||||
|
||||
|
||||
def _read(session: Any) -> None:
|
||||
if session.state != "playing":
|
||||
return
|
||||
p = session.player
|
||||
scroll = next((it for it in p.inventory if getattr(it, "category", "") == "scroll"), None)
|
||||
if scroll is None:
|
||||
_log(session, "You have no scrolls to read.")
|
||||
return
|
||||
p.inventory.remove(scroll)
|
||||
eff = scroll.stats.get("effect")
|
||||
if eff == "fireball":
|
||||
_fireball(session, scroll.stats)
|
||||
elif eff == "teleport":
|
||||
_teleport(session)
|
||||
elif eff == "mapping":
|
||||
gm = session.dungeon[session.current_floor]
|
||||
for y in range(gm.height):
|
||||
for x in range(gm.width):
|
||||
gm.explored[y][x] = True
|
||||
_log(session, "The scroll reveals the entire floor.")
|
||||
else:
|
||||
_log(session, f"You read a {scroll.name}.")
|
||||
_end_turn(session)
|
||||
|
||||
|
||||
def _fireball(session: Any, stats: dict) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
radius = stats.get("radius", 3)
|
||||
dmg = stats.get("damage", 20)
|
||||
enemies = [e for e in gm.entities if _is_enemy(e)]
|
||||
if not enemies:
|
||||
_log(session, "The fireball fizzles — no target in sight.")
|
||||
return
|
||||
target = min(enemies, key=lambda e: max(abs(e.x - p.x), abs(e.y - p.y)))
|
||||
cx, cy = target.x, target.y
|
||||
_log(session, f"A fireball erupts! ({dmg} damage, radius {radius})")
|
||||
for e in [en for en in enemies if max(abs(en.x - cx), abs(en.y - cy)) <= radius]:
|
||||
e.hp -= dmg
|
||||
_log(session, f"The {e.name} is caught in the blast. ({dmg} damage)")
|
||||
if e.hp <= 0:
|
||||
_defeat_enemy(session, e)
|
||||
|
||||
|
||||
def _teleport(session: Any) -> None:
|
||||
gm = session.dungeon[session.current_floor]
|
||||
tiles = [(x, y) for y in range(gm.height) for x in range(gm.width) if gm.walkable(x, y)]
|
||||
if not tiles:
|
||||
_log(session, "The teleport scroll finds nowhere to send you.")
|
||||
return
|
||||
session.player.x, session.player.y = random.choice(tiles)
|
||||
_log(session, "You blink across the floor.")
|
||||
_recompute_fov(session)
|
||||
|
||||
|
||||
def _equip(session: Any) -> None:
|
||||
p = session.player
|
||||
improved = False
|
||||
best_w = max((it for it in p.inventory if getattr(it, "category", "") == "weapon"),
|
||||
key=lambda it: it.stats.get("power", 0), default=None)
|
||||
cur_w = p.equipped_weapon.stats.get("power", 0) if p.equipped_weapon else -1
|
||||
if best_w is not None and best_w.stats.get("power", 0) > cur_w:
|
||||
p.inventory.remove(best_w)
|
||||
p.equip(best_w)
|
||||
_log(session, f"You equip the {best_w.name}.")
|
||||
improved = True
|
||||
best_a = max((it for it in p.inventory if getattr(it, "category", "") == "armor"),
|
||||
key=lambda it: it.stats.get("armor", 0), default=None)
|
||||
cur_a = p.equipped_armor.stats.get("armor", 0) if p.equipped_armor else -1
|
||||
if best_a is not None and best_a.stats.get("armor", 0) > cur_a:
|
||||
p.inventory.remove(best_a)
|
||||
p.equip(best_a)
|
||||
_log(session, f"You equip the {best_a.name}.")
|
||||
improved = True
|
||||
if not improved:
|
||||
_log(session, "Nothing in your pack is worthier than what you wear.")
|
||||
|
||||
|
||||
def _inventory_info(session: Any) -> None:
|
||||
inv = session.player.inventory
|
||||
if not inv:
|
||||
_log(session, "Your pack is empty.")
|
||||
return
|
||||
_log(session, "Pack: " + ", ".join(it.name for it in inv))
|
||||
|
||||
|
||||
def _save_path() -> str:
|
||||
return os.path.join(os.getcwd(), SAVE_FILE)
|
||||
|
||||
|
||||
def _save(session: Any) -> None:
|
||||
try:
|
||||
with open(_save_path(), "w", encoding="utf-8") as f:
|
||||
json.dump(session_to_dict(session), f)
|
||||
session.state = "saved"
|
||||
_log(session, "Game saved.")
|
||||
except OSError as ex:
|
||||
_log(session, f"Could not save the game: {ex}")
|
||||
|
||||
|
||||
def load_saved() -> Any:
|
||||
"""Rebuild a GameSession from ``save.json`` if present, else None."""
|
||||
from engine.serializers import session_from_dict
|
||||
path = _save_path()
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return session_from_dict(json.load(f))
|
||||
except (OSError, ValueError, KeyError):
|
||||
return None
|
||||
|
||||
|
||||
def delete_save() -> None:
|
||||
try:
|
||||
os.remove(_save_path())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Self-check: pickup + descent work on a fresh session.
|
||||
from engine.game_state import new_session
|
||||
s = new_session(seed=1)
|
||||
gm = s.dungeon[0]
|
||||
from data import items as I
|
||||
px, py = s.player.x, s.player.y
|
||||
gm.entities.append(I.make_item("healing_potion", px, py))
|
||||
n0 = len(s.player.inventory)
|
||||
apply_input(s, "g")
|
||||
assert len(s.player.inventory) == n0 + 1, "pickup failed"
|
||||
s.player.x, s.player.y = gm.stairs_down
|
||||
f0 = s.current_floor
|
||||
apply_input(s, "f")
|
||||
assert s.current_floor == f0 + 1, "descent failed"
|
||||
print("actions self-check: OK")
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Procedural sound effects via pygame.mixer.
|
||||
|
||||
A handful of short tones are synthesized in memory with stdlib ``array`` (no
|
||||
asset files). Audio is feedback only: it never mutates game state and never
|
||||
blocks input. If the mixer cannot initialize (no device, headless run) the
|
||||
engine degrades to silent no-ops and never raises.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
import pygame
|
||||
|
||||
_FREQ = 22050
|
||||
_SIZE = -16 # 16-bit signed
|
||||
_CHANNELS = 1
|
||||
_BUFFER = 256
|
||||
|
||||
# (base_freq_hz, duration_ms, volume, sweep_to_freq). sweep 0 => steady tone.
|
||||
_SFX: dict[str, tuple[int, int, float, int]] = {
|
||||
"hit": (330, 70, 0.35, 180),
|
||||
"crit": (660, 110, 0.45, 990),
|
||||
"miss": (200, 60, 0.20, 120),
|
||||
"damage": (140, 120, 0.40, 70),
|
||||
"pickup": (520, 70, 0.30, 780),
|
||||
"use": (700, 90, 0.30, 520),
|
||||
"stairs": (440, 140, 0.35, 880),
|
||||
"levelup": (523, 220, 0.40, 1046),
|
||||
"death": (300, 420, 0.45, 70),
|
||||
"victory": (523, 480, 0.45, 1568),
|
||||
"menu": (600, 50, 0.22, 600),
|
||||
}
|
||||
|
||||
|
||||
def _synth(freq: int, ms: int, volume: float, sweep: int) -> bytes:
|
||||
n = max(1, int(_FREQ * ms / 1000))
|
||||
buf = array.array("h")
|
||||
for i in range(n):
|
||||
t = i / _FREQ
|
||||
f = freq + (sweep - freq) * (i / n) if sweep else freq
|
||||
env = (1.0 - i / n) ** 1.2 # quick decay envelope
|
||||
val = int(volume * 32767 * env * math.sin(2 * math.pi * f * t))
|
||||
buf.append(max(-32768, min(32767, val)))
|
||||
return buf.tobytes()
|
||||
|
||||
|
||||
class AudioEngine:
|
||||
"""Tiny SFX player. Silent and raise-free when no audio device is present."""
|
||||
|
||||
def __init__(self, enabled: bool = True) -> None:
|
||||
self.muted: bool = False
|
||||
self.available: bool = False
|
||||
self._sounds: dict[str, Any] = {}
|
||||
if not enabled:
|
||||
return
|
||||
# Always attempt init ourselves so a forced failure (e.g. a monkeypatched
|
||||
# pygame.mixer.init that raises) is observed here, not masked by an
|
||||
# earlier pygame.init() that may have quietly succeeded.
|
||||
try:
|
||||
pygame.mixer.init(frequency=_FREQ, size=_SIZE, channels=_CHANNELS, buffer=_BUFFER)
|
||||
except Exception:
|
||||
self.available = False
|
||||
return
|
||||
try:
|
||||
for name, (f, ms, vol, sweep) in _SFX.items():
|
||||
self._sounds[name] = pygame.mixer.Sound(buffer=_synth(f, ms, vol, sweep))
|
||||
self.available = True
|
||||
except Exception:
|
||||
# Mixer init'd but Sound creation failed: stay silent, stay safe.
|
||||
self._sounds = {}
|
||||
self.available = False
|
||||
|
||||
def play(self, name: str) -> None:
|
||||
if not self.available or self.muted:
|
||||
return
|
||||
snd = self._sounds.get(name) or self._sounds.get("hit")
|
||||
if snd is None:
|
||||
return
|
||||
try:
|
||||
snd.play()
|
||||
except Exception:
|
||||
pass # audio is best-effort; never propagate a playback error
|
||||
|
||||
def toggle_mute(self) -> bool:
|
||||
self.muted = not self.muted
|
||||
return self.muted
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pygame.init()
|
||||
eng = AudioEngine(enabled=True)
|
||||
print("available:", eng.available, "muted:", eng.muted)
|
||||
eng.play("hit")
|
||||
eng.toggle_mute()
|
||||
print("toggled mute ->", eng.muted)
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Combat resolution: hit chance, armor reduction, critical hits."""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttackRoll:
|
||||
hit: bool
|
||||
crit: bool
|
||||
damage: int
|
||||
|
||||
|
||||
def roll_attack(attacker: Any, defender: Any, rng: random.Random = random) -> AttackRoll:
|
||||
hit_chance = 0.7 + (attacker.accuracy - defender.evasion) * 0.05
|
||||
hit_chance = max(0.1, min(0.95, hit_chance))
|
||||
base = attacker.power + getattr(attacker, "weapon_power", 0)
|
||||
# Player exposes effective armor via total_armor(); plain objects/enemies use .armor.
|
||||
total_armor = getattr(defender, "total_armor", None)
|
||||
armor = total_armor() if callable(total_armor) else getattr(defender, "armor", 0)
|
||||
reduced = max(0, base - armor)
|
||||
if rng.random() >= hit_chance:
|
||||
return AttackRoll(hit=False, crit=False, damage=0)
|
||||
crit = rng.random() < attacker.crit_chance
|
||||
return AttackRoll(hit=True, crit=crit, damage=reduced * (2 if crit else 1))
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Recursive shadowcasting field of view over 8 octants."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from data.constants import FLOOR, SIGHT_RADIUS
|
||||
|
||||
# (xx, xy, yx, yy) transforms covering the 8 octants around the origin.
|
||||
_OCTANTS: tuple[tuple[int, int, int, int], ...] = (
|
||||
( 1, 0, 0, 1),
|
||||
( 0, 1, 1, 0),
|
||||
( 0, -1, 1, 0),
|
||||
(-1, 0, 0, 1),
|
||||
(-1, 0, 0, -1),
|
||||
( 0, -1, -1, 0),
|
||||
( 0, 1, -1, 0),
|
||||
( 1, 0, 0, -1),
|
||||
)
|
||||
|
||||
|
||||
def compute_fov(
|
||||
game_map: Any, origin: tuple[int, int], radius: int = SIGHT_RADIUS
|
||||
) -> set[tuple[int, int]]:
|
||||
"""Set of tiles visible from ``origin`` within ``radius``.
|
||||
|
||||
Walls block sight but a wall touched by the beam is itself reported
|
||||
visible (so it renders as a seen wall when adjacent to lit floor).
|
||||
"""
|
||||
tiles = game_map.tiles
|
||||
cx, cy = origin
|
||||
r2 = radius * radius
|
||||
visible: set[tuple[int, int]] = {(cx, cy)}
|
||||
|
||||
def blocks(x: int, y: int) -> bool:
|
||||
if not game_map.in_bounds(x, y):
|
||||
return True
|
||||
return tiles[y][x] != FLOOR
|
||||
|
||||
def cast(row: int, start: float, end: float,
|
||||
xx: int, xy: int, yx: int, yy: int) -> None:
|
||||
if start < end:
|
||||
return
|
||||
for j in range(row, radius + 1):
|
||||
dx = -j - 1
|
||||
dy = -j
|
||||
blocked = False
|
||||
new_start = end
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
mx = cx + dx * xx + dy * xy
|
||||
my = cy + dx * yx + dy * yy
|
||||
l_slope = (dx - 0.5) / (dy + 0.5)
|
||||
r_slope = (dx + 0.5) / (dy - 0.5)
|
||||
if start < r_slope:
|
||||
continue
|
||||
if end > l_slope:
|
||||
break
|
||||
if dx * dx + dy * dy <= r2 and game_map.in_bounds(mx, my):
|
||||
visible.add((mx, my))
|
||||
if blocked:
|
||||
if blocks(mx, my):
|
||||
new_start = r_slope
|
||||
continue
|
||||
blocked = False
|
||||
start = new_start
|
||||
elif blocks(mx, my) and j < radius:
|
||||
blocked = True
|
||||
cast(j + 1, start, l_slope, xx, xy, yx, yy)
|
||||
new_start = r_slope
|
||||
# Row ended inside a wall run: deeper rows are fully occluded.
|
||||
if blocked:
|
||||
break
|
||||
|
||||
for xx, xy, yx, yy in _OCTANTS:
|
||||
cast(1, 1.0, 0.0, xx, xy, yx, yy)
|
||||
return visible
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import random
|
||||
|
||||
from engine.map_gen import generate_dungeon
|
||||
|
||||
gm = generate_dungeon(seed=1)[0]
|
||||
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
|
||||
seen = compute_fov(gm, (sx, sy))
|
||||
for y in range(gm.height):
|
||||
print("".join(
|
||||
"@" if (x, y) == (sx, sy) else
|
||||
"o" if (x, y) in seen else
|
||||
("." if gm.walkable(x, y) else "#")
|
||||
for x in range(gm.width)
|
||||
))
|
||||
print(f"visible={len(seen)} (random seed used only by map_gen)", random.random())
|
||||
@@ -0,0 +1,139 @@
|
||||
"""GameSession: the single source of truth for all mutable state.
|
||||
|
||||
``new_session`` generates all 10 floors AND populates them with enemies/items
|
||||
(keep generation in map_gen, content spawning here). Floor 9 always carries the
|
||||
Ancient Dragon so the boss is killable/victory-triggerable on a real playthrough.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from entities.player import Player
|
||||
from engine import map_gen
|
||||
from data import enemies as ENEMIES
|
||||
from data import items as ITEMS
|
||||
from data.constants import BOSS_ROOM_W, BOSS_ROOM_H, MAP_W, MAP_H
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Any = None
|
||||
dungeon: list = field(default_factory=list)
|
||||
current_floor: int = 0
|
||||
log: list = field(default_factory=list)
|
||||
turn: int = 0
|
||||
state: str = "playing"
|
||||
|
||||
|
||||
# Enemy roster gated by depth (plan.md Enemy Roster "Floors" column).
|
||||
_FLOOR_ENEMIES: dict[int, list[str]] = {
|
||||
0: ["rat", "goblin"],
|
||||
1: ["rat", "goblin"],
|
||||
2: ["rat", "goblin", "skeleton_archer"],
|
||||
3: ["rat", "goblin", "skeleton_archer", "orc_warrior"],
|
||||
4: ["goblin", "skeleton_archer", "orc_warrior", "green_slime"],
|
||||
5: ["goblin", "skeleton_archer", "orc_warrior", "wraith", "green_slime"],
|
||||
6: ["skeleton_archer", "orc_warrior", "wraith", "green_slime"],
|
||||
7: ["skeleton_archer", "orc_warrior", "wraith", "green_slime"],
|
||||
8: ["orc_warrior", "wraith", "green_slime", "skeleton_archer"],
|
||||
}
|
||||
|
||||
# (min_enemies, max_enemies, min_items, max_items) per depth band (plan.md table).
|
||||
_FLOOR_COUNTS: dict[int, tuple[int, int, int, int]] = {
|
||||
0: (3, 4, 2, 3), 1: (3, 4, 2, 3),
|
||||
2: (4, 6, 2, 3), 3: (4, 6, 2, 3),
|
||||
4: (5, 7, 3, 4), 5: (5, 7, 3, 4),
|
||||
6: (6, 8, 3, 4), 7: (6, 8, 3, 4),
|
||||
8: (7, 9, 4, 5),
|
||||
}
|
||||
|
||||
# Item pool split by depth (better weapons/armor appear deeper; consumables uniform).
|
||||
_DEEP_WEAPONS = ["battle_axe", "war_hammer"]
|
||||
_MID_WEAPONS = ["short_sword", "battle_axe"]
|
||||
_SHALLOW_WEAPONS = ["rusty_dagger", "short_sword"]
|
||||
_DEEP_ARMOR = ["chain_mail", "plate_armor"]
|
||||
_SHALLOW_ARMOR = ["leather_armor", "chain_mail"]
|
||||
_CONSUMABLES = ["healing_potion", "strength_potion", "invisibility_potion",
|
||||
"fireball_scroll", "teleport_scroll", "mapping_scroll"]
|
||||
|
||||
|
||||
def _walkable_tiles(gm: Any) -> list[tuple[int, int]]:
|
||||
return [(x, y) for y in range(gm.height) for x in range(gm.width)
|
||||
if gm.walkable(x, y)]
|
||||
|
||||
|
||||
def _populate_standard(gm: Any, rng: random.Random) -> None:
|
||||
pool = _FLOOR_ENEMIES.get(gm.floor_index, ["goblin"])
|
||||
lo_e, hi_e, lo_i, hi_i = _FLOOR_COUNTS.get(gm.floor_index, (3, 4, 2, 3))
|
||||
spawn = gm.spawn
|
||||
tiles = [t for t in _walkable_tiles(gm)
|
||||
if spawn is None or max(abs(t[0] - spawn[0]), abs(t[1] - spawn[1])) >= 4]
|
||||
rng.shuffle(tiles)
|
||||
|
||||
def take() -> tuple[int, int] | None:
|
||||
return tiles.pop() if tiles else None
|
||||
|
||||
for _ in range(rng.randint(lo_e, hi_e)):
|
||||
pos = take()
|
||||
if pos is None:
|
||||
break
|
||||
kind = rng.choice(pool)
|
||||
gm.entities.append(ENEMIES.make_enemy(kind, pos[0], pos[1]))
|
||||
|
||||
fi = gm.floor_index
|
||||
if fi <= 1:
|
||||
weapons, armors = _SHALLOW_WEAPONS, _SHALLOW_ARMOR
|
||||
elif fi <= 4:
|
||||
weapons, armors = _MID_WEAPONS, _SHALLOW_ARMOR
|
||||
else:
|
||||
weapons, armors = _DEEP_WEAPONS, _DEEP_ARMOR
|
||||
for _ in range(rng.randint(lo_i, hi_i)):
|
||||
pos = take()
|
||||
if pos is None:
|
||||
break
|
||||
roll = rng.random()
|
||||
if roll < 0.35:
|
||||
kind = rng.choice(weapons)
|
||||
elif roll < 0.55:
|
||||
kind = rng.choice(armors)
|
||||
else:
|
||||
kind = rng.choice(_CONSUMABLES)
|
||||
gm.entities.append(ITEMS.make_item(kind, pos[0], pos[1]))
|
||||
|
||||
|
||||
def _populate_boss(gm: Any) -> None:
|
||||
# Boss arena: dragon on the far side of the room, two potions near the entrance.
|
||||
rx = (MAP_W - BOSS_ROOM_W) // 2
|
||||
ry = (MAP_H - BOSS_ROOM_H) // 2
|
||||
mid_y = ry + BOSS_ROOM_H // 2
|
||||
dragon = ENEMIES.make_enemy("ancient_dragon", rx + BOSS_ROOM_W - 2, mid_y)
|
||||
gm.entities.append(dragon)
|
||||
gm.entities.append(ITEMS.make_item("healing_potion", rx + 2, mid_y))
|
||||
gm.entities.append(ITEMS.make_item("healing_potion", rx + 2, mid_y + 1))
|
||||
|
||||
|
||||
def populate_floor(gm: Any, rng: random.Random) -> None:
|
||||
"""Fill a generated floor's entity list with enemies + items (in place)."""
|
||||
if gm.floor_index == 9:
|
||||
_populate_boss(gm)
|
||||
else:
|
||||
_populate_standard(gm, rng)
|
||||
|
||||
|
||||
def new_session(seed: int = 0) -> GameSession:
|
||||
rng = random.Random(seed)
|
||||
dungeon = map_gen.generate_dungeon(seed=seed)
|
||||
for gm in dungeon:
|
||||
populate_floor(gm, rng)
|
||||
spawn = dungeon[0].spawn or (1, 1)
|
||||
player = Player(x=spawn[0], y=spawn[1])
|
||||
return GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=["You descend into the Underdepths."],
|
||||
turn=0,
|
||||
state="playing",
|
||||
)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""BSP dungeon generation.
|
||||
|
||||
Floors 0..8: a region recursively split into non-overlapping leaf regions,
|
||||
each gets a carved room, rooms are chained by L-corridors (guarantees a
|
||||
connected walkable graph), spawn in the first room, stairs in the room
|
||||
farthest from spawn. Reachability is flood-fill-verified with a fallback
|
||||
direct corridor.
|
||||
|
||||
Floor 9 (boss arena): a single large room, no descent.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data.constants import (
|
||||
MAP_W, MAP_H, FLOOR_COUNT, WALL, FLOOR,
|
||||
ROOM_MIN_W, ROOM_MIN_H, ROOM_MAX_W, ROOM_MAX_H,
|
||||
BSP_MIN_HALF, BSP_LEAVES_MIN, BSP_LEAVES_MAX,
|
||||
BOSS_ROOM_W, BOSS_ROOM_H,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[int, int]:
|
||||
return (self.x + self.w // 2, self.y + self.h // 2)
|
||||
|
||||
def intersects(self, other: "Rect") -> bool:
|
||||
return (self.x < other.x + other.w
|
||||
and self.x + self.w > other.x
|
||||
and self.y < other.y + other.h
|
||||
and self.y + self.h > other.y)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: list[list[int]]
|
||||
rooms: list[Rect]
|
||||
explored: list[list[bool]]
|
||||
visible: list[list[bool]]
|
||||
entities: list
|
||||
stairs_down: tuple[int, int] | None
|
||||
spawn: tuple[int, int] | None
|
||||
floor_index: int
|
||||
|
||||
def in_bounds(self, x: int, y: int) -> bool:
|
||||
return 0 <= x < self.width and 0 <= y < self.height
|
||||
|
||||
def walkable(self, x: int, y: int) -> bool:
|
||||
return self.in_bounds(x, y) and self.tiles[y][x] == FLOOR
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- carving
|
||||
def _carve_rect(tiles: list[list[int]], r: Rect) -> None:
|
||||
for y in range(r.y, r.y + r.h):
|
||||
for x in range(r.x, r.x + r.w):
|
||||
tiles[y][x] = FLOOR
|
||||
|
||||
|
||||
def _carve_h(tiles: list[list[int]], x1: int, x2: int, y: int) -> None:
|
||||
if x2 < x1:
|
||||
x1, x2 = x2, x1
|
||||
for x in range(x1, x2 + 1):
|
||||
tiles[y][x] = FLOOR
|
||||
|
||||
|
||||
def _carve_v(tiles: list[list[int]], y1: int, y2: int, x: int) -> None:
|
||||
if y2 < y1:
|
||||
y1, y2 = y2, y1
|
||||
for y in range(y1, y2 + 1):
|
||||
tiles[y][x] = FLOOR
|
||||
|
||||
|
||||
def _carve_corridor(tiles: list[list[int]], a: tuple[int, int],
|
||||
b: tuple[int, int], rng: random.Random) -> None:
|
||||
ax, ay = a
|
||||
bx, by = b
|
||||
if rng.random() < 0.5:
|
||||
_carve_h(tiles, ax, bx, ay)
|
||||
_carve_v(tiles, ay, by, bx)
|
||||
else:
|
||||
_carve_v(tiles, ay, by, ax)
|
||||
_carve_h(tiles, ax, bx, by)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- bsp tree
|
||||
def _bsp(root: Rect, rng: random.Random) -> list[Rect]:
|
||||
target = rng.randint(BSP_LEAVES_MIN, BSP_LEAVES_MAX)
|
||||
leaves: list[Rect] = []
|
||||
frontier: list[Rect] = [root]
|
||||
while frontier:
|
||||
node = frontier.pop()
|
||||
if len(leaves) + len(frontier) + 1 >= target:
|
||||
leaves.append(node)
|
||||
continue
|
||||
can_v = node.w >= 2 * BSP_MIN_HALF
|
||||
can_h = node.h >= 2 * BSP_MIN_HALF
|
||||
if not (can_v or can_h):
|
||||
leaves.append(node)
|
||||
continue
|
||||
vertical = can_v and (not can_h or rng.random() < node.w / (node.w + node.h))
|
||||
if vertical:
|
||||
s = rng.randint(BSP_MIN_HALF, node.w - BSP_MIN_HALF)
|
||||
frontier.append(Rect(node.x, node.y, s, node.h))
|
||||
frontier.append(Rect(node.x + s, node.y, node.w - s, node.h))
|
||||
else:
|
||||
s = rng.randint(BSP_MIN_HALF, node.h - BSP_MIN_HALF)
|
||||
frontier.append(Rect(node.x, node.y, node.w, s))
|
||||
frontier.append(Rect(node.x, node.y + s, node.w, node.h - s))
|
||||
return leaves
|
||||
|
||||
|
||||
def _room_in(leaf: Rect, tiles: list[list[int]], rng: random.Random) -> Rect:
|
||||
max_w = leaf.w - 2
|
||||
max_h = leaf.h - 2
|
||||
w = rng.randint(ROOM_MIN_W, min(ROOM_MAX_W, max_w))
|
||||
h = rng.randint(ROOM_MIN_H, min(ROOM_MAX_H, max_h))
|
||||
x = rng.randint(leaf.x + 1, leaf.x + 1 + max(0, max_w - w))
|
||||
y = rng.randint(leaf.y + 1, leaf.y + 1 + max(0, max_h - h))
|
||||
room = Rect(x, y, w, h)
|
||||
_carve_rect(tiles, room)
|
||||
return room
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reachability
|
||||
def _flood(tiles: list[list[int]], start: tuple[int, int],
|
||||
width: int, height: int) -> set[tuple[int, int]]:
|
||||
sx, sy = start
|
||||
seen = {(sx, sy)}
|
||||
dq = deque([(sx, sy)])
|
||||
while dq:
|
||||
x, y = dq.popleft()
|
||||
for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
||||
if (nx, ny) in seen:
|
||||
continue
|
||||
if 0 <= nx < width and 0 <= ny < height and tiles[ny][nx] == FLOOR:
|
||||
seen.add((nx, ny))
|
||||
dq.append((nx, ny))
|
||||
return seen
|
||||
|
||||
|
||||
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- builders
|
||||
def _boss_floor(floor_index: int) -> GameMap:
|
||||
width, height = MAP_W, MAP_H
|
||||
tiles = [[WALL] * width for _ in range(height)]
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
|
||||
rx = (width - rw) // 2
|
||||
ry = (height - rh) // 2
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
_carve_rect(tiles, room)
|
||||
spawn = (rx + 1, ry + rh // 2)
|
||||
return GameMap(width, height, tiles, [room], explored, visible,
|
||||
[], None, spawn, floor_index)
|
||||
|
||||
|
||||
def _standard_floor(floor_index: int, rng: random.Random) -> GameMap:
|
||||
width, height = MAP_W, MAP_H
|
||||
tiles = [[WALL] * width for _ in range(height)]
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
|
||||
leaves = _bsp(Rect(1, 1, width - 2, height - 2), rng)
|
||||
rooms = [_room_in(leaf, tiles, rng) for leaf in leaves]
|
||||
|
||||
# Chain-connect consecutive rooms -> connected spanning path of floor tiles.
|
||||
for i in range(len(rooms) - 1):
|
||||
_carve_corridor(tiles, rooms[i].center, rooms[i + 1].center, rng)
|
||||
|
||||
spawn = rooms[0].center
|
||||
far = max(rooms, key=lambda r: _dist2(r.center, spawn))
|
||||
stairs = far.center
|
||||
|
||||
# Reachability safety net (chain already guarantees it; re-carve if a
|
||||
# future tweak ever breaks connectivity).
|
||||
reach = _flood(tiles, spawn, width, height)
|
||||
if stairs not in reach:
|
||||
_carve_corridor(tiles, spawn, stairs, rng)
|
||||
|
||||
return GameMap(width, height, tiles, rooms, explored, visible,
|
||||
[], stairs, spawn, floor_index)
|
||||
|
||||
|
||||
def generate_floor(floor_index: int, rng: random.Random) -> GameMap:
|
||||
if floor_index == FLOOR_COUNT - 1:
|
||||
return _boss_floor(floor_index)
|
||||
return _standard_floor(floor_index, rng)
|
||||
|
||||
|
||||
def generate_dungeon(seed: int) -> list[GameMap]:
|
||||
rng = random.Random(seed)
|
||||
return [generate_floor(i, rng) for i in range(FLOOR_COUNT)]
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Grid A* pathfinding with Manhattan heuristic.
|
||||
|
||||
Returns shortest 4-connected paths over a game map's walkable tiles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
from typing import Any
|
||||
|
||||
# 4-connected movement on the tile grid.
|
||||
_DIRS: tuple[tuple[int, int], ...] = ((1, 0), (-1, 0), (0, 1), (0, -1))
|
||||
|
||||
|
||||
def find_path(
|
||||
game_map: Any,
|
||||
start: tuple[int, int],
|
||||
goal: tuple[int, int],
|
||||
blocked: frozenset[tuple[int, int]] = frozenset(),
|
||||
) -> list[tuple[int, int]] | None:
|
||||
"""Shortest 4-connected path from ``start`` to ``goal``.
|
||||
|
||||
The path excludes ``start`` and includes ``goal``. Returns ``[]`` when
|
||||
``start == goal`` and ``None`` when no route exists. Walls and every tile
|
||||
in ``blocked`` are impassable.
|
||||
"""
|
||||
if start == goal:
|
||||
return []
|
||||
if not game_map.walkable(*start) or not game_map.walkable(*goal) or goal in blocked:
|
||||
return None
|
||||
|
||||
gx, gy = goal
|
||||
|
||||
def h(x: int, y: int) -> int:
|
||||
return abs(x - gx) + abs(y - gy)
|
||||
|
||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
counter = 0
|
||||
open_heap: list[tuple[int, int, tuple[int, int]]] = [(h(*start), counter, start)]
|
||||
closed: set[tuple[int, int]] = set()
|
||||
|
||||
while open_heap:
|
||||
_, _, current = heapq.heappop(open_heap)
|
||||
if current in closed:
|
||||
continue
|
||||
if current == goal:
|
||||
path: list[tuple[int, int]] = []
|
||||
node = goal
|
||||
while node != start:
|
||||
path.append(node)
|
||||
node = came_from[node]
|
||||
path.reverse()
|
||||
return path
|
||||
closed.add(current)
|
||||
cx, cy = current
|
||||
base = g_score[current]
|
||||
for dx, dy in _DIRS:
|
||||
nxt = (cx + dx, cy + dy)
|
||||
if nxt in closed or nxt in blocked or not game_map.walkable(*nxt):
|
||||
continue
|
||||
tentative = base + 1
|
||||
if tentative < g_score.get(nxt, float("inf")):
|
||||
g_score[nxt] = tentative
|
||||
came_from[nxt] = current
|
||||
counter += 1
|
||||
heapq.heappush(open_heap, (tentative + h(*nxt), counter, nxt))
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from engine.map_gen import generate_dungeon
|
||||
|
||||
gm = generate_dungeon(seed=1)[0]
|
||||
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
|
||||
# identity
|
||||
assert find_path(gm, (sx, sy), (sx, sy)) == []
|
||||
# reach stairs
|
||||
if gm.stairs_down is not None:
|
||||
p = find_path(gm, (sx, sy), gm.stairs_down)
|
||||
assert p is not None and p[-1] == gm.stairs_down, (sx, sy, gm.stairs_down, p)
|
||||
assert (sx, sy) not in p
|
||||
assert all(gm.walkable(*t) for t in p)
|
||||
print(f"path spawn->stairs: {len(p)} steps, first {p[:3]}")
|
||||
# no path to a wall
|
||||
wx = next(x for x in range(gm.width) if not gm.walkable(x, 0))
|
||||
assert find_path(gm, (sx, sy), (wx, 0)) is None
|
||||
print("pathfinding self-check: OK")
|
||||
@@ -0,0 +1,124 @@
|
||||
"""JSON-safe serialization of GameSession for save/load.
|
||||
|
||||
The volatile `visible` grid is deliberately excluded from the saved form: it is
|
||||
recomputed from FOV on load, so persisting it would only bloat the save and risk
|
||||
a stale view. Everything else that survives across a save/quit/relaunch is kept.
|
||||
|
||||
Tuples are preserved as tuples (not flattened to lists) so a to_dict -> from_dict
|
||||
-> to_dict cycle is byte-stable under Python dict equality.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import fields
|
||||
from typing import Any
|
||||
|
||||
from entities.player import Player
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from engine.map_gen import GameMap, Rect
|
||||
from engine.game_state import GameSession
|
||||
|
||||
# Discriminators for the polymorphic entity list + room rects.
|
||||
_DCTAGS: dict[type, str] = {Player: "player", Enemy: "enemy", Item: "item", Rect: "rect"}
|
||||
|
||||
|
||||
def _to_json(v: Any) -> Any:
|
||||
"""Recursively coerce a value to a JSON-safe structure, preserving tuples."""
|
||||
if v is None or isinstance(v, (bool, int, float, str)):
|
||||
return v
|
||||
if isinstance(v, tuple):
|
||||
return tuple(_to_json(x) for x in v)
|
||||
if isinstance(v, list):
|
||||
return [_to_json(x) for x in v]
|
||||
if isinstance(v, dict):
|
||||
return {str(k): _to_json(val) for k, val in v.items()}
|
||||
tag = _DCTAGS.get(type(v))
|
||||
if tag is not None:
|
||||
out: dict[str, Any] = {"__type__": tag}
|
||||
for f in fields(v):
|
||||
out[f.name] = _to_json(getattr(v, f.name))
|
||||
return out
|
||||
raise TypeError(f"not JSON-serializable: {type(v).__name__}")
|
||||
|
||||
|
||||
def _make_dc(cls: type, d: dict) -> Any:
|
||||
kwargs = {f.name: _from_json(d[f.name]) for f in fields(cls) if f.name in d}
|
||||
return cls(**kwargs)
|
||||
|
||||
|
||||
def _from_json(v: Any) -> Any:
|
||||
"""Inverse of _to_json: rebuild dataclass instances from tagged dicts."""
|
||||
if v is None or isinstance(v, (bool, int, float, str)):
|
||||
return v
|
||||
if isinstance(v, tuple):
|
||||
return tuple(_from_json(x) for x in v)
|
||||
if isinstance(v, list):
|
||||
return [_from_json(x) for x in v]
|
||||
if isinstance(v, dict):
|
||||
tag = v.get("__type__")
|
||||
if tag == "player":
|
||||
return _make_dc(Player, v)
|
||||
if tag == "enemy":
|
||||
return _make_dc(Enemy, v)
|
||||
if tag == "item":
|
||||
return _make_dc(Item, v)
|
||||
if tag == "rect":
|
||||
return Rect(v["x"], v["y"], v["w"], v["h"])
|
||||
return {k: _from_json(val) for k, val in v.items()}
|
||||
raise TypeError(f"cannot decode: {type(v).__name__}")
|
||||
|
||||
|
||||
def _floor_to_dict(gm: GameMap) -> dict:
|
||||
# `visible` is intentionally absent: recomputed from FOV on load.
|
||||
return {
|
||||
"width": gm.width,
|
||||
"height": gm.height,
|
||||
"tiles": gm.tiles,
|
||||
"rooms": [_to_json(r) for r in gm.rooms],
|
||||
"explored": gm.explored,
|
||||
"entities": [_to_json(e) for e in gm.entities],
|
||||
"stairs_down": gm.stairs_down,
|
||||
"spawn": gm.spawn,
|
||||
"floor_index": gm.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _floor_from_dict(d: dict) -> GameMap:
|
||||
width, height = d["width"], d["height"]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
stairs = d["stairs_down"]
|
||||
spawn = d["spawn"]
|
||||
return GameMap(
|
||||
width=width,
|
||||
height=height,
|
||||
tiles=d["tiles"],
|
||||
rooms=[_from_json(r) for r in d["rooms"]],
|
||||
explored=d["explored"],
|
||||
visible=visible,
|
||||
entities=[_from_json(e) for e in d["entities"]],
|
||||
stairs_down=tuple(stairs) if stairs is not None else None,
|
||||
spawn=tuple(spawn) if spawn is not None else None,
|
||||
floor_index=d["floor_index"],
|
||||
)
|
||||
|
||||
|
||||
def session_to_dict(session: GameSession) -> dict:
|
||||
return {
|
||||
"player": _to_json(session.player),
|
||||
"dungeon": [_floor_to_dict(gm) for gm in session.dungeon],
|
||||
"current_floor": session.current_floor,
|
||||
"turn": session.turn,
|
||||
"log": list(session.log),
|
||||
"state": session.state,
|
||||
}
|
||||
|
||||
|
||||
def session_from_dict(d: dict) -> GameSession:
|
||||
return GameSession(
|
||||
player=_from_json(d["player"]),
|
||||
dungeon=[_floor_from_dict(fd) for fd in d["dungeon"]],
|
||||
current_floor=d["current_floor"],
|
||||
turn=d["turn"],
|
||||
log=list(d["log"]),
|
||||
state=d["state"],
|
||||
)
|
||||
Reference in new issue
Block a user