"""JSON-safe serialization of GameSession for save/load. The volatile `visible` grid is deliberately excluded from the saved form: it is recomputed from FOV on load, so persisting it would only bloat the save and risk a stale view. Everything else that survives across a save/quit/relaunch is kept. Tuples are preserved as tuples (not flattened to lists) so a to_dict -> from_dict -> to_dict cycle is byte-stable under Python dict equality. """ from __future__ import annotations from dataclasses import fields from typing import Any from entities.player import Player from entities.enemy import Enemy from entities.item import Item from engine.map_gen import GameMap, Rect from engine.game_state import GameSession # Discriminators for the polymorphic entity list + room rects. _DCTAGS: dict[type, str] = {Player: "player", Enemy: "enemy", Item: "item", Rect: "rect"} def _to_json(v: Any) -> Any: """Recursively coerce a value to a JSON-safe structure, preserving tuples.""" if v is None or isinstance(v, (bool, int, float, str)): return v if isinstance(v, tuple): return tuple(_to_json(x) for x in v) if isinstance(v, list): return [_to_json(x) for x in v] if isinstance(v, dict): return {str(k): _to_json(val) for k, val in v.items()} tag = _DCTAGS.get(type(v)) if tag is not None: out: dict[str, Any] = {"__type__": tag} for f in fields(v): out[f.name] = _to_json(getattr(v, f.name)) return out raise TypeError(f"not JSON-serializable: {type(v).__name__}") def _make_dc(cls: type, d: dict) -> Any: kwargs = {f.name: _from_json(d[f.name]) for f in fields(cls) if f.name in d} return cls(**kwargs) def _from_json(v: Any) -> Any: """Inverse of _to_json: rebuild dataclass instances from tagged dicts.""" if v is None or isinstance(v, (bool, int, float, str)): return v if isinstance(v, tuple): return tuple(_from_json(x) for x in v) if isinstance(v, list): return [_from_json(x) for x in v] if isinstance(v, dict): tag = v.get("__type__") if tag == "player": return _make_dc(Player, v) if tag == "enemy": return _make_dc(Enemy, v) if tag == "item": return _make_dc(Item, v) if tag == "rect": return Rect(v["x"], v["y"], v["w"], v["h"]) return {k: _from_json(val) for k, val in v.items()} raise TypeError(f"cannot decode: {type(v).__name__}") def _floor_to_dict(gm: GameMap) -> dict: # `visible` is intentionally absent: recomputed from FOV on load. return { "width": gm.width, "height": gm.height, "tiles": gm.tiles, "rooms": [_to_json(r) for r in gm.rooms], "explored": gm.explored, "entities": [_to_json(e) for e in gm.entities], "stairs_down": gm.stairs_down, "spawn": gm.spawn, "floor_index": gm.floor_index, } def _floor_from_dict(d: dict) -> GameMap: width, height = d["width"], d["height"] visible = [[False] * width for _ in range(height)] stairs = d["stairs_down"] spawn = d["spawn"] return GameMap( width=width, height=height, tiles=d["tiles"], rooms=[_from_json(r) for r in d["rooms"]], explored=d["explored"], visible=visible, entities=[_from_json(e) for e in d["entities"]], stairs_down=tuple(stairs) if stairs is not None else None, spawn=tuple(spawn) if spawn is not None else None, floor_index=d["floor_index"], ) def session_to_dict(session: GameSession) -> dict: return { "player": _to_json(session.player), "dungeon": [_floor_to_dict(gm) for gm in session.dungeon], "current_floor": session.current_floor, "turn": session.turn, "log": list(session.log), "state": session.state, } def session_from_dict(d: dict) -> GameSession: return GameSession( player=_from_json(d["player"]), dungeon=[_floor_from_dict(fd) for fd in d["dungeon"]], current_floor=d["current_floor"], turn=d["turn"], log=list(d["log"]), state=d["state"], )