(Underdepths) Prepare for Pass 4
This commit is contained in:
33 files changed
+123
-4173
No files matched your search
@@ -1,263 +0,0 @@
|
||||
"""Player actions: pure functions that mutate a GameSession and log.
|
||||
|
||||
Each turn-costing action resolves its effect, then calls _end_turn which ticks
|
||||
the player's effect timers, advances the turn counter, runs every living enemy's
|
||||
turn (the entity list is snapshotted first so slime splits / deaths can't corrupt
|
||||
the loop), recomputes FOV, and flips the session to "dead" or "victory" when
|
||||
warranted. Actions never raise on a valid game state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from data.constants import BOSS_FLOOR, LOG_MAX, STRENGTH_POWER_BONUS
|
||||
from engine.combat import attack
|
||||
from engine.map_gen import walkable
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from ai.behaviors import enemy_turn, on_enemy_death
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from engine.game_state import GameSession
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
|
||||
_DRAGON_NAME = "Ancient Dragon"
|
||||
|
||||
|
||||
def _enemy_at(cmap: GameMap, x: int, y: int) -> Enemy | None:
|
||||
for e in cmap.entities:
|
||||
if isinstance(e, Enemy) and e.hp > 0 and e.x == x and e.y == y:
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def _remove_entity(cmap: GameMap, entity: object) -> None:
|
||||
ents = cmap.entities
|
||||
for i, e in enumerate(ents):
|
||||
if e is entity:
|
||||
del ents[i]
|
||||
return
|
||||
|
||||
|
||||
def _trim_log(sess: GameSession) -> None:
|
||||
if len(sess.log) > LOG_MAX:
|
||||
del sess.log[: len(sess.log) - LOG_MAX]
|
||||
|
||||
|
||||
def _check_player_death(sess: GameSession) -> None:
|
||||
if sess.player.hp <= 0:
|
||||
sess.player.hp = 0
|
||||
sess.state = "dead"
|
||||
sess.log.append("You have died.")
|
||||
|
||||
|
||||
def _check_victory(sess: GameSession) -> None:
|
||||
# The dragon only ever exists on the boss floor; once it is gone there is
|
||||
# nothing left to conquer, so the empty boss floor means victory.
|
||||
if sess.current_floor != BOSS_FLOOR:
|
||||
return
|
||||
if sess.state != "playing":
|
||||
return
|
||||
dragon_alive = any(
|
||||
isinstance(e, Enemy) and e.name == _DRAGON_NAME and e.hp > 0
|
||||
for e in sess.current_map.entities
|
||||
)
|
||||
if not dragon_alive:
|
||||
sess.state = "victory"
|
||||
sess.log.append("You slew the Ancient Dragon! You conquer the Underdepths!")
|
||||
|
||||
|
||||
def _run_enemies(sess: GameSession) -> None:
|
||||
cmap = sess.current_map
|
||||
enemies = [e for e in cmap.entities if isinstance(e, Enemy) and e.hp > 0]
|
||||
for e in enemies:
|
||||
if sess.state != "playing":
|
||||
break
|
||||
if e.hp <= 0:
|
||||
continue
|
||||
enemy_turn(e, sess)
|
||||
|
||||
|
||||
def _end_turn(sess: GameSession) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
sess.player.tick_timers(sess.log)
|
||||
sess.turn += 1
|
||||
_run_enemies(sess)
|
||||
sess.recompute_fov()
|
||||
_check_player_death(sess)
|
||||
_check_victory(sess)
|
||||
_trim_log(sess)
|
||||
|
||||
|
||||
def try_move(sess: GameSession, dx: int, dy: int) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
p = sess.player
|
||||
cmap = sess.current_map
|
||||
nx, ny = p.x + dx, p.y + dy
|
||||
|
||||
target = _enemy_at(cmap, nx, ny)
|
||||
if target is not None:
|
||||
attack(p, target, sess.log)
|
||||
if target.hp <= 0:
|
||||
p.gain_xp(target.xp_value, sess.log)
|
||||
_remove_entity(cmap, target)
|
||||
on_enemy_death(target, sess)
|
||||
_end_turn(sess)
|
||||
return
|
||||
|
||||
if walkable(cmap, nx, ny):
|
||||
p.x, p.y = nx, ny
|
||||
_end_turn(sess)
|
||||
return
|
||||
# Bumping a wall costs no turn.
|
||||
|
||||
|
||||
def pickup(sess: GameSession) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
p = sess.player
|
||||
cmap = sess.current_map
|
||||
for e in list(cmap.entities):
|
||||
if isinstance(e, Item) and e.x == p.x and e.y == p.y:
|
||||
_remove_entity(cmap, e)
|
||||
p.inventory.append(e)
|
||||
sess.log.append(f"You pick up the {e.name}.")
|
||||
_end_turn(sess)
|
||||
return
|
||||
sess.log.append("There is nothing here to pick up.")
|
||||
|
||||
|
||||
def descend(sess: GameSession) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
cmap = sess.current_map
|
||||
p = sess.player
|
||||
if cmap.stairs_down is None:
|
||||
sess.log.append("There are no stairs here.")
|
||||
return
|
||||
if (p.x, p.y) != cmap.stairs_down:
|
||||
sess.log.append("You must stand on the stairs to descend.")
|
||||
return
|
||||
if sess.current_floor >= len(sess.dungeon) - 1:
|
||||
return
|
||||
sess.current_floor += 1
|
||||
nxt = sess.current_map
|
||||
if nxt.rooms:
|
||||
sx, sy = nxt.rooms[0].center()
|
||||
else:
|
||||
tile = next(
|
||||
((x, y) for y in range(nxt.height) for x in range(nxt.width) if nxt.tiles[y][x] == 1),
|
||||
(p.x, p.y),
|
||||
)
|
||||
sx, sy = tile
|
||||
p.x, p.y = sx, sy
|
||||
sess.log.append(f"You descend to floor {sess.current_floor + 1}.")
|
||||
# Arriving on a fresh floor is a free look: tick timers + advance the turn
|
||||
# but do not let enemies act before the player has moved.
|
||||
sess.player.tick_timers(sess.log)
|
||||
sess.turn += 1
|
||||
sess.recompute_fov()
|
||||
_check_player_death(sess)
|
||||
_trim_log(sess)
|
||||
|
||||
|
||||
def use_item(sess: GameSession, index: int) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
p = sess.player
|
||||
if index < 0 or index >= len(p.inventory):
|
||||
sess.log.append("You have no such item.")
|
||||
return
|
||||
item = p.inventory[index]
|
||||
kind, sub = item.kind, item.sub
|
||||
|
||||
if kind == "potion":
|
||||
if sub == "healing":
|
||||
amount = min(item.heal, p.max_hp - p.hp)
|
||||
p.hp += amount
|
||||
sess.log.append(f"You quaff the {item.name} and recover {amount} HP.")
|
||||
elif sub == "strength":
|
||||
p.timers["strength"] = item.duration
|
||||
sess.log.append(
|
||||
f"A surge of strength courses through you! (+{STRENGTH_POWER_BONUS} power for {item.duration} turns)"
|
||||
)
|
||||
elif sub == "invisibility":
|
||||
p.timers["invisibility"] = item.duration
|
||||
sess.log.append(f"You drink the {item.name} and fade from sight.")
|
||||
else:
|
||||
sess.log.append(f"Nothing happens with the {item.name}.")
|
||||
return
|
||||
elif kind == "scroll":
|
||||
if sub == "fireball":
|
||||
_fireball(sess, p.x, p.y, item.damage, item.radius)
|
||||
elif sub == "teleport":
|
||||
_teleport(sess)
|
||||
elif sub == "mapping":
|
||||
for row in sess.current_map.explored:
|
||||
for i in range(len(row)):
|
||||
row[i] = True
|
||||
sess.log.append("The scroll reveals the entire floor!")
|
||||
else:
|
||||
sess.log.append(f"Nothing happens with the {item.name}.")
|
||||
return
|
||||
else:
|
||||
sess.log.append(f"You can't quaff or read the {item.name}.")
|
||||
return
|
||||
|
||||
p.inventory.pop(index)
|
||||
_end_turn(sess)
|
||||
|
||||
|
||||
def equip(sess: GameSession, index: int) -> None:
|
||||
if sess.state != "playing":
|
||||
return
|
||||
p = sess.player
|
||||
if index < 0 or index >= len(p.inventory):
|
||||
sess.log.append("You have no such item.")
|
||||
return
|
||||
item = p.inventory[index]
|
||||
if item.kind not in ("weapon", "armor"):
|
||||
sess.log.append(f"You can't equip the {item.name}.")
|
||||
return
|
||||
p.inventory.pop(index)
|
||||
p.equip_item(item)
|
||||
sess.log.append(f"You equip the {item.name}.")
|
||||
_end_turn(sess)
|
||||
|
||||
|
||||
def _fireball(sess: GameSession, cx: int, cy: int, damage: int, radius: int) -> None:
|
||||
sess.log.append("A fireball erupts!")
|
||||
cmap = sess.current_map
|
||||
hit_any = False
|
||||
for e in list(cmap.entities):
|
||||
if isinstance(e, Enemy) and e.hp > 0 and max(abs(e.x - cx), abs(e.y - cy)) <= radius:
|
||||
e.hp -= damage
|
||||
sess.log.append(f"The fireball burns the {e.name} for {damage} damage.")
|
||||
hit_any = True
|
||||
if e.hp <= 0:
|
||||
sess.player.gain_xp(e.xp_value, sess.log)
|
||||
_remove_entity(cmap, e)
|
||||
on_enemy_death(e, sess)
|
||||
if not hit_any:
|
||||
sess.log.append("The flames find no target.")
|
||||
|
||||
|
||||
def _teleport(sess: GameSession) -> None:
|
||||
cmap = sess.current_map
|
||||
tiles = [
|
||||
(x, y)
|
||||
for y in range(cmap.height)
|
||||
for x in range(cmap.width)
|
||||
if cmap.tiles[y][x] == 1
|
||||
]
|
||||
if not tiles:
|
||||
sess.log.append("The scroll fizzles.")
|
||||
return
|
||||
nx, ny = random.choice(tiles)
|
||||
sess.player.x, sess.player.y = nx, ny
|
||||
sess.log.append("You teleport across the floor!")
|
||||
@@ -1,98 +0,0 @@
|
||||
"""Generated sound effects with graceful silent fallback.
|
||||
|
||||
Audio is feedback only: it never alters game state or blocks input. The mixer is
|
||||
initialized at the application boundary; if init fails (no device, headless CI),
|
||||
self.enabled stays False and every call becomes a silent no-op. Sounds are built
|
||||
in memory from array.array tone samples matched to the mixer's format -- no
|
||||
asset files are loaded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
# name -> (frequency_hz, duration_ms, volume)
|
||||
_EFFECTS: dict[str, tuple[int, int, float]] = {
|
||||
"hit": (330, 60, 0.30),
|
||||
"miss": (150, 70, 0.18),
|
||||
"damage": (110, 130, 0.40),
|
||||
"pickup": (660, 70, 0.28),
|
||||
"stairs": (520, 120, 0.28),
|
||||
"levelup": (740, 170, 0.32),
|
||||
"death": (90, 280, 0.45),
|
||||
"victory": (880, 340, 0.38),
|
||||
}
|
||||
|
||||
|
||||
class Audio:
|
||||
def __init__(self) -> None:
|
||||
self.enabled: bool = False
|
||||
self.muted: bool = False
|
||||
self.sounds: dict = {}
|
||||
self._freq: int = 22050
|
||||
self._size: int = -16
|
||||
self._channels: int = 2
|
||||
try:
|
||||
pygame.mixer.init()
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
info = pygame.mixer.get_init()
|
||||
if info:
|
||||
self._freq, self._size, self._channels = info
|
||||
for name, spec in _EFFECTS.items():
|
||||
try:
|
||||
snd = self._build_sound(*spec)
|
||||
except Exception:
|
||||
continue
|
||||
self.sounds[name] = snd
|
||||
self.enabled = bool(self.sounds)
|
||||
except Exception:
|
||||
self.enabled = False
|
||||
self.sounds = {}
|
||||
|
||||
def _build_sound(self, freq_hz: int, dur_ms: int, volume: float):
|
||||
n = max(1, int(self._freq * dur_ms / 1000))
|
||||
size = self._size
|
||||
channels = self._channels
|
||||
if abs(size) == 8:
|
||||
typecode = "b" if size < 0 else "B"
|
||||
peak = 127
|
||||
zero = 0 if size < 0 else 128
|
||||
signed = size < 0
|
||||
else:
|
||||
# treat anything 16-bit-or-wider as signed 16-bit; mixer default.
|
||||
typecode = "h"
|
||||
peak = 32767
|
||||
zero = 0
|
||||
signed = True
|
||||
samples: list[int] = []
|
||||
for i in range(n):
|
||||
t = i / self._freq
|
||||
env = max(0.0, 1.0 - i / n)
|
||||
wave = math.sin(2 * math.pi * freq_hz * t) * env * volume
|
||||
val = int(wave * peak) if signed else int(zero + wave * peak)
|
||||
samples.append(val)
|
||||
interleaved: list[int] = []
|
||||
for v in samples:
|
||||
interleaved.extend([v] * channels)
|
||||
arr = array.array(typecode, interleaved)
|
||||
return pygame.mixer.Sound(buffer=arr.tobytes())
|
||||
|
||||
def play(self, name: str) -> None:
|
||||
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) -> None:
|
||||
self.muted = not self.muted
|
||||
@@ -1,71 +0,0 @@
|
||||
"""Combat: hit resolution and damage calculation. Pure functions over state.
|
||||
|
||||
Combat is symmetric: the same attack() handles player-vs-enemy and
|
||||
enemy-vs-player melee/ranged strikes. It mutates defender.hp and appends
|
||||
human-readable messages to the caller-supplied log. It NEVER awards XP or
|
||||
removes entities — that is the caller's job (game loop owns lifecycle).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from data.constants import HIT_BASE, HIT_CEIL, HIT_FLOOR, HIT_STEP
|
||||
|
||||
|
||||
def eff_acc(o: Any) -> int | float:
|
||||
return getattr(o, "effective_accuracy", getattr(o, "accuracy", 5))
|
||||
|
||||
|
||||
def eff_eva(o: Any) -> int | float:
|
||||
return getattr(o, "effective_evasion", getattr(o, "evasion", 2))
|
||||
|
||||
|
||||
def eff_power(o: Any) -> int | float:
|
||||
return getattr(o, "effective_power", getattr(o, "power", 0))
|
||||
|
||||
|
||||
def eff_armor(o: Any) -> int | float:
|
||||
return getattr(o, "effective_armor", getattr(o, "armor", 0))
|
||||
|
||||
|
||||
def eff_crit(o: Any) -> float:
|
||||
return getattr(o, "effective_crit_chance", getattr(o, "crit_chance", 0.0))
|
||||
|
||||
|
||||
def hit_chance(attacker: Any, defender: Any) -> float:
|
||||
base = HIT_BASE + (eff_acc(attacker) - eff_eva(defender)) * HIT_STEP
|
||||
return max(HIT_FLOOR, min(HIT_CEIL, base))
|
||||
|
||||
|
||||
def attack(attacker: Any, defender: Any, log: list[str], ranged: bool = False) -> dict:
|
||||
was_alive = getattr(defender, "hp", 0) > 0
|
||||
|
||||
if random.random() >= hit_chance(attacker, defender):
|
||||
log.append(f"{attacker.name} misses {defender.name}")
|
||||
return {"hit": False, "damage": 0, "crit": False}
|
||||
|
||||
if ranged and hasattr(attacker, "ranged_power"):
|
||||
base = getattr(attacker, "ranged_power", 0)
|
||||
else:
|
||||
base = eff_power(attacker)
|
||||
|
||||
reduced = max(0, base - eff_armor(defender))
|
||||
crit = random.random() < eff_crit(attacker)
|
||||
damage = reduced * (2 if crit else 1)
|
||||
|
||||
defender.hp -= damage
|
||||
|
||||
if crit:
|
||||
log.append(f"Critical! {attacker.name} hits {defender.name} for {damage} damage")
|
||||
else:
|
||||
log.append(f"{attacker.name} hits {defender.name} for {damage} damage")
|
||||
|
||||
# Defeat is logged only on the living->dead transition so a strike against
|
||||
# an already-dead defender never duplicates the line and never raises.
|
||||
if was_alive and getattr(defender, "hp", 0) <= 0:
|
||||
xp = getattr(defender, "xp_value", 0)
|
||||
log.append(f"{attacker.name} defeats {defender.name}! (+{xp} XP)")
|
||||
|
||||
return {"hit": True, "damage": damage, "crit": crit}
|
||||
@@ -1,108 +0,0 @@
|
||||
"""Recursive shadowcasting field of view.
|
||||
|
||||
8-octant recursive shadowcasting (Bjorn Bergstrom). A floor tile is visible when
|
||||
an unblocked line of sight reaches it; walls block and cast shadows. A wall next
|
||||
to a visible floor tile is itself visible so room boundaries render. The origin
|
||||
never lands in the lit set, so a player sealed inside a single floor tile has no
|
||||
lit floor neighbour and sees only themselves.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
|
||||
# (xx, xy, yx, yy) transforms map a single octant scan onto all 8 octants.
|
||||
_FOV_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 _blocks(gmap: GameMap, x: int, y: int) -> bool:
|
||||
if x < 0 or y < 0 or x >= gmap.width or y >= gmap.height:
|
||||
return True
|
||||
return gmap.tiles[y][x] == 0
|
||||
|
||||
|
||||
def _cast_light(
|
||||
gmap: GameMap,
|
||||
cx: int,
|
||||
cy: int,
|
||||
row: int,
|
||||
start: float,
|
||||
end: float,
|
||||
radius: int,
|
||||
radius_sq: int,
|
||||
xx: int,
|
||||
xy: int,
|
||||
yx: int,
|
||||
yy: int,
|
||||
light: set[tuple[int, int]],
|
||||
) -> None:
|
||||
if start < end:
|
||||
return
|
||||
width, height, tiles = gmap.width, gmap.height, gmap.tiles
|
||||
new_start = 0.0
|
||||
j = row
|
||||
while j <= radius:
|
||||
dx = -j - 1
|
||||
dy = -j
|
||||
blocked = False
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
x = cx + dx * xx + dy * xy
|
||||
y = 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 <= radius_sq and 0 <= x < width and 0 <= y < height:
|
||||
light.add((x, y))
|
||||
if blocked:
|
||||
if _blocks(gmap, x, y):
|
||||
new_start = r_slope
|
||||
continue
|
||||
blocked = False
|
||||
start = new_start
|
||||
elif _blocks(gmap, x, y) and j < radius:
|
||||
blocked = True
|
||||
_cast_light(
|
||||
gmap, cx, cy, j + 1, start, l_slope,
|
||||
radius, radius_sq, xx, xy, yx, yy, light,
|
||||
)
|
||||
new_start = r_slope
|
||||
if blocked:
|
||||
break
|
||||
j += 1
|
||||
|
||||
|
||||
def compute_fov(gmap: GameMap, ox: int, oy: int, radius: int) -> set[tuple[int, int]]:
|
||||
radius_sq = radius * radius
|
||||
light: set[tuple[int, int]] = set()
|
||||
for xx, xy, yx, yy in _FOV_OCTANTS:
|
||||
_cast_light(gmap, ox, oy, 1, 1.0, 0.0, radius, radius_sq, xx, xy, yx, yy, light)
|
||||
|
||||
width, height, tiles = gmap.width, gmap.height, gmap.tiles
|
||||
lit_floors = {(x, y) for (x, y) in light if tiles[y][x] == 1}
|
||||
|
||||
result: set[tuple[int, int]] = {(ox, oy)} | lit_floors
|
||||
for fx, fy in lit_floors:
|
||||
for ddx in (-1, 0, 1):
|
||||
wx = fx + ddx
|
||||
if wx < 0 or wx >= width:
|
||||
continue
|
||||
for ddy in (-1, 0, 1):
|
||||
if not ddx and not ddy:
|
||||
continue
|
||||
wy = fy + ddy
|
||||
if wy < 0 or wy >= height:
|
||||
continue
|
||||
if tiles[wy][wx] == 0 and max(abs(wx - ox), abs(wy - oy)) <= radius:
|
||||
result.add((wx, wy))
|
||||
return result
|
||||
@@ -1,154 +0,0 @@
|
||||
"""GameSession: single source of truth for all mutable state.
|
||||
|
||||
Owns the player, all 10 dungeon floors, the message log, turn counter, and the
|
||||
high-level state tag. new_game() generates a fresh dungeon and populates it per
|
||||
plan.md's per-floor tables; recompute_fov() refreshes the current floor's
|
||||
visibility from the player's position.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data.constants import FLOORS, BOSS_FLOOR, SIGHT_RADIUS
|
||||
from engine.fov import compute_fov
|
||||
from engine.map_gen import GameMap, generate_dungeon
|
||||
from entities.player import Player
|
||||
from data.enemies import enemies_for_floor
|
||||
from entities.enemy import make_enemy
|
||||
from entities.item import make_item
|
||||
from data.items import roll_item
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Player
|
||||
dungeon: list[GameMap]
|
||||
current_floor: int
|
||||
log: list[str]
|
||||
turn: int = 0
|
||||
state: str = "playing"
|
||||
|
||||
@property
|
||||
def current_map(self) -> GameMap:
|
||||
return self.dungeon[self.current_floor]
|
||||
|
||||
def recompute_fov(self) -> None:
|
||||
cmap = self.current_map
|
||||
for y in range(cmap.height):
|
||||
vrow = cmap.visible[y]
|
||||
for x in range(cmap.width):
|
||||
vrow[x] = False
|
||||
seen = compute_fov(cmap, self.player.x, self.player.y, SIGHT_RADIUS)
|
||||
for (x, y) in seen:
|
||||
cmap.visible[y][x] = True
|
||||
cmap.explored[y][x] = True
|
||||
|
||||
|
||||
# --- per-floor spawn counts (plan.md spawning table) --------------------------
|
||||
# (floor_lo, floor_hi, min, max) for enemies and items.
|
||||
_ENEMY_TABLE: tuple[tuple[int, int, int, int], ...] = (
|
||||
(0, 1, 3, 4), (2, 3, 4, 6), (4, 5, 5, 7), (6, 7, 6, 8), (8, 8, 7, 9),
|
||||
)
|
||||
_ITEM_TABLE: tuple[tuple[int, int, int, int], ...] = (
|
||||
(0, 1, 2, 3), (2, 3, 2, 3), (4, 5, 3, 4), (6, 7, 3, 4), (8, 8, 4, 5),
|
||||
)
|
||||
|
||||
|
||||
def _count_for(floor_index: int, table: tuple[tuple[int, int, int, int], ...]) -> tuple[int, int]:
|
||||
for lo, hi, mn, mx in table:
|
||||
if lo <= floor_index <= hi:
|
||||
return (mn, mx)
|
||||
return (0, 0)
|
||||
|
||||
|
||||
def _floor_tiles(gmap: GameMap) -> list[tuple[int, int]]:
|
||||
return [
|
||||
(x, y)
|
||||
for y in range(gmap.height)
|
||||
for x in range(gmap.width)
|
||||
if gmap.tiles[y][x] == 1
|
||||
]
|
||||
|
||||
|
||||
def _populate_boss(gmap: GameMap) -> None:
|
||||
room = gmap.rooms[0]
|
||||
cx, cy = room.center()
|
||||
dragon_x = room.x + room.w - 2
|
||||
dragon_y = room.y + room.h - 2
|
||||
if not (0 <= dragon_x < gmap.width and 0 <= dragon_y < gmap.height):
|
||||
dragon_x, dragon_y = cx, cy
|
||||
gmap.entities.append(make_enemy("Ancient Dragon", dragon_x, dragon_y))
|
||||
placed = 0
|
||||
for ox, oy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
|
||||
if placed >= 2:
|
||||
break
|
||||
px, py = cx + ox, cy + oy
|
||||
if 0 <= px < gmap.width and 0 <= py < gmap.height and gmap.tiles[py][px] == 1:
|
||||
pot = make_item("Healing Potion")
|
||||
pot.x, pot.y = px, py
|
||||
gmap.entities.append(pot)
|
||||
placed += 1
|
||||
|
||||
|
||||
def _populate(gmap: GameMap, floor_index: int, rng: random.Random) -> None:
|
||||
if floor_index == BOSS_FLOOR:
|
||||
_populate_boss(gmap)
|
||||
return
|
||||
|
||||
occupied: set[tuple[int, int]] = set()
|
||||
if gmap.rooms:
|
||||
occupied.add(gmap.rooms[0].center())
|
||||
if gmap.stairs_down is not None:
|
||||
occupied.add(gmap.stairs_down)
|
||||
|
||||
tiles = _floor_tiles(gmap)
|
||||
rng.shuffle(tiles)
|
||||
|
||||
n_enemies = rng.randint(*_count_for(floor_index, _ENEMY_TABLE))
|
||||
roster = enemies_for_floor(floor_index)
|
||||
placed = 0
|
||||
if roster:
|
||||
for (x, y) in tiles:
|
||||
if placed >= n_enemies:
|
||||
break
|
||||
if (x, y) in occupied:
|
||||
continue
|
||||
gmap.entities.append(make_enemy(rng.choice(roster), x, y))
|
||||
occupied.add((x, y))
|
||||
placed += 1
|
||||
|
||||
n_items = rng.randint(*_count_for(floor_index, _ITEM_TABLE))
|
||||
placed = 0
|
||||
for (x, y) in tiles:
|
||||
if placed >= n_items:
|
||||
break
|
||||
if (x, y) in occupied:
|
||||
continue
|
||||
item = roll_item(floor_index, rng)
|
||||
item.x, item.y = x, y
|
||||
gmap.entities.append(item)
|
||||
occupied.add((x, y))
|
||||
placed += 1
|
||||
|
||||
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
rng = random.Random(seed)
|
||||
dungeon = [generate_dungeon(fi, rng) for fi in range(FLOORS)]
|
||||
for fi, gmap in enumerate(dungeon):
|
||||
_populate(gmap, fi, rng)
|
||||
|
||||
spawn = dungeon[0].rooms[0].center()
|
||||
player = Player(x=spawn[0], y=spawn[1], name="You")
|
||||
|
||||
sess = GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=[],
|
||||
turn=0,
|
||||
state="playing",
|
||||
)
|
||||
sess.log.append("Welcome to the Underdepths. Slay the Ancient Dragon on floor 10!")
|
||||
sess.recompute_fov()
|
||||
return sess
|
||||
@@ -1,212 +0,0 @@
|
||||
"""BSP dungeon generation.
|
||||
|
||||
Deterministic for a given (floor_index, rng): the only source of randomness is
|
||||
the passed random.Random. The global random module is never touched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data.constants import (
|
||||
MAP_W, MAP_H, BOSS_FLOOR,
|
||||
BSP_SPLITS_MIN, BSP_SPLITS_MAX, SPLIT_MIN_DIM,
|
||||
SPLIT_RATIO_MIN, SPLIT_RATIO_MAX,
|
||||
ROOM_MIN_W, ROOM_MAX_W, ROOM_MIN_H, ROOM_MAX_H,
|
||||
ROOM_SHRINK_MIN, ROOM_SHRINK_MAX,
|
||||
BOSS_ROOM_W, BOSS_ROOM_H,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
|
||||
def center(self) -> tuple[int, int]:
|
||||
return (self.x + self.w // 2, self.y + self.h // 2)
|
||||
|
||||
def inner(self) -> tuple[int, int, int, int]:
|
||||
# x1, y1, x2, y2 inclusive of the carved floor area
|
||||
return (self.x, self.y, self.x + self.w - 1, self.y + self.h - 1)
|
||||
|
||||
|
||||
@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
|
||||
floor_index: int
|
||||
|
||||
|
||||
class _Node:
|
||||
__slots__ = ("region", "left", "right", "room")
|
||||
|
||||
def __init__(self, region: Rect) -> None:
|
||||
self.region: Rect = region
|
||||
self.left: _Node | None = None
|
||||
self.right: _Node | None = None
|
||||
self.room: Rect | None = None
|
||||
|
||||
|
||||
def _splittable(region: Rect, depth: int) -> bool:
|
||||
vertical = (depth % 2 == 0)
|
||||
extent = region.w if vertical else region.h
|
||||
return extent >= SPLIT_MIN_DIM
|
||||
|
||||
|
||||
def _split_region(region: Rect, depth: int, rng: random.Random) -> tuple[Rect, Rect]:
|
||||
vertical = (depth % 2 == 0)
|
||||
half = SPLIT_MIN_DIM // 2
|
||||
if vertical:
|
||||
cut = region.x + int(region.w * rng.uniform(SPLIT_RATIO_MIN, SPLIT_RATIO_MAX))
|
||||
cut = max(region.x + half, min(cut, region.x + region.w - half))
|
||||
a = Rect(region.x, region.y, cut - region.x, region.h)
|
||||
b = Rect(cut, region.y, region.x + region.w - cut, region.h)
|
||||
else:
|
||||
cut = region.y + int(region.h * rng.uniform(SPLIT_RATIO_MIN, SPLIT_RATIO_MAX))
|
||||
cut = max(region.y + half, min(cut, region.y + region.h - half))
|
||||
a = Rect(region.x, region.y, region.w, cut - region.y)
|
||||
b = Rect(region.x, cut, region.w, region.y + region.h - cut)
|
||||
return a, b
|
||||
|
||||
|
||||
def _make_room(region: Rect, rng: random.Random, tiles: list[list[int]]) -> Rect:
|
||||
shrink = rng.randint(ROOM_SHRINK_MIN, ROOM_SHRINK_MAX)
|
||||
avail_w = region.w - 2 * shrink
|
||||
avail_h = region.h - 2 * shrink
|
||||
if avail_w < ROOM_MIN_W or avail_h < ROOM_MIN_H:
|
||||
shrink = max(0, min(shrink, (region.w - ROOM_MIN_W) // 2, (region.h - ROOM_MIN_H) // 2))
|
||||
avail_w = max(ROOM_MIN_W, region.w - 2 * shrink)
|
||||
avail_h = max(ROOM_MIN_H, region.h - 2 * shrink)
|
||||
rw = min(avail_w, rng.randint(ROOM_MIN_W, ROOM_MAX_W))
|
||||
rh = min(avail_h, rng.randint(ROOM_MIN_H, ROOM_MAX_H))
|
||||
ox = rng.randint(0, avail_w - rw)
|
||||
oy = rng.randint(0, avail_h - rh)
|
||||
rx = region.x + shrink + ox
|
||||
ry = region.y + shrink + oy
|
||||
for yy in range(ry, ry + rh):
|
||||
for xx in range(rx, rx + rw):
|
||||
tiles[yy][xx] = 1
|
||||
return Rect(rx, ry, rw, rh)
|
||||
|
||||
|
||||
def _build(region: Rect, depth: int, rng: random.Random,
|
||||
tiles: list[list[int]], budget: list[int]) -> _Node:
|
||||
node = _Node(region)
|
||||
if budget[0] > 0 and _splittable(region, depth):
|
||||
a, b = _split_region(region, depth, rng)
|
||||
budget[0] -= 1
|
||||
node.left = _build(a, depth + 1, rng, tiles, budget)
|
||||
node.right = _build(b, depth + 1, rng, tiles, budget)
|
||||
else:
|
||||
node.room = _make_room(region, rng, tiles)
|
||||
return node
|
||||
|
||||
|
||||
def _gather(node: _Node, out: list[Rect]) -> None:
|
||||
if node.room is not None:
|
||||
out.append(node.room)
|
||||
return
|
||||
assert node.left is not None and node.right is not None
|
||||
_gather(node.left, out)
|
||||
_gather(node.right, out)
|
||||
|
||||
|
||||
def _hcarve(x1: int, x2: int, y: int, tiles: list[list[int]]) -> None:
|
||||
for x in range(min(x1, x2), max(x1, x2) + 1):
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _vcarve(y1: int, y2: int, x: int, tiles: list[list[int]]) -> None:
|
||||
for y in range(min(y1, y2), max(y1, y2) + 1):
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _corridor(a: Rect, b: Rect, rng: random.Random, tiles: list[list[int]]) -> None:
|
||||
ax, ay = a.center()
|
||||
bx, by = b.center()
|
||||
if rng.random() < 0.5:
|
||||
_hcarve(ax, bx, ay, tiles)
|
||||
_vcarve(ay, by, bx, tiles)
|
||||
else:
|
||||
_vcarve(ay, by, ax, tiles)
|
||||
_hcarve(ax, bx, by, tiles)
|
||||
|
||||
|
||||
def _connect(node: _Node, rng: random.Random, tiles: list[list[int]]) -> Rect:
|
||||
# Carves a corridor between a representative room of each subtree, for every
|
||||
# internal node -> a spanning tree -> the whole floor is connected.
|
||||
if node.room is not None:
|
||||
return node.room
|
||||
assert node.left is not None and node.right is not None
|
||||
ra = _connect(node.left, rng, tiles)
|
||||
rb = _connect(node.right, rng, tiles)
|
||||
_corridor(ra, rb, rng, tiles)
|
||||
return ra
|
||||
|
||||
|
||||
def _empty_grids() -> tuple[list[list[bool]], list[list[bool]]]:
|
||||
explored = [[False] * MAP_W for _ in range(MAP_H)]
|
||||
visible = [[False] * MAP_W for _ in range(MAP_H)]
|
||||
return explored, visible
|
||||
|
||||
|
||||
def _boss_arena(floor_index: int) -> GameMap:
|
||||
tiles = [[0] * MAP_W for _ in range(MAP_H)]
|
||||
rx = (MAP_W - BOSS_ROOM_W) // 2
|
||||
ry = (MAP_H - BOSS_ROOM_H) // 2
|
||||
for yy in range(ry, ry + BOSS_ROOM_H):
|
||||
for xx in range(rx, rx + BOSS_ROOM_W):
|
||||
tiles[yy][xx] = 1
|
||||
explored, visible = _empty_grids()
|
||||
return GameMap(
|
||||
width=MAP_W, height=MAP_H, tiles=tiles,
|
||||
rooms=[Rect(rx, ry, BOSS_ROOM_W, BOSS_ROOM_H)],
|
||||
explored=explored, visible=visible, entities=[],
|
||||
stairs_down=None, floor_index=floor_index,
|
||||
)
|
||||
|
||||
|
||||
def generate_dungeon(floor_index: int, rng: random.Random) -> GameMap:
|
||||
if floor_index == BOSS_FLOOR:
|
||||
return _boss_arena(floor_index)
|
||||
|
||||
tiles = [[0] * MAP_W for _ in range(MAP_H)]
|
||||
interior = Rect(1, 1, MAP_W - 2, MAP_H - 2)
|
||||
budget = [rng.randint(BSP_SPLITS_MIN, BSP_SPLITS_MAX)]
|
||||
root = _build(interior, 0, rng, tiles, budget)
|
||||
|
||||
rooms: list[Rect] = []
|
||||
_gather(root, rooms)
|
||||
_connect(root, rng, tiles)
|
||||
|
||||
spawn = rooms[0].center()
|
||||
far = max(rooms, key=lambda r: abs(r.center()[0] - spawn[0]) + abs(r.center()[1] - spawn[1]))
|
||||
stairs_down = far.center()
|
||||
|
||||
explored, visible = _empty_grids()
|
||||
return GameMap(
|
||||
width=MAP_W, height=MAP_H, tiles=tiles, rooms=rooms,
|
||||
explored=explored, visible=visible, entities=[],
|
||||
stairs_down=stairs_down, floor_index=floor_index,
|
||||
)
|
||||
|
||||
|
||||
def is_wall(gmap: GameMap, x: int, y: int) -> bool:
|
||||
if x < 0 or y < 0 or x >= gmap.width or y >= gmap.height:
|
||||
return True
|
||||
return gmap.tiles[y][x] == 0
|
||||
|
||||
|
||||
def walkable(gmap: GameMap, x: int, y: int) -> bool:
|
||||
if x < 0 or y < 0 or x >= gmap.width or y >= gmap.height:
|
||||
return False
|
||||
return gmap.tiles[y][x] == 1
|
||||
@@ -1,95 +0,0 @@
|
||||
"""Grid A* with Manhattan heuristic.
|
||||
|
||||
4-connected movement (matches the plan's one-tile enemy steps and the
|
||||
Manhattan distance heuristic). Returns the full path start..goal inclusive.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
from typing import Any
|
||||
|
||||
from engine.map_gen import GameMap
|
||||
|
||||
|
||||
def _heuristic(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _walkable(gmap: GameMap, x: int, y: int, blocked: set[tuple[int, int]] | None) -> bool:
|
||||
if x < 0 or y < 0 or x >= gmap.width or y >= gmap.height:
|
||||
return False
|
||||
if gmap.tiles[y][x] != 1:
|
||||
return False
|
||||
if blocked is not None and (x, y) in blocked:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def astar(
|
||||
gmap: Any,
|
||||
start: tuple[int, int],
|
||||
goal: tuple[int, int],
|
||||
blocked: set[tuple[int, int]] | None = None,
|
||||
) -> list[tuple[int, int]] | None:
|
||||
if not _walkable(gmap, start[0], start[1], blocked) or not _walkable(gmap, goal[0], goal[1], blocked):
|
||||
return None
|
||||
|
||||
if start == goal:
|
||||
return [start]
|
||||
|
||||
# (f, tie_breaker, node)
|
||||
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
||||
counter = 0
|
||||
heapq.heappush(open_heap, (_heuristic(start, goal), counter, start))
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
||||
|
||||
neighbors = ((0, -1), (0, 1), (-1, 0), (1, 0))
|
||||
|
||||
while open_heap:
|
||||
_, _, current = heapq.heappop(open_heap)
|
||||
if current == goal:
|
||||
path = [current]
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append(current)
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
cx, cy = current
|
||||
step = g_score[current] + 1
|
||||
for dx, dy in neighbors:
|
||||
nxt = (cx + dx, cy + dy)
|
||||
if nxt in g_score and step >= g_score[nxt]:
|
||||
continue
|
||||
if not _walkable(gmap, nxt[0], nxt[1], blocked):
|
||||
continue
|
||||
g_score[nxt] = step
|
||||
f = step + _heuristic(nxt, goal)
|
||||
counter += 1
|
||||
heapq.heappush(open_heap, (f, counter, nxt))
|
||||
came_from[nxt] = current
|
||||
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from random import Random
|
||||
from engine.map_gen import generate_dungeon
|
||||
|
||||
rng = Random(0)
|
||||
failures = 0
|
||||
for floor in range(9):
|
||||
m = generate_dungeon(floor, rng)
|
||||
floors = [(x, y) for y in range(m.height) for x in range(m.width) if m.tiles[y][x] == 1]
|
||||
a, b = floors[0], floors[-1]
|
||||
p = astar(m, a, b)
|
||||
if p is None or p[0] != a or p[-1] != b:
|
||||
failures += 1
|
||||
print(f"floor {floor}: FAIL a={a} b={b} p={p}")
|
||||
# blocked corner case: wall off goal
|
||||
flat = GameMap(5, 1, [[1, 1, 0, 1, 1]], [], [], [], [], None, 0)
|
||||
assert astar(flat, (0, 0), (4, 0)) is None, "wall should block"
|
||||
assert astar(flat, (0, 0), (1, 0)) == [(0, 0), (1, 0)]
|
||||
print(f"astar ok ({failures} connectivity failures)")
|
||||
@@ -1,156 +0,0 @@
|
||||
"""JSON save/load for a GameSession.
|
||||
|
||||
Serialization is lossless and invertible: dict_to_session(session_to_dict(s))
|
||||
rebuilds a session whose session_to_dict is byte-identical, which is what the
|
||||
round-trip gate asserts. Tuples (colors, positions, stairs) are normalized to
|
||||
JSON lists on the way out and back to tuples on the way in, so sess and its
|
||||
loaded copy serialize identically. The per-turn visible grid is NEVER serialized
|
||||
-- it is recomputed from FOV on load.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from engine.game_state import GameSession
|
||||
from engine.map_gen import GameMap, Rect
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Player
|
||||
|
||||
|
||||
def _item_to_dict(it: Item) -> dict:
|
||||
return {
|
||||
"type": "item",
|
||||
"x": it.x, "y": it.y, "name": it.name, "color": list(it.color),
|
||||
"kind": it.kind, "sub": it.sub, "power": it.power, "armor": it.armor,
|
||||
"evasion_delta": it.evasion_delta, "crit_delta": it.crit_delta,
|
||||
"heal": it.heal, "duration": it.duration, "radius": it.radius,
|
||||
"damage": it.damage, "value": it.value,
|
||||
}
|
||||
|
||||
|
||||
def _enemy_to_dict(e: Enemy) -> dict:
|
||||
return {
|
||||
"type": "enemy",
|
||||
"x": e.x, "y": e.y, "name": e.name, "color": list(e.color),
|
||||
"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,
|
||||
"ranged_power": e.ranged_power,
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
def _entity_to_dict(e: object) -> dict | None:
|
||||
if isinstance(e, Enemy):
|
||||
return _enemy_to_dict(e)
|
||||
if isinstance(e, Item):
|
||||
return _item_to_dict(e)
|
||||
return None
|
||||
|
||||
|
||||
def _item_from_dict(d: dict) -> Item:
|
||||
fields = dict(d)
|
||||
fields.pop("type", None)
|
||||
fields["color"] = tuple(fields["color"])
|
||||
return Item(**fields)
|
||||
|
||||
|
||||
def _enemy_from_dict(d: dict) -> Enemy:
|
||||
fields = dict(d)
|
||||
fields.pop("type", None)
|
||||
fields["color"] = tuple(fields["color"])
|
||||
lkp = fields["last_known_pos"]
|
||||
fields["last_known_pos"] = tuple(lkp) if lkp is not None else None
|
||||
return Enemy(**fields)
|
||||
|
||||
|
||||
def _entity_from_dict(d: dict) -> object:
|
||||
if d["type"] == "enemy":
|
||||
return _enemy_from_dict(d)
|
||||
return _item_from_dict(d)
|
||||
|
||||
|
||||
def _player_to_dict(p: Player) -> dict:
|
||||
return {
|
||||
"name": p.name, "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,
|
||||
"timers": dict(p.timers),
|
||||
"inventory": [_item_to_dict(i) for i in p.inventory],
|
||||
"weapon": _item_to_dict(p.weapon) if p.weapon is not None else None,
|
||||
"armor_item": _item_to_dict(p.armor_item) if p.armor_item is not None else None,
|
||||
}
|
||||
|
||||
|
||||
def _player_from_dict(d: dict) -> Player:
|
||||
return Player(
|
||||
name=d["name"], x=d["x"], y=d["y"],
|
||||
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"], level=d["level"], xp=d["xp"],
|
||||
timers=dict(d["timers"]),
|
||||
inventory=[_item_from_dict(i) for i in d["inventory"]],
|
||||
weapon=_entity_from_dict(d["weapon"]) if d["weapon"] is not None else None,
|
||||
armor_item=_entity_from_dict(d["armor_item"]) if d["armor_item"] is not None else None,
|
||||
)
|
||||
|
||||
|
||||
def _map_to_dict(gmap: GameMap) -> dict:
|
||||
return {
|
||||
"width": gmap.width, "height": gmap.height,
|
||||
"tiles": gmap.tiles,
|
||||
"rooms": [[r.x, r.y, r.w, r.h] for r in gmap.rooms],
|
||||
"explored": gmap.explored,
|
||||
"entities": [d for d in (_entity_to_dict(e) for e in gmap.entities) if d is not None],
|
||||
"stairs_down": list(gmap.stairs_down) if gmap.stairs_down is not None else None,
|
||||
"floor_index": gmap.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _map_from_dict(d: dict) -> GameMap:
|
||||
rooms = [Rect(r[0], r[1], r[2], r[3]) for r in d["rooms"]]
|
||||
entities = [_entity_from_dict(e) for e in d["entities"]]
|
||||
width, height = d["width"], d["height"]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
stairs = tuple(d["stairs_down"]) if d["stairs_down"] is not None else None
|
||||
return GameMap(
|
||||
width=width, height=height, tiles=d["tiles"], rooms=rooms,
|
||||
explored=d["explored"], visible=visible, entities=entities,
|
||||
stairs_down=stairs, floor_index=d["floor_index"],
|
||||
)
|
||||
|
||||
|
||||
def session_to_dict(sess: GameSession) -> dict:
|
||||
return {
|
||||
"player": _player_to_dict(sess.player),
|
||||
"dungeon": [_map_to_dict(m) for m in sess.dungeon],
|
||||
"current_floor": sess.current_floor,
|
||||
"log": list(sess.log),
|
||||
"turn": sess.turn,
|
||||
"state": sess.state,
|
||||
}
|
||||
|
||||
|
||||
def dict_to_session(d: dict) -> GameSession:
|
||||
return GameSession(
|
||||
player=_player_from_dict(d["player"]),
|
||||
dungeon=[_map_from_dict(m) for m in d["dungeon"]],
|
||||
current_floor=d["current_floor"],
|
||||
log=list(d["log"]),
|
||||
turn=d["turn"],
|
||||
state=d["state"],
|
||||
)
|
||||
|
||||
|
||||
def save_session(sess: GameSession, path: str) -> None:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(session_to_dict(sess), f)
|
||||
|
||||
|
||||
def load_session(path: str) -> GameSession:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return dict_to_session(json.load(f))
|
||||
Reference in new issue
Block a user