"""JSON serialization helpers for game entities, items and maps. These are thin, pure data <-> dict converters used by ``engine.game_state``. Everything produced is JSON-safe (tuples -> lists, sets -> lists); the inverse converters rebuild the typed dataclass instances. Persistence policy (per plan.md ยง8): * Player stats, level, XP, inventory, equipped items, position: persisted. * Dungeon: all 10 floors โ€” tiles, rooms, explored, entities, stairs, index. * Effects timers (strength / invisibility): persisted. * ``visible`` grid: NOT persisted โ€” recomputed from FOV on load. Reconstruction does not consult the item/enemy catalogs for stats: the saved dict is the source of truth, so a mid-run edit to an instance survives a round trip. ``color`` tuples are restored as tuples (rendering compares them). """ from __future__ import annotations import json from typing import Any from entities.entity import Rect from entities.player import Player from entities.enemy import Enemy from entities.item import Item from engine.map_gen import GameMap __all__ = [ "rect_to_dict", "rect_from_dict", "item_to_dict", "item_from_dict", "enemy_to_dict", "enemy_from_dict", "player_to_dict", "player_from_dict", "map_to_dict", "map_from_dict", "write_json", "read_json", ] def _tup(value) -> tuple | None: """Coerce a JSON-loaded list back into a tuple; pass None through.""" if value is None: return None return tuple(value) def rect_to_dict(r: Rect) -> dict: return {"x": r.x, "y": r.y, "w": r.w, "h": r.h} def rect_from_dict(d: dict) -> Rect: return Rect(x=int(d["x"]), y=int(d["y"]), w=int(d["w"]), h=int(d["h"])) def item_to_dict(it: Item | None) -> dict | None: if it is None: return None return { "name": it.name, "category": it.category, "x": it.x, "y": it.y, "stats": dict(it.stats or {}), "effect": dict(it.effect or {}), "glyph": it.glyph, "color": list(it.color), "blocks": bool(it.blocks), "is_alive": bool(it.is_alive), } def item_from_dict(d: dict | None) -> Item | None: if d is None: return None return Item( name=d["name"], category=d["category"], x=int(d["x"]), y=int(d["y"]), stats=dict(d.get("stats", {}) or {}), effect=dict(d.get("effect", {}) or {}), glyph=d.get("glyph", "?"), color=tuple(d.get("color", (200, 200, 200))), blocks=bool(d.get("blocks", False)), is_alive=bool(d.get("is_alive", True)), ) def enemy_to_dict(e: Enemy | None) -> dict | None: if e is None: return None return { "x": e.x, "y": e.y, "name": e.name, "glyph": e.glyph, "color": list(e.color), "kind": e.kind, "hp": e.hp, "max_hp": e.max_hp, "power": e.power, "armor": e.armor, "speed": e.speed, "behavior": e.behavior, "xp": e.xp, "is_alive": bool(e.is_alive), "last_known_pos": list(e.last_known_pos) if e.last_known_pos is not None else None, "ranged_power": int(e.ranged_power), "can_split": bool(e.can_split), "blocks": bool(e.blocks), } def enemy_from_dict(d: dict | None) -> Enemy | None: if d is None: return None return Enemy( x=int(d["x"]), y=int(d["y"]), name=d["name"], glyph=d["glyph"], color=tuple(d["color"]), kind=d["kind"], hp=int(d["hp"]), max_hp=int(d["max_hp"]), power=int(d["power"]), armor=int(d["armor"]), speed=int(d["speed"]), behavior=d["behavior"], xp=int(d["xp"]), is_alive=bool(d.get("is_alive", True)), last_known_pos=_tup(d.get("last_known_pos")), ranged_power=int(d.get("ranged_power", 0)), can_split=bool(d.get("can_split", False)), blocks=bool(d.get("blocks", True)), ) def player_to_dict(p: Player) -> dict: return { "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, "inventory": [item_to_dict(i) for i in p.inventory], "weapon": item_to_dict(p.weapon), "armor_item": item_to_dict(p.armor_item), "effects": {k: v for k, v in (p.effects or {}).items()}, "name": p.name, "glyph": p.glyph, "color": list(p.color), "blocks": bool(p.blocks), "is_alive": bool(p.is_alive), } def player_from_dict(d: dict) -> Player: return Player( x=int(d["x"]), y=int(d["y"]), hp=int(d["hp"]), max_hp=int(d["max_hp"]), power=int(d["power"]), armor=int(d["armor"]), accuracy=int(d["accuracy"]), evasion=int(d["evasion"]), crit_chance=float(d["crit_chance"]), speed=int(d["speed"]), level=int(d["level"]), xp=int(d["xp"]), inventory=[item_from_dict(i) for i in d.get("inventory", [])], weapon=item_from_dict(d.get("weapon")), armor_item=item_from_dict(d.get("armor_item")), effects={k: v for k, v in (d.get("effects", {}) or {}).items()}, name=d.get("name", "Adventurer"), glyph=d.get("glyph", "@"), color=tuple(d.get("color", (255, 255, 255))), blocks=bool(d.get("blocks", True)), is_alive=bool(d.get("is_alive", True)), ) def map_to_dict(gm: GameMap) -> dict: return { "width": gm.width, "height": gm.height, "tiles": [[int(v) for v in row] for row in gm.tiles], "rooms": [rect_to_dict(r) for r in gm.rooms], "explored": [[bool(v) for v in row] for row in gm.explored], # visible intentionally omitted โ€” recomputed on load. "entities": [ enemy_to_dict(e) if isinstance(e, Enemy) else item_to_dict(e) if isinstance(e, Item) else None for e in gm.entities ], "stairs_down": list(gm.stairs_down) if gm.stairs_down is not None else None, "floor_index": gm.floor_index, } def map_from_dict(d: dict) -> GameMap: width = int(d["width"]) height = int(d["height"]) entities: list = [] for e in d.get("entities", []): if e is None: continue kind = e.get("kind") if kind is not None: entities.append(enemy_from_dict(e)) else: entities.append(item_from_dict(e)) return GameMap( width=width, height=height, tiles=[[int(v) for v in row] for row in d["tiles"]], rooms=[rect_from_dict(r) for r in d.get("rooms", [])], explored=[[bool(v) for v in row] for row in d["explored"]], visible=[[False] * width for _ in range(height)], entities=entities, stairs_down=_tup(d.get("stairs_down")), floor_index=int(d.get("floor_index", 0)), ) def write_json(data: Any, path: str) -> None: """Atomically-ish JSON dump; errors propagate to the caller for handling.""" tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(data, f, separators=(",", ":")) import os os.replace(tmp, path) def read_json(path: str) -> Any: with open(path, "r", encoding="utf-8") as f: return json.load(f)