(Underdepth) Prepare for Pass 5
This commit is contained in:
1 parent
6147ab3121
commit
05e340dec2
29 files changed
-4888
No files matched your search
Whitespace-only changes.
@@ -1,256 +0,0 @@
|
||||
"""Gameplay actions: pure functions that mutate a GameSession (plan.md §6, §9).
|
||||
|
||||
`try_move` is the turn driver — a successful move or attack advances the turn,
|
||||
runs enemy AI, recomputes FOV, ticks effect timers, and checks for death.
|
||||
`pickup` / `descend` / `use_item` / `equip` are resolution actions; they log and
|
||||
mutate but leave turn advancement to the caller so item use stays deterministic
|
||||
(a potion must not let an enemy sneak in a hit between quaff and the HP check).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from data import constants as C
|
||||
from ai.behaviors import on_death, take_enemy_turn
|
||||
from engine.combat import attack
|
||||
from engine import game_state
|
||||
from engine.game_state import recompute_fov
|
||||
from engine.map_gen import is_walkable
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Effect
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Movement / melee
|
||||
# --------------------------------------------------------------------------- #
|
||||
def try_move(session, dx: int, dy: int) -> bool:
|
||||
"""Move the player by (dx, dy) or melee an enemy there. Returns whether the
|
||||
player acted (and thus a turn elapsed)."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
nx, ny = player.x + dx, player.y + dy
|
||||
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
return False
|
||||
if dx or dy:
|
||||
player.facing = _facing(dx, dy)
|
||||
|
||||
target = _enemy_at(floor, nx, ny)
|
||||
if target is not None:
|
||||
res = attack(player, target, rng=session.rng, log=session.log)
|
||||
if res["killed"]:
|
||||
on_death(target, session)
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
if floor.tiles[ny][nx] == 1 and not _blocked_at(floor, nx, ny):
|
||||
player.x, player.y = nx, ny
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _end_turn(session) -> None:
|
||||
"""One turn elapsed: counter up, FOV, enemy turns, effect timers, death."""
|
||||
session.turn += 1
|
||||
recompute_fov(session)
|
||||
_enemy_turns(session)
|
||||
_tick_effects(session)
|
||||
if session.player.hp <= 0 and session.state == "playing":
|
||||
game_state.mark_dead(session)
|
||||
session.log.append("You have died.")
|
||||
|
||||
|
||||
def _enemy_turns(session) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Enemy) and e.hp > 0:
|
||||
take_enemy_turn(e, session, rng=session.rng)
|
||||
if session.player.hp <= 0:
|
||||
return
|
||||
|
||||
|
||||
def _tick_effects(session) -> None:
|
||||
player = session.player
|
||||
if not player.effects:
|
||||
return
|
||||
remaining: list = []
|
||||
for eff in player.effects:
|
||||
eff.duration -= 1
|
||||
if eff.duration > 0:
|
||||
remaining.append(eff)
|
||||
elif eff.kind == "invisibility":
|
||||
player.invisible = False
|
||||
session.log.append("You fade back into view.")
|
||||
player.effects = remaining
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Pickup / descend
|
||||
# --------------------------------------------------------------------------- #
|
||||
def pickup(session) -> bool:
|
||||
"""Move the item under the player into inventory. False if nothing there."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Item) and e.x == player.x and e.y == player.y:
|
||||
floor.entities.remove(e)
|
||||
player.inventory.append(e)
|
||||
session.log.append(f"You pick up the {e.name}.")
|
||||
return True
|
||||
session.log.append("There is nothing here to pick up.")
|
||||
return False
|
||||
|
||||
|
||||
def descend(session) -> bool:
|
||||
"""Descend the stairs the player stands on. False if not on stairs / last floor."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
if (player.x, player.y) != floor.stairs_down:
|
||||
session.log.append("There are no stairs here.")
|
||||
return False
|
||||
if session.current_floor >= C.FLOORS - 1:
|
||||
return False # no descent past the boss floor
|
||||
|
||||
session.current_floor += 1
|
||||
new_floor = session.dungeon[session.current_floor]
|
||||
spawn = new_floor.rooms[0].center if new_floor.rooms else _first_walkable(new_floor)
|
||||
if not is_walkable(new_floor, *spawn):
|
||||
spawn = _first_walkable(new_floor)
|
||||
player.x, player.y = spawn
|
||||
recompute_fov(session)
|
||||
session.log.append(f"You descend to floor {session.current_floor + 1}.")
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Use / equip
|
||||
# --------------------------------------------------------------------------- #
|
||||
def use_item(session, item) -> None:
|
||||
"""Apply a potion/scroll, or equip a weapon/armor. Consumes consumables."""
|
||||
if item.item_type == "potion":
|
||||
_use_potion(session, item)
|
||||
_consume(session, item)
|
||||
elif item.item_type == "scroll":
|
||||
_use_scroll(session, item)
|
||||
_consume(session, item)
|
||||
elif item.item_type in ("weapon", "armor"):
|
||||
equip(session, item)
|
||||
else:
|
||||
session.log.append(f"You can't use the {item.name}.")
|
||||
|
||||
|
||||
def equip(session, item) -> None:
|
||||
"""Place an equippable in its slot; the previous item returns to inventory."""
|
||||
player = session.player
|
||||
if item.item_type not in ("weapon", "armor"):
|
||||
session.log.append(f"You can't equip the {item.name}.")
|
||||
return
|
||||
slot = item.item_type
|
||||
old = player.equipped.get(slot)
|
||||
player.equipped[slot] = item
|
||||
if item in player.inventory:
|
||||
player.inventory.remove(item)
|
||||
if old is not None:
|
||||
player.inventory.append(old)
|
||||
session.log.append(f"You unequip the {old.name}.")
|
||||
session.log.append(f"You equip the {item.name}.")
|
||||
|
||||
|
||||
def _use_potion(session, item) -> None:
|
||||
player = session.player
|
||||
if item.subtype == "healing":
|
||||
amount = item.stats.get("heal", 30)
|
||||
player.hp = min(player.max_hp, player.hp + amount)
|
||||
session.log.append(f"You quaff a Healing Potion and recover {amount} HP.")
|
||||
elif item.subtype == "strength":
|
||||
player.effects.append(Effect(
|
||||
kind="strength",
|
||||
power=item.stats.get("power", 5),
|
||||
duration=item.stats.get("duration", 20),
|
||||
))
|
||||
session.log.append("Your muscles surge! (+5 power for 20 turns)")
|
||||
elif item.subtype == "invisibility":
|
||||
player.effects.append(Effect(
|
||||
kind="invisibility",
|
||||
duration=item.stats.get("duration", 15),
|
||||
))
|
||||
player.invisible = True
|
||||
session.log.append("You fade from sight!")
|
||||
|
||||
|
||||
def _use_scroll(session, item) -> None:
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
if item.subtype == "fireball":
|
||||
radius = item.stats.get("radius", 3)
|
||||
dmg = item.stats.get("damage", 20)
|
||||
hit = [e for e in floor.entities
|
||||
if isinstance(e, Enemy)
|
||||
and max(abs(e.x - player.x), abs(e.y - player.y)) <= radius]
|
||||
for e in hit:
|
||||
e.hp -= dmg
|
||||
session.log.append(f"The fireball erupts! {len(hit)} foe(s) burn for {dmg} damage.")
|
||||
for e in hit:
|
||||
if e.hp <= 0:
|
||||
on_death(e, session)
|
||||
elif item.subtype == "teleport":
|
||||
targets = [
|
||||
(x, y) for y in range(floor.height) for x in range(floor.width)
|
||||
if floor.tiles[y][x] == 1
|
||||
and (x, y) != (player.x, player.y)
|
||||
and not _blocked_at(floor, x, y)
|
||||
]
|
||||
if targets:
|
||||
player.x, player.y = session.rng.choice(targets)
|
||||
recompute_fov(session)
|
||||
session.log.append("The world blurs — you teleport across the floor!")
|
||||
elif item.subtype == "mapping":
|
||||
for y in range(floor.height):
|
||||
for x in range(floor.width):
|
||||
if floor.tiles[y][x] == 1:
|
||||
floor.explored[y][x] = True
|
||||
session.log.append("A complete map of this floor floods your mind!")
|
||||
|
||||
|
||||
def _consume(session, item) -> None:
|
||||
if item in session.player.inventory:
|
||||
session.player.inventory.remove(item)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _enemy_at(floor, x: int, y: int):
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def _blocked_at(floor, x: int, y: int) -> bool:
|
||||
"""True if a blocking entity (enemy) occupies (x, y). Items never block."""
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _first_walkable(game_map) -> tuple[int, int]:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return (1, 1)
|
||||
|
||||
|
||||
def _facing(dx: int, dy: int) -> str:
|
||||
if dy < 0:
|
||||
return "up"
|
||||
if dy > 0:
|
||||
return "down"
|
||||
if dx < 0:
|
||||
return "left"
|
||||
if dx > 0:
|
||||
return "right"
|
||||
return "down"
|
||||
@@ -1,108 +0,0 @@
|
||||
"""Resilient generated-audio manager (plan.md Audio).
|
||||
|
||||
Every sound is synthesized in memory from a stdlib `array` of PCM samples — no
|
||||
asset files. The mixer is initialized once, lazily and defensively: if the audio
|
||||
driver is missing, `mixer.init` fails, or `Sound` creation throws, audio is
|
||||
disabled and the game keeps running silently. No public method ever raises.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
import random
|
||||
|
||||
try:
|
||||
import pygame
|
||||
_HAS_PYGAME = True
|
||||
except Exception: # pragma: no cover - pygame is a hard dep, but stay safe
|
||||
pygame = None
|
||||
_HAS_PYGAME = False
|
||||
|
||||
|
||||
# name -> synthesis spec: freq (Hz), dur (s), decay (envelope rate),
|
||||
# kind (sine | square | noise | sweep), optional freq2 (sweep target).
|
||||
_SPECS: dict[str, dict] = {
|
||||
"hit": dict(freq=330, dur=0.07, decay=9.0, kind="square"),
|
||||
"miss": dict(freq=180, dur=0.06, decay=10.0, kind="sine"),
|
||||
"damage": dict(freq=120, dur=0.18, decay=5.0, kind="noise"),
|
||||
"pickup": dict(freq=660, dur=0.10, decay=8.0, kind="sweep", freq2=990),
|
||||
"use": dict(freq=520, dur=0.12, decay=7.0, kind="sweep", freq2=780),
|
||||
"stairs": dict(freq=400, dur=0.16, decay=5.0, kind="sweep", freq2=600),
|
||||
"levelup": dict(freq=523, dur=0.30, decay=3.0, kind="sweep", freq2=1046),
|
||||
"death": dict(freq=200, dur=0.45, decay=2.5, kind="sweep", freq2=80),
|
||||
"victory": dict(freq=523, dur=0.50, decay=2.0, kind="sweep", freq2=1568),
|
||||
}
|
||||
|
||||
|
||||
class AudioManager:
|
||||
"""Generates and plays short SFX; degrades to silence on any audio fault."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.muted: bool = False
|
||||
self._ok: bool = False
|
||||
self._sounds: dict = {}
|
||||
self._init()
|
||||
|
||||
def play(self, name: str) -> None:
|
||||
try:
|
||||
if self.muted or not self._ok:
|
||||
return
|
||||
snd = self._sounds.get(name)
|
||||
if snd is not None:
|
||||
snd.play()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def toggle_mute(self) -> None:
|
||||
self.muted = not self.muted
|
||||
|
||||
# -- internal ------------------------------------------------------------- #
|
||||
def _init(self) -> None:
|
||||
if not _HAS_PYGAME:
|
||||
return
|
||||
try:
|
||||
if not pygame.mixer.get_init():
|
||||
pygame.mixer.init()
|
||||
except Exception:
|
||||
self._ok = False
|
||||
return
|
||||
self._ok = True
|
||||
for name, spec in _SPECS.items():
|
||||
try:
|
||||
self._sounds[name] = self._make_sound(spec)
|
||||
except Exception:
|
||||
pass # that one effect just won't play; others may still work
|
||||
|
||||
def _make_sound(self, spec: dict):
|
||||
info = pygame.mixer.get_init()
|
||||
if info is None:
|
||||
raise RuntimeError("mixer not initialized")
|
||||
rate, size, channels = info
|
||||
code = "h" if abs(size) == 16 else "b"
|
||||
maxv = (1 << (abs(size) - 1)) - 1
|
||||
n = max(1, int(rate * spec["dur"]))
|
||||
freq = spec["freq"]
|
||||
freq2 = spec.get("freq2")
|
||||
decay = spec["decay"]
|
||||
kind = spec["kind"]
|
||||
vol = 0.45
|
||||
rng = random.Random(0x5EED)
|
||||
buf = array.array(code)
|
||||
for i in range(n):
|
||||
t = i / rate
|
||||
frac = i / n
|
||||
f = freq + (freq2 - freq) * frac if (kind == "sweep" and freq2) else freq
|
||||
if kind == "noise":
|
||||
wave = rng.uniform(-1.0, 1.0)
|
||||
elif kind == "square":
|
||||
wave = 1.0 if math.sin(2 * math.pi * f * t) >= 0 else -1.0
|
||||
else:
|
||||
wave = math.sin(2 * math.pi * f * t)
|
||||
env = math.exp(-decay * t)
|
||||
s = int(maxv * env * wave * vol)
|
||||
if s > maxv:
|
||||
s = maxv
|
||||
elif s < -maxv:
|
||||
s = -maxv
|
||||
buf.extend([s] * channels)
|
||||
return pygame.mixer.Sound(buffer=buf.tobytes())
|
||||
@@ -1,60 +0,0 @@
|
||||
"""Turn-based combat resolution (plan.md §4).
|
||||
|
||||
`attack` works for any attacker/defender pair: a Player uses total_power /
|
||||
total_armor (gear + effects), an Enemy uses its raw stats. The caller owns
|
||||
death consequences (XP, removal, state changes); attack only resolves the swing
|
||||
and logs the immediate feedback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def attack(attacker, defender, rng=None, log=None) -> dict:
|
||||
r = rng if rng is not None else random.Random()
|
||||
|
||||
acc = getattr(attacker, "accuracy", 0)
|
||||
eva = getattr(defender, "evasion", 0)
|
||||
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05))
|
||||
|
||||
attacker_is_player = hasattr(attacker, "total_power")
|
||||
defender_is_player = hasattr(defender, "total_armor")
|
||||
base = attacker.total_power() if attacker_is_player else attacker.power
|
||||
crit_chance = getattr(attacker, "crit_chance", 0.0)
|
||||
|
||||
hit = r.random() < hit_chance
|
||||
crit = False
|
||||
damage = 0
|
||||
if hit:
|
||||
arm = defender.total_armor() if defender_is_player else defender.armor
|
||||
reduced = max(0, base - arm)
|
||||
crit = r.random() < crit_chance
|
||||
damage = reduced * (2 if crit else 1)
|
||||
defender.hp -= damage
|
||||
|
||||
killed = defender.hp <= 0
|
||||
|
||||
if log is not None:
|
||||
_log_swing(log, attacker, defender, hit, crit, damage, attacker_is_player)
|
||||
|
||||
return {"hit": hit, "damage": damage, "crit": crit, "killed": killed}
|
||||
|
||||
|
||||
def _log_swing(log: list, attacker, defender, hit: bool, crit: bool,
|
||||
damage: int, attacker_is_player: bool) -> None:
|
||||
if not hit:
|
||||
if attacker_is_player:
|
||||
log.append(f"You miss the {defender.name}")
|
||||
else:
|
||||
log.append(f"{attacker.name} misses you")
|
||||
return
|
||||
if attacker_is_player:
|
||||
if crit:
|
||||
log.append(f"Critical hit! You hit the {defender.name} for {damage} damage!")
|
||||
else:
|
||||
log.append(f"You hit the {defender.name} for {damage} damage!")
|
||||
else:
|
||||
if crit:
|
||||
log.append(f"{attacker.name} critically strikes you for {damage} damage!")
|
||||
else:
|
||||
log.append(f"{attacker.name} hits you for {damage} damage!")
|
||||
@@ -1,87 +0,0 @@
|
||||
"""Recursive shadowcasting field of view over 8 octants (plan.md §2).
|
||||
|
||||
Written from scratch. Walls block sight, but a wall reached by a light ray is
|
||||
itself visible (you see the wall face). `compute_fov` mutates `game_map.visible`
|
||||
to match the set it returns.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Per-octant transforms: (xx, xy, yx, yy) map scan offsets (dx, dy) to map space.
|
||||
_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, ox: int, oy: int, radius: int = 8) -> set[tuple[int, int]]:
|
||||
"""Return the set of visible tiles from (ox, oy); also set game_map.visible."""
|
||||
width, height = game_map.width, game_map.height
|
||||
tiles = game_map.tiles
|
||||
|
||||
# Fresh visible grid every call so stale tiles never linger.
|
||||
for y in range(height):
|
||||
vrow = game_map.visible[y]
|
||||
for x in range(width):
|
||||
vrow[x] = False
|
||||
|
||||
visible: set[tuple[int, int]] = set()
|
||||
|
||||
def blocks(x: int, y: int) -> bool:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
return tiles[y][x] == 0
|
||||
return True # out of bounds behaves as wall
|
||||
|
||||
def light(x: int, y: int) -> None:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
visible.add((x, y))
|
||||
|
||||
if not (0 <= ox < width and 0 <= oy < height):
|
||||
return visible
|
||||
|
||||
light(ox, oy) # origin is always seen
|
||||
r2 = radius * radius
|
||||
|
||||
def cast(row: int, start: float, end: float,
|
||||
xx: int, xy: int, yx: int, yy: int) -> None:
|
||||
if start < end:
|
||||
return
|
||||
new_start = start
|
||||
for j in range(row, radius + 1):
|
||||
dy = -j
|
||||
dx = -j - 1
|
||||
blocked = False
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
mx = ox + dx * xx + dy * xy
|
||||
my = oy + 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
|
||||
elif end > l_slope:
|
||||
break
|
||||
else:
|
||||
if dx * dx + dy * dy <= r2:
|
||||
light(mx, my)
|
||||
if blocked:
|
||||
if blocks(mx, my):
|
||||
new_start = r_slope
|
||||
continue
|
||||
else:
|
||||
blocked = False
|
||||
start = new_start
|
||||
else:
|
||||
if blocks(mx, my) and j < radius:
|
||||
blocked = True
|
||||
cast(j + 1, start, l_slope, xx, xy, yx, yy)
|
||||
new_start = r_slope
|
||||
if blocked:
|
||||
break
|
||||
|
||||
for (xx, xy, yx, yy) in _OCTANTS:
|
||||
cast(1, 1.0, 0.0, xx, xy, yx, yy)
|
||||
|
||||
for (x, y) in visible:
|
||||
game_map.visible[y][x] = True
|
||||
|
||||
return visible
|
||||
@@ -1,130 +0,0 @@
|
||||
"""GameSession: the single source of truth for all mutable game state.
|
||||
|
||||
It holds the player, all 10 floors, the message log, turn counter, and game
|
||||
state string. `new_game` builds a fresh dive; `recompute_fov` refreshes the
|
||||
player's sight and merges it into the explored memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from data import constants as C
|
||||
from engine import map_gen
|
||||
from engine.fov import compute_fov
|
||||
from entities.player import Player
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Player
|
||||
dungeon: list
|
||||
current_floor: int = 0
|
||||
log: list = field(default_factory=list)
|
||||
turn: int = 0
|
||||
state: str = "playing"
|
||||
rng: random.Random = field(default_factory=random.Random)
|
||||
|
||||
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
rng = random.Random(seed)
|
||||
# generate_dungeon draws from the global random module; seed it too so the
|
||||
# entire dive is deterministic from `seed`.
|
||||
random.seed(seed)
|
||||
|
||||
player = Player(0, 0)
|
||||
|
||||
dungeon = []
|
||||
for fi in range(C.FLOORS):
|
||||
floor = map_gen.generate_dungeon(fi)
|
||||
map_gen.populate(floor, fi, rng=rng)
|
||||
dungeon.append(floor)
|
||||
|
||||
# Player starts at the center of the first room on floor 0.
|
||||
spawn = dungeon[0].rooms[0].center
|
||||
if not map_gen.is_walkable(dungeon[0], *spawn):
|
||||
spawn = _first_walkable(dungeon[0])
|
||||
player.x, player.y = spawn
|
||||
|
||||
session = GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=["You enter the Underdepths. Find the stairs and descend."],
|
||||
turn=0,
|
||||
state="playing",
|
||||
rng=rng,
|
||||
)
|
||||
recompute_fov(session)
|
||||
return session
|
||||
|
||||
|
||||
def recompute_fov(session: GameSession) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
visible = compute_fov(floor, session.player.x, session.player.y, C.SIGHT_RADIUS)
|
||||
for (x, y) in visible:
|
||||
floor.explored[y][x] = True
|
||||
|
||||
|
||||
def _first_walkable(game_map) -> tuple[int, int]:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return (1, 1)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Persistence + permadeath
|
||||
# --------------------------------------------------------------------------- #
|
||||
_GAME_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def _save_path(path: str) -> str:
|
||||
"""Resolve a save path relative to the game directory unless it is absolute."""
|
||||
return path if os.path.isabs(path) else os.path.join(_GAME_DIR, path)
|
||||
|
||||
|
||||
def save(session: GameSession, path: str = "save.json") -> str:
|
||||
"""Serialize the session to JSON in the game directory. Returns the file path."""
|
||||
from engine.serializers import session_to_dict
|
||||
full = _save_path(path)
|
||||
with open(full, "w", encoding="utf-8") as f:
|
||||
json.dump(session_to_dict(session), f)
|
||||
return full
|
||||
|
||||
|
||||
def load(path: str = "save.json") -> GameSession:
|
||||
"""Read a saved session JSON and rebuild a live GameSession (FOV recomputed)."""
|
||||
from engine.serializers import dict_to_session
|
||||
with open(_save_path(path), "r", encoding="utf-8") as f:
|
||||
return dict_to_session(json.load(f))
|
||||
|
||||
|
||||
def has_save(path: str = "save.json") -> bool:
|
||||
"""True when a save file exists (drives the menu's 'Continue' entry)."""
|
||||
return os.path.isfile(_save_path(path))
|
||||
|
||||
|
||||
def delete_save(path: str = "save.json") -> None:
|
||||
"""Remove the save file if present. Never raises."""
|
||||
full = _save_path(path)
|
||||
try:
|
||||
if os.path.isfile(full):
|
||||
os.remove(full)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def mark_dead(session: GameSession) -> None:
|
||||
"""End the run on player death: flag the state and delete the save (permadeath)."""
|
||||
session.state = "dead"
|
||||
delete_save()
|
||||
|
||||
|
||||
def mark_victory(session: GameSession) -> None:
|
||||
"""End the run on victory: flag the state and delete the save."""
|
||||
session.state = "victory"
|
||||
delete_save()
|
||||
@@ -1,309 +0,0 @@
|
||||
"""BSP dungeon generation, the GameMap/Rect model, and per-floor population."""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data import constants as C
|
||||
from entities.enemy import make_enemy, kinds_for_floor
|
||||
from entities.item import make_item, item_pool_for_floor
|
||||
|
||||
# BSP / room sizing. Rooms are 4x4..10x8 (plan.md §1); leaves must hold one.
|
||||
MIN_LEAF: int = 8
|
||||
MIN_ROOM_W: int = 4
|
||||
MIN_ROOM_H: int = 4
|
||||
MAX_ROOM_W: int = 10
|
||||
MAX_ROOM_H: int = 8
|
||||
BOSS_ROOM_W: int = 20
|
||||
BOSS_ROOM_H: int = 15
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
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)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: list[list[int]] # 0 = wall, 1 = floor
|
||||
rooms: list[Rect]
|
||||
explored: list[list[bool]]
|
||||
visible: list[list[bool]]
|
||||
entities: list # enemies + items present on this floor
|
||||
stairs_down: tuple[int, int]
|
||||
floor_index: int
|
||||
|
||||
|
||||
def is_walkable(game_map: GameMap, x: int, y: int) -> bool:
|
||||
"""True if (x, y) is in bounds and a floor tile."""
|
||||
if not (0 <= x < game_map.width and 0 <= y < game_map.height):
|
||||
return False
|
||||
return game_map.tiles[y][x] == 1
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Generation
|
||||
# --------------------------------------------------------------------------- #
|
||||
def generate_dungeon(floor_index: int, width: int = C.MAP_WIDTH,
|
||||
height: int = C.MAP_HEIGHT) -> GameMap:
|
||||
"""Generate one floor via BSP (floors 0-8) or a boss arena (floor 9).
|
||||
|
||||
Uses the global `random` state so new_game(seed) can seed the whole dive.
|
||||
"""
|
||||
tiles: list[list[int]] = [[0] * width for _ in range(height)]
|
||||
if floor_index == C.FLOORS - 1:
|
||||
return _boss_arena(floor_index, width, height, tiles)
|
||||
|
||||
# Working area sits inside the 1-tile wall border.
|
||||
root = {"x": 1, "y": 1, "w": width - 2, "h": height - 2}
|
||||
_build_bsp(root, random.randint(5, 8))
|
||||
|
||||
leaves: list[dict] = []
|
||||
_collect_leaves(root, leaves)
|
||||
rooms: list[Rect] = []
|
||||
for leaf in leaves:
|
||||
leaf["room"] = _carve_room(leaf, tiles, width, height)
|
||||
rooms.append(leaf["room"])
|
||||
_connect(root, tiles, width, height)
|
||||
|
||||
# Stairs go in the room farthest from the spawn room.
|
||||
spawn = rooms[0].center
|
||||
stairs_room = max(rooms, key=lambda r: _dist2(r.center, spawn))
|
||||
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
return GameMap(width, height, tiles, rooms, explored, visible, [],
|
||||
stairs_room.center, floor_index)
|
||||
|
||||
|
||||
def _build_bsp(root: dict, target_splits: int) -> None:
|
||||
"""Split the largest splittable leaf until target_splits splits are done."""
|
||||
splittable = [root]
|
||||
done = 0
|
||||
prefer_horiz = True
|
||||
while done < target_splits and splittable:
|
||||
splittable.sort(key=lambda n: n["w"] * n["h"], reverse=True)
|
||||
node = splittable.pop(0)
|
||||
halves = _split_node(node, prefer_horiz)
|
||||
prefer_horiz = not prefer_horiz
|
||||
if halves is None:
|
||||
continue # this leaf can't be split; it stays a leaf
|
||||
left, right = halves
|
||||
node["left"] = left
|
||||
node["right"] = right
|
||||
splittable.append(left)
|
||||
splittable.append(right)
|
||||
done += 1
|
||||
|
||||
|
||||
def _split_node(node: dict, prefer_horiz: bool) -> tuple[dict, dict] | None:
|
||||
"""Split a region on the preferred axis, falling back to the other.
|
||||
|
||||
Returns the two child regions, or None if neither axis can be split.
|
||||
"""
|
||||
use_horiz = prefer_horiz
|
||||
if use_horiz and node["w"] < 2 * MIN_LEAF:
|
||||
use_horiz = False
|
||||
if not use_horiz and node["h"] < 2 * MIN_LEAF:
|
||||
use_horiz = True
|
||||
length = node["w"] if use_horiz else node["h"]
|
||||
if length < 2 * MIN_LEAF:
|
||||
return None
|
||||
p = random.randint(MIN_LEAF, length - MIN_LEAF)
|
||||
if use_horiz:
|
||||
left = {"x": node["x"], "y": node["y"], "w": p, "h": node["h"]}
|
||||
right = {"x": node["x"] + p, "y": node["y"], "w": node["w"] - p, "h": node["h"]}
|
||||
else:
|
||||
left = {"x": node["x"], "y": node["y"], "w": node["w"], "h": p}
|
||||
right = {"x": node["x"], "y": node["y"] + p, "w": node["w"], "h": node["h"] - p}
|
||||
return left, right
|
||||
|
||||
|
||||
def _collect_leaves(node: dict, out: list[dict]) -> None:
|
||||
if "left" in node:
|
||||
_collect_leaves(node["left"], out)
|
||||
_collect_leaves(node["right"], out)
|
||||
else:
|
||||
out.append(node)
|
||||
|
||||
|
||||
def _carve_room(leaf: dict, tiles: list[list[int]], width: int, height: int) -> Rect:
|
||||
"""Carve a room (4x4..10x8) inside the leaf, shrunk from its edges."""
|
||||
shrink = random.randint(1, 2)
|
||||
max_w = max(MIN_ROOM_W, leaf["w"] - 2 * shrink)
|
||||
max_h = max(MIN_ROOM_H, leaf["h"] - 2 * shrink)
|
||||
rw = random.randint(MIN_ROOM_W, min(MAX_ROOM_W, max_w))
|
||||
rh = random.randint(MIN_ROOM_H, min(MAX_ROOM_H, max_h))
|
||||
ox = random.randint(shrink, max(shrink, leaf["w"] - rw - shrink))
|
||||
oy = random.randint(shrink, max(shrink, leaf["h"] - rh - shrink))
|
||||
rx = leaf["x"] + ox
|
||||
ry = leaf["y"] + oy
|
||||
for y in range(ry, ry + rh):
|
||||
for x in range(rx, rx + rw):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
return Rect(rx, ry, rw, rh)
|
||||
|
||||
|
||||
def _connect(node: dict, tiles: list[list[int]], width: int, height: int) -> Rect | None:
|
||||
"""Carve L-corridors between sibling subtree rooms so all rooms connect."""
|
||||
if "left" not in node:
|
||||
return node.get("room")
|
||||
lr = _connect(node["left"], tiles, width, height)
|
||||
rr = _connect(node["right"], tiles, width, height)
|
||||
if lr is not None and rr is not None:
|
||||
_carve_corridor(lr.center, rr.center, tiles, width, height)
|
||||
return lr if lr is not None else rr
|
||||
|
||||
|
||||
def _carve_corridor(a: tuple[int, int], b: tuple[int, int],
|
||||
tiles: list[list[int]], width: int, height: int) -> None:
|
||||
x1, y1 = a
|
||||
x2, y2 = b
|
||||
if random.random() < 0.5:
|
||||
_h_tunnel(x1, x2, y1, tiles, width, height)
|
||||
_v_tunnel(y1, y2, x2, tiles, width, height)
|
||||
else:
|
||||
_v_tunnel(y1, y2, x1, tiles, width, height)
|
||||
_h_tunnel(x1, x2, y2, tiles, width, height)
|
||||
|
||||
|
||||
def _h_tunnel(x1: int, x2: int, y: int, tiles: list[list[int]],
|
||||
width: int, height: int) -> None:
|
||||
for x in range(min(x1, x2), max(x1, x2) + 1):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _v_tunnel(y1: int, y2: int, x: int, tiles: list[list[int]],
|
||||
width: int, height: int) -> None:
|
||||
for y in range(min(y1, y2), max(y1, y2) + 1):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _boss_arena(floor_index: int, width: int, height: int,
|
||||
tiles: list[list[int]]) -> GameMap:
|
||||
"""Floor 9: a single large room; the dragon is placed by populate()."""
|
||||
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
|
||||
rx = (width - rw) // 2
|
||||
ry = (height - rh) // 2
|
||||
for y in range(ry, ry + rh):
|
||||
for x in range(rx, rx + rw):
|
||||
tiles[y][x] = 1
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
stairs = (rx + rw // 2, ry + rh - 2) # unused for descent; victory ends the run
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
return GameMap(width, height, tiles, [room], explored, visible, [],
|
||||
stairs, floor_index)
|
||||
|
||||
|
||||
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Population
|
||||
# --------------------------------------------------------------------------- #
|
||||
def populate(game_map: GameMap, floor_index: int, rng: random.Random | None = None) -> None:
|
||||
"""Place enemies AND items per the plan's per-floor distribution. Never raises.
|
||||
|
||||
Floor 9 (boss) gets the dragon plus exactly two healing potions near the
|
||||
entrance; every other floor gets enemies and items drawn from the roster /
|
||||
catalog, depth-gated.
|
||||
"""
|
||||
r = rng if rng is not None else random
|
||||
|
||||
if floor_index == C.FLOORS - 1:
|
||||
room = game_map.rooms[0]
|
||||
dx, dy = room.x + room.w // 2, room.y + 2
|
||||
if not is_walkable(game_map, dx, dy):
|
||||
ft = _first_floor_tile(game_map)
|
||||
if ft is None:
|
||||
return
|
||||
dx, dy = ft
|
||||
game_map.entities.append(make_enemy("ancient_dragon", dx, dy))
|
||||
_place_boss_potions(game_map, room, r)
|
||||
return
|
||||
|
||||
lo, hi = C.ENEMY_COUNT[floor_index]
|
||||
n = r.randint(lo, hi)
|
||||
pool = [
|
||||
(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
|
||||
]
|
||||
if not pool:
|
||||
return
|
||||
kinds = kinds_for_floor(floor_index)
|
||||
if not kinds:
|
||||
return
|
||||
|
||||
r.shuffle(pool)
|
||||
placed = 0
|
||||
for tile in pool:
|
||||
if placed >= n:
|
||||
break
|
||||
kind = r.choice(kinds)
|
||||
game_map.entities.append(make_enemy(kind, tile[0], tile[1]))
|
||||
placed += 1
|
||||
_place_items(game_map, floor_index, r)
|
||||
|
||||
|
||||
def _place_items(game_map: GameMap, floor_index: int, r) -> None:
|
||||
"""Scatter ITEM_COUNT items from the depth-weighted pool across floor tiles."""
|
||||
lo, hi = C.ITEM_COUNT[floor_index]
|
||||
n = r.randint(lo, hi)
|
||||
pool = [
|
||||
(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
|
||||
]
|
||||
if not pool:
|
||||
return
|
||||
r.shuffle(pool)
|
||||
names = item_pool_for_floor(floor_index)
|
||||
placed = 0
|
||||
for tile in pool:
|
||||
if placed >= n:
|
||||
break
|
||||
game_map.entities.append(make_item(r.choice(names), tile[0], tile[1]))
|
||||
placed += 1
|
||||
|
||||
|
||||
def _place_boss_potions(game_map: GameMap, room: Rect, r) -> None:
|
||||
"""Put two Healing Potions by the boss-room entrance (far side from the dragon)."""
|
||||
ex, ey = room.center[0], room.y + room.h - 2
|
||||
placed = 0
|
||||
for dx in (-1, 0, 1):
|
||||
if placed >= 2:
|
||||
break
|
||||
x, y = ex + dx, ey
|
||||
if is_walkable(game_map, x, y):
|
||||
game_map.entities.append(make_item("Healing Potion", x, y))
|
||||
placed += 1
|
||||
if placed < 2: # entrance row blocked: fall back to any floor tiles
|
||||
pool = [(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1]
|
||||
r.shuffle(pool)
|
||||
for (x, y) in pool:
|
||||
if placed >= 2:
|
||||
break
|
||||
game_map.entities.append(make_item("Healing Potion", x, y))
|
||||
placed += 1
|
||||
|
||||
|
||||
def _first_floor_tile(game_map: GameMap) -> tuple[int, int] | None:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return None
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Grid A* pathfinding with a Manhattan heuristic (plan.md §3)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
|
||||
|
||||
def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] | None:
|
||||
"""Shortest floor path from start to goal, or None if unreachable.
|
||||
|
||||
Walkable tiles are in-bounds floor tiles. `blocked` marks extra impassable
|
||||
tiles (other entities) except that the goal is always reachable even if it
|
||||
sits in `blocked` (an enemy may path up to its target). Returns the path
|
||||
including both endpoints; None if start/goal is a wall or out of bounds.
|
||||
"""
|
||||
sx, sy = start
|
||||
gx, gy = goal
|
||||
|
||||
if not _is_floor(game_map, sx, sy) or not _is_floor(game_map, gx, gy):
|
||||
return None
|
||||
if start == goal:
|
||||
return [(sx, sy)]
|
||||
|
||||
blocked_set = set(blocked)
|
||||
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
counter = 0
|
||||
heapq.heappush(open_heap, (_manhattan(start, goal), counter, start))
|
||||
closed: set[tuple[int, int]] = set()
|
||||
|
||||
while open_heap:
|
||||
_, _, current = heapq.heappop(open_heap)
|
||||
if current in closed:
|
||||
continue
|
||||
if current == goal:
|
||||
return _reconstruct(came_from, current)
|
||||
closed.add(current)
|
||||
cx, cy = current
|
||||
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
|
||||
nb = (nx, ny)
|
||||
if nb in closed or not _is_floor(game_map, nx, ny):
|
||||
continue
|
||||
if nb in blocked_set and nb != goal:
|
||||
continue
|
||||
tentative = g_score[current] + 1
|
||||
if tentative < g_score.get(nb, 1_000_000):
|
||||
g_score[nb] = tentative
|
||||
came_from[nb] = current
|
||||
counter += 1
|
||||
heapq.heappush(open_heap, (tentative + _manhattan(nb, goal), counter, nb))
|
||||
return None
|
||||
|
||||
|
||||
def _is_floor(game_map, x: int, y: int) -> bool:
|
||||
return (0 <= x < game_map.width and 0 <= y < game_map.height
|
||||
and game_map.tiles[y][x] == 1)
|
||||
|
||||
|
||||
def _manhattan(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _reconstruct(came_from: dict, current: tuple[int, int]) -> list[tuple[int, int]]:
|
||||
path = [current]
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append(current)
|
||||
path.reverse()
|
||||
return path
|
||||
@@ -1,224 +0,0 @@
|
||||
"""JSON save/load: exact round-trip serialization of a GameSession.
|
||||
|
||||
The `visible` grids are intentionally NOT serialized — they are recomputed via
|
||||
`recompute_fov` on load. Every other field of Player / Enemy / Item is preserved
|
||||
verbatim, including per-instance enemy state (damaged HP, last-known position,
|
||||
small-slime `can_split=False`, act counters) so a loaded dive matches the saved
|
||||
dive exactly. Entities are reconstructed directly from their serialized fields
|
||||
rather than via `make_enemy`/`make_item`, which would reset mutable state to the
|
||||
roster/catalog defaults.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from engine.game_state import GameSession, recompute_fov
|
||||
from engine.map_gen import GameMap, Rect
|
||||
from entities.enemy import Enemy
|
||||
from entities.entity import Entity
|
||||
from entities.item import Item
|
||||
from entities.player import Effect, Player
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Top level
|
||||
# --------------------------------------------------------------------------- #
|
||||
def session_to_dict(session: GameSession) -> dict:
|
||||
return {
|
||||
"player": _player_to_dict(session.player),
|
||||
"dungeon": [_map_to_dict(m) for m in session.dungeon],
|
||||
"current_floor": session.current_floor,
|
||||
"turn": session.turn,
|
||||
"log": list(session.log),
|
||||
"state": session.state,
|
||||
}
|
||||
|
||||
|
||||
def dict_to_session(d: dict) -> GameSession:
|
||||
session = GameSession(
|
||||
player=_dict_to_player(d["player"]),
|
||||
dungeon=[_dict_to_map(m) for m in d["dungeon"]],
|
||||
current_floor=d["current_floor"],
|
||||
log=list(d["log"]),
|
||||
turn=d["turn"],
|
||||
state=d["state"],
|
||||
)
|
||||
recompute_fov(session)
|
||||
return session
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Player
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _player_to_dict(p: Player) -> dict:
|
||||
return {
|
||||
"type": "player",
|
||||
"x": p.x, "y": p.y,
|
||||
"name": p.name,
|
||||
"sprite_key": p.sprite_key,
|
||||
"blocks": p.blocks,
|
||||
"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],
|
||||
"equipped": {
|
||||
slot: (_item_to_dict(it) if it is not None else None)
|
||||
for slot, it in p.equipped.items()
|
||||
},
|
||||
"effects": [_effect_to_dict(e) for e in p.effects],
|
||||
"facing": p.facing,
|
||||
"invisible": p.invisible,
|
||||
"pending_log": list(p.pending_log),
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_player(d: dict) -> Player:
|
||||
p = Player(d["x"], d["y"])
|
||||
p.name = d["name"]
|
||||
p.sprite_key = d["sprite_key"]
|
||||
p.blocks = d["blocks"]
|
||||
p.hp = d["hp"]
|
||||
p.max_hp = d["max_hp"]
|
||||
p.power = d["power"]
|
||||
p.armor = d["armor"]
|
||||
p.accuracy = d["accuracy"]
|
||||
p.evasion = d["evasion"]
|
||||
p.crit_chance = d["crit_chance"]
|
||||
p.speed = d["speed"]
|
||||
p.level = d["level"]
|
||||
p.xp = d["xp"]
|
||||
p.inventory = [_dict_to_item(i) for i in d["inventory"]]
|
||||
p.equipped = {
|
||||
slot: (_dict_to_item(it) if it is not None else None)
|
||||
for slot, it in d["equipped"].items()
|
||||
}
|
||||
p.effects = [_dict_to_effect(e) for e in d["effects"]]
|
||||
p.facing = d["facing"]
|
||||
p.invisible = d["invisible"]
|
||||
p.pending_log = list(d["pending_log"])
|
||||
return p
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Effects
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _effect_to_dict(e: Effect) -> dict:
|
||||
return {"kind": e.kind, "power": e.power, "duration": e.duration}
|
||||
|
||||
|
||||
def _dict_to_effect(d: dict) -> Effect:
|
||||
return Effect(kind=d["kind"], power=d["power"], duration=d["duration"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Floor entities (enemies + items) — discriminated by "type"
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _entity_to_dict(e) -> dict:
|
||||
if isinstance(e, Enemy):
|
||||
return _enemy_to_dict(e)
|
||||
if isinstance(e, Item):
|
||||
return _item_to_dict(e)
|
||||
return {"type": "entity", "x": e.x, "y": e.y,
|
||||
"name": getattr(e, "name", ""), "sprite_key": getattr(e, "sprite_key", ""),
|
||||
"blocks": getattr(e, "blocks", True)}
|
||||
|
||||
|
||||
def _dict_to_entity(d):
|
||||
t = d.get("type")
|
||||
if t == "enemy":
|
||||
return _dict_to_enemy(d)
|
||||
if t == "item":
|
||||
return _dict_to_item(d)
|
||||
return Entity(d["x"], d["y"], d.get("name", ""),
|
||||
d.get("sprite_key", ""), d.get("blocks", True))
|
||||
|
||||
|
||||
def _enemy_to_dict(e: Enemy) -> dict:
|
||||
return {
|
||||
"type": "enemy",
|
||||
"x": e.x, "y": e.y,
|
||||
"name": e.name,
|
||||
"sprite_key": e.sprite_key,
|
||||
"blocks": e.blocks,
|
||||
"hp": e.hp, "max_hp": e.max_hp,
|
||||
"power": e.power, "armor": e.armor,
|
||||
"accuracy": e.accuracy, "evasion": e.evasion,
|
||||
"crit_chance": e.crit_chance, "speed": e.speed,
|
||||
"behavior": e.behavior, "xp_value": e.xp_value,
|
||||
"last_known_pos": (list(e.last_known_pos)
|
||||
if e.last_known_pos is not None else None),
|
||||
"act_counter": e.act_counter,
|
||||
"can_split": e.can_split,
|
||||
"ranged_power": e.ranged_power,
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_enemy(d: dict) -> Enemy:
|
||||
lkp = d["last_known_pos"]
|
||||
return Enemy(
|
||||
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
|
||||
blocks=d["blocks"],
|
||||
hp=d["hp"], max_hp=d["max_hp"], power=d["power"], armor=d["armor"],
|
||||
accuracy=d["accuracy"], evasion=d["evasion"],
|
||||
crit_chance=d["crit_chance"], speed=d["speed"],
|
||||
behavior=d["behavior"], xp_value=d["xp_value"],
|
||||
last_known_pos=(tuple(lkp) if lkp is not None else None),
|
||||
act_counter=d["act_counter"], can_split=d["can_split"],
|
||||
ranged_power=d["ranged_power"],
|
||||
)
|
||||
|
||||
|
||||
def _item_to_dict(it: Item) -> dict:
|
||||
return {
|
||||
"type": "item",
|
||||
"x": it.x, "y": it.y,
|
||||
"name": it.name,
|
||||
"sprite_key": it.sprite_key,
|
||||
"blocks": it.blocks,
|
||||
"item_type": it.item_type,
|
||||
"subtype": it.subtype,
|
||||
"stats": dict(it.stats),
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_item(d: dict) -> Item:
|
||||
return Item(
|
||||
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
|
||||
blocks=d["blocks"], item_type=d["item_type"],
|
||||
subtype=d["subtype"], stats=dict(d["stats"]),
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Map
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _rect_to_dict(r: Rect) -> dict:
|
||||
return {"x": r.x, "y": r.y, "w": r.w, "h": r.h}
|
||||
|
||||
|
||||
def _map_to_dict(m: GameMap) -> dict:
|
||||
return {
|
||||
"width": m.width,
|
||||
"height": m.height,
|
||||
"tiles": [list(row) for row in m.tiles],
|
||||
"rooms": [_rect_to_dict(r) for r in m.rooms],
|
||||
"explored": [list(row) for row in m.explored],
|
||||
"entities": [_entity_to_dict(e) for e in m.entities],
|
||||
"stairs_down": list(m.stairs_down),
|
||||
"floor_index": m.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_map(d: dict) -> GameMap:
|
||||
width = d["width"]
|
||||
height = d["height"]
|
||||
return GameMap(
|
||||
width=width, height=height,
|
||||
tiles=[list(row) for row in d["tiles"]],
|
||||
rooms=[Rect(r["x"], r["y"], r["w"], r["h"]) for r in d["rooms"]],
|
||||
explored=[list(row) for row in d["explored"]],
|
||||
visible=[[False] * width for _ in range(height)],
|
||||
entities=[_dict_to_entity(e) for e in d["entities"]],
|
||||
stairs_down=tuple(d["stairs_down"]),
|
||||
floor_index=d["floor_index"],
|
||||
)
|
||||
Reference in new issue
Block a user