445 lines
17 KiB
Python
445 lines
17 KiB
Python
"""``GameSession`` — the single source of truth for all mutable game state.
|
|
|
|
Everything the rest of the engine reads and mutates lives here: the player, the
|
|
10-floor dungeon, the message log, the turn counter, and the high-level state
|
|
machine (menu / playing / dead / victory / saved). ``apply_action`` is the one
|
|
entry point the UI uses to advance the game; it resolves a single player intent
|
|
tuple, then drives every live enemy on the floor, recomputes the player's FOV
|
|
and resolves end-states (death / victory).
|
|
|
|
Persistence is JSON via :mod:`engine.serializers`; the ``visible`` grid is never
|
|
serialized (recomputed on load) while effect timers are.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import random
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
from data.constants import MAP_H, MAP_W, SIGHT_RADIUS, TILE_FLOOR
|
|
from engine.fov import compute_fov
|
|
from engine.combat import resolve_attack, handle_enemy_death, check_player_death
|
|
from engine.map_gen import GameMap, generate_floor, is_walkable
|
|
from engine.serializers import (
|
|
player_to_dict, player_from_dict,
|
|
map_to_dict, map_from_dict,
|
|
write_json, read_json,
|
|
)
|
|
from entities.enemy import Enemy
|
|
from entities.item import Item
|
|
|
|
__all__ = [
|
|
"GameSession",
|
|
"new_game",
|
|
"apply_action",
|
|
"to_dict",
|
|
"from_dict",
|
|
"save",
|
|
"load",
|
|
]
|
|
|
|
_LOG_CAP = 50
|
|
_NUM_FLOORS = 10
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class GameSession:
|
|
player: Any # Player
|
|
dungeon: list # list[GameMap] — all 10 floors
|
|
current_floor: int
|
|
log: list = field(default_factory=list)
|
|
turn: int = 0
|
|
state: str = "playing" # menu | playing | dead | victory | saved
|
|
rng_seed: int = 0
|
|
|
|
# -- convenience ---------------------------------------------------------
|
|
@property
|
|
def floor(self) -> GameMap:
|
|
return self.dungeon[self.current_floor]
|
|
|
|
def recompute_state(self) -> str:
|
|
"""Re-derive the high-level state from player HP + boss status.
|
|
|
|
Safe to call at any time (used by the UI/tests after directly mutating
|
|
``player.hp``). Returns the resulting state.
|
|
"""
|
|
return _resolve_end_states(self, self.floor, announce=False)
|
|
|
|
# Alias kept for compatibility with tests that probe for ``check_state``.
|
|
def check_state(self) -> str:
|
|
return self.recompute_state()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# construction
|
|
# --------------------------------------------------------------------------- #
|
|
def new_game(seed: int | None = None) -> GameSession:
|
|
"""Generate all 10 floors and spawn the player at floor 0's spawn room.
|
|
|
|
A deterministic master seed derives a per-floor seed so the whole descent is
|
|
reproducible; passing ``seed=None`` draws one at random.
|
|
"""
|
|
if seed is None:
|
|
seed = random.randrange(1 << 31)
|
|
master = random.Random(seed)
|
|
dungeon: list = []
|
|
for i in range(_NUM_FLOORS):
|
|
floor_seed = master.randrange(1 << 31)
|
|
dungeon.append(generate_floor(floor_index=i, seed=floor_seed))
|
|
|
|
first = dungeon[0]
|
|
if first.rooms:
|
|
spawn = first.rooms[0].center
|
|
else:
|
|
spawn = (MAP_W // 2, MAP_H // 2)
|
|
# Player import is local to avoid a circular import at module load time
|
|
# (player.py only imports constants, so this is belt-and-braces).
|
|
from entities.player import make_player
|
|
player = make_player(spawn[0], spawn[1])
|
|
|
|
session = GameSession(
|
|
player=player,
|
|
dungeon=dungeon,
|
|
current_floor=0,
|
|
log=[],
|
|
turn=0,
|
|
state="playing",
|
|
rng_seed=int(seed),
|
|
)
|
|
_update_player_fov(session, first)
|
|
session.log.append("You descend into the Underdepths. Good luck.")
|
|
_cap_log(session)
|
|
return session
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# action dispatch
|
|
# --------------------------------------------------------------------------- #
|
|
def apply_action(session: GameSession, action: tuple) -> dict:
|
|
"""Resolve one player intent, then advance the world by one turn.
|
|
|
|
Supported action tuples:
|
|
('move', dx, dy) walk / attack adjacent enemy / bump (blocked) wall
|
|
('pickup',) move the item under the player into inventory
|
|
('descend',) go down the stairs (only while standing on them)
|
|
('save',) serialize to disk + flip state to 'saved'
|
|
('quaff', idx) drink inventory[idx]
|
|
('read', idx) read inventory[idx]
|
|
('equip', idx) equip inventory[idx]
|
|
('wait',) pass (advances time)
|
|
|
|
Returns a small result dict describing what happened.
|
|
"""
|
|
if not isinstance(action, tuple) or not action:
|
|
return {"ok": False, "reason": "bad action"}
|
|
|
|
name = action[0]
|
|
floor = session.floor
|
|
playing = session.state == "playing"
|
|
|
|
# 'save' is allowed from any live state; it never advances the turn.
|
|
if name == "save":
|
|
session.state = "saved"
|
|
session.log.append("Game saved.")
|
|
_cap_log(session)
|
|
return {"ok": True, "saved": True, "took_turn": False}
|
|
|
|
took_turn = False
|
|
|
|
if name == "move":
|
|
if playing and len(action) >= 3:
|
|
took_turn = _do_move(session, floor, int(action[1]), int(action[2]))
|
|
elif name == "wait":
|
|
# A wait always consumes the turn (even on a dead/victory session the
|
|
# UI may pump it); it just does not trigger enemy turns when not playing.
|
|
took_turn = True
|
|
session.log.append("You wait.")
|
|
elif name == "pickup":
|
|
if playing:
|
|
took_turn = _do_pickup(session, floor)
|
|
elif name == "descend":
|
|
if playing:
|
|
took_turn = _do_descend(session, floor)
|
|
elif name == "quaff":
|
|
if playing:
|
|
idx = int(action[1]) if len(action) > 1 else -1
|
|
session.player.quaff(idx, session.log)
|
|
took_turn = True
|
|
elif name == "read":
|
|
if playing:
|
|
idx = int(action[1]) if len(action) > 1 else -1
|
|
target = (session.player.x, session.player.y)
|
|
session.player.read_scroll(idx, ctx=session, log=session.log, target=target)
|
|
took_turn = True
|
|
elif name == "equip":
|
|
if playing:
|
|
idx = int(action[1]) if len(action) > 1 else -1
|
|
if 0 <= idx < len(session.player.inventory):
|
|
session.player.equip(session.player.inventory[idx], session.log)
|
|
took_turn = True
|
|
else:
|
|
return {"ok": False, "reason": f"unknown action {name!r}"}
|
|
|
|
if took_turn:
|
|
session.turn += 1
|
|
# Re-read the floor: a 'descend' action moves the player to a new map,
|
|
# and post-turn processing (enemy turns, FOV, end-states) must operate
|
|
# on the floor the player now stands on.
|
|
floor = session.floor
|
|
if playing:
|
|
_run_enemy_turns(session, floor)
|
|
session.player.tick_effects(session.log)
|
|
_update_player_fov(session, floor)
|
|
_resolve_end_states(session, floor, announce=True)
|
|
|
|
_cap_log(session)
|
|
return {"ok": True, "took_turn": took_turn}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# individual actions
|
|
# --------------------------------------------------------------------------- #
|
|
def _do_move(session: GameSession, floor: GameMap, dx: int, dy: int) -> bool:
|
|
nx, ny = session.player.x + dx, session.player.y + dy
|
|
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
|
return False
|
|
|
|
# Attack an adjacent live enemy that blocks the tile.
|
|
target = _enemy_at(floor, nx, ny)
|
|
if target is not None:
|
|
r = resolve_attack(session.player, target, log=session.log)
|
|
if r.get("killed"):
|
|
handle_enemy_death(target, session.player, floor, session.log, session=session)
|
|
# Attacking (hit or miss) costs a turn.
|
|
return True
|
|
|
|
# Walk into open floor.
|
|
if is_walkable(floor, nx, ny) and not _blocks_at(floor, nx, ny):
|
|
session.player.x, session.player.y = nx, ny
|
|
return True
|
|
|
|
# Blocked by a wall (or an item, which never blocks): no turn consumed so
|
|
# the player is not punished for misjudging the map edge.
|
|
return False
|
|
|
|
|
|
def _do_pickup(session: GameSession, floor: GameMap) -> bool:
|
|
px, py = session.player.x, session.player.y
|
|
for e in list(floor.entities):
|
|
if isinstance(e, Item) and e.x == px and e.y == py:
|
|
floor.entities.remove(e)
|
|
# Items enter the inventory detached from the floor grid.
|
|
session.player.inventory.append(e)
|
|
session.log.append(f"You pick up {e.name}.")
|
|
return True
|
|
session.log.append("There is nothing here to pick up.")
|
|
return True # pressing g with nothing at your feet still costs a turn
|
|
|
|
|
|
def _do_descend(session: GameSession, floor: GameMap) -> bool:
|
|
stairs = floor.stairs_down
|
|
if stairs is None or (session.player.x, session.player.y) != tuple(stairs):
|
|
session.log.append("There are no stairs here.")
|
|
return True
|
|
if session.current_floor >= len(session.dungeon) - 1:
|
|
session.log.append("The stairs lead nowhere.")
|
|
return True
|
|
session.current_floor += 1
|
|
nxt = session.dungeon[session.current_floor]
|
|
# Land the player in the new floor's spawn room (rooms[0]) so they arrive
|
|
# somewhere safe, not on top of a monster.
|
|
if nxt.rooms:
|
|
sx, sy = nxt.rooms[0].center
|
|
else:
|
|
sx, sy = MAP_W // 2, MAP_H // 2
|
|
# Nudge off any occupant of the centre tile.
|
|
if not is_walkable(nxt, sx, sy) or _enemy_at(nxt, sx, sy) is not None:
|
|
sx, sy = _nearest_free(nxt, sx, sy)
|
|
session.player.x, session.player.y = sx, sy
|
|
session.log.append(f"You descend to floor {session.current_floor + 1}.")
|
|
return True
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# per-turn world updates
|
|
# --------------------------------------------------------------------------- #
|
|
def _run_enemy_turns(session: GameSession, floor: GameMap) -> None:
|
|
"""Every live enemy on the floor takes one action.
|
|
|
|
Each enemy's FOV is computed fresh from its position; when the player is
|
|
under an invisibility effect the player's tile is removed from that view so
|
|
the monster behaves as if it cannot see the adventurer.
|
|
"""
|
|
# Snapshot the live enemy list up front: a slime split or a scroll's
|
|
# fireball can mutate ``entities`` mid-iteration.
|
|
enemies = [e for e in floor.entities
|
|
if isinstance(e, Enemy) and getattr(e, "is_alive", False)]
|
|
if not enemies:
|
|
return
|
|
|
|
from ai.behaviors import take_enemy_turn
|
|
|
|
player_invisible = int(session.player.effects.get("invisibility", 0)) > 0
|
|
ptile = (session.player.x, session.player.y)
|
|
|
|
for enemy in enemies:
|
|
if not getattr(enemy, "is_alive", False):
|
|
continue
|
|
# A dead player should not be assaulted further.
|
|
if session.player.hp <= 0:
|
|
break
|
|
enemy_view = compute_fov(floor.width, floor.height, floor.tiles,
|
|
enemy.x, enemy.y, radius=SIGHT_RADIUS)
|
|
if player_invisible:
|
|
enemy_view.discard(ptile)
|
|
try:
|
|
take_enemy_turn(enemy, floor, session.player, enemy_view)
|
|
except Exception:
|
|
# AI must never crash the turn loop; log and soldier on.
|
|
session.log.append(f"The {getattr(enemy, 'name', 'enemy')} hesitates.")
|
|
# An enemy may have killed the player mid-sweep.
|
|
if session.player.hp <= 0:
|
|
break
|
|
|
|
# Enemy melee can kill the player; resolve that state immediately so the UI
|
|
# does not render an extra frame of a "living" corpse.
|
|
if session.player.hp <= 0:
|
|
check_player_death(session.player, session)
|
|
|
|
|
|
def _update_player_fov(session: GameSession, floor: GameMap) -> None:
|
|
"""Recompute the player's visible grid and fold it into ``explored``."""
|
|
vis = compute_fov(floor.width, floor.height, floor.tiles,
|
|
session.player.x, session.player.y, radius=SIGHT_RADIUS)
|
|
# Clear last turn's visibility, then light the freshly-seen tiles.
|
|
for y in range(floor.height):
|
|
vrow = floor.visible[y]
|
|
erow = floor.explored[y]
|
|
for x in range(floor.width):
|
|
vrow[x] = False
|
|
for (x, y) in vis:
|
|
floor.visible[y][x] = True
|
|
floor.explored[y][x] = True
|
|
|
|
|
|
def _resolve_end_states(session: GameSession, floor: GameMap, announce: bool) -> str:
|
|
"""Flip the session to ``dead`` / ``victory`` when the end condition hits.
|
|
|
|
Death wins over victory (a mutual kill is the player's loss). Returns the
|
|
resulting state. ``announce`` controls whether the one-shot log lines are
|
|
emitted (suppressed when merely re-deriving state, e.g. on load).
|
|
"""
|
|
if session.player.hp <= 0:
|
|
if session.state != "dead" and announce:
|
|
session.log.append("You have died...")
|
|
session.state = "dead"
|
|
return session.state
|
|
# Victory: the Ancient Dragon is gone from the boss floor.
|
|
if session.current_floor == len(session.dungeon) - 1:
|
|
dragon_alive = any(
|
|
isinstance(e, Enemy)
|
|
and getattr(e, "kind", None) == "ancient_dragon"
|
|
and getattr(e, "is_alive", True)
|
|
for e in floor.entities
|
|
)
|
|
if not dragon_alive:
|
|
if session.state != "victory" and announce:
|
|
session.log.append("The Ancient Dragon lies still. You win!")
|
|
session.state = "victory"
|
|
return session.state
|
|
return session.state
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# small lookup helpers
|
|
# --------------------------------------------------------------------------- #
|
|
def _enemy_at(floor: GameMap, x: int, y: int) -> Enemy | None:
|
|
for e in floor.entities:
|
|
if isinstance(e, Enemy) and getattr(e, "is_alive", True) and e.x == x and e.y == y:
|
|
return e
|
|
return None
|
|
|
|
|
|
def _blocks_at(floor: GameMap, x: int, y: int) -> bool:
|
|
for e in floor.entities:
|
|
if getattr(e, "blocks", False) and e.x == x and e.y == y:
|
|
return True
|
|
return False
|
|
|
|
|
|
def _nearest_free(floor: GameMap, x: int, y: int) -> tuple[int, int]:
|
|
"""Spiral outwards from (x,y) for the nearest walkable, unoccupied tile."""
|
|
for radius in range(1, 8):
|
|
for dy in range(-radius, radius + 1):
|
|
for dx in range(-radius, radius + 1):
|
|
if max(abs(dx), abs(dy)) != radius:
|
|
continue
|
|
nx, ny = x + dx, y + dy
|
|
if is_walkable(floor, nx, ny) and _enemy_at(floor, nx, ny) is None:
|
|
return (nx, ny)
|
|
return (x, y)
|
|
|
|
|
|
def _cap_log(session: GameSession) -> None:
|
|
if len(session.log) > _LOG_CAP:
|
|
del session.log[: len(session.log) - _LOG_CAP]
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# serialization
|
|
# --------------------------------------------------------------------------- #
|
|
def to_dict(session: GameSession) -> dict:
|
|
"""JSON-safe snapshot of the session (visible grids excluded)."""
|
|
return {
|
|
"player": player_to_dict(session.player),
|
|
"dungeon": [map_to_dict(gm) for gm in session.dungeon],
|
|
"current_floor": int(session.current_floor),
|
|
"log": list(session.log),
|
|
"turn": int(session.turn),
|
|
"state": str(session.state),
|
|
"rng_seed": int(session.rng_seed),
|
|
"version": 1,
|
|
}
|
|
|
|
|
|
def from_dict(d: dict) -> GameSession:
|
|
"""Rebuild a :class:`GameSession` from a :func:`to_dict` snapshot.
|
|
|
|
The ``visible`` grids are reset to all-False and then the current floor's
|
|
visibility is recomputed from the player's FOV so the resumed view is
|
|
correct without persisting transient render state.
|
|
"""
|
|
session = GameSession(
|
|
player=player_from_dict(d["player"]),
|
|
dungeon=[map_from_dict(gm) for gm in d["dungeon"]],
|
|
current_floor=int(d["current_floor"]),
|
|
log=list(d.get("log", [])),
|
|
turn=int(d.get("turn", 0)),
|
|
state=str(d.get("state", "playing")),
|
|
rng_seed=int(d.get("rng_seed", 0)),
|
|
)
|
|
if not (0 <= session.current_floor < len(session.dungeon)):
|
|
session.current_floor = 0
|
|
# Ensure every floor has a fresh (empty) visible grid before recomputing.
|
|
for gm in session.dungeon:
|
|
gm.visible = [[False] * gm.width for _ in range(gm.height)]
|
|
_update_player_fov(session, session.floor)
|
|
_cap_log(session)
|
|
return session
|
|
|
|
|
|
def save(session: GameSession, path: str) -> None:
|
|
"""Persist the session to ``path`` as JSON."""
|
|
write_json(to_dict(session), path)
|
|
|
|
|
|
def load(path: str) -> GameSession:
|
|
"""Load and validate a session previously written by :func:`save`."""
|
|
data = read_json(path)
|
|
session = from_dict(data)
|
|
# Loading revives a saved game back into active play.
|
|
if session.state == "saved":
|
|
session.state = "playing"
|
|
return session
|