194 lines
6.7 KiB
Python
194 lines
6.7 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import random
|
|
from array import array
|
|
from dataclasses import fields
|
|
from pathlib import Path
|
|
|
|
from data.constants import SAVE_FILENAME
|
|
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 Player
|
|
from engine.game_state import GameSession
|
|
|
|
SAVE_PATH = Path(__file__).resolve().parents[1] / SAVE_FILENAME
|
|
|
|
_TUPLE_FIELDS = {"last_known_position", "stairs_down", "spawn", "position"}
|
|
|
|
|
|
_ITEM_FIELDS = {"inventory", "equipped_weapon", "equipped_armor"}
|
|
|
|
|
|
def _entity_to_dict(entity: Entity) -> dict:
|
|
result = {f.name: getattr(entity, f.name) for f in fields(entity)}
|
|
for name in _ITEM_FIELDS & result.keys():
|
|
value = result[name]
|
|
if isinstance(value, list):
|
|
result[name] = [_entity_to_dict(i) for i in value]
|
|
elif value is not None:
|
|
result[name] = _entity_to_dict(value)
|
|
return {"kind": type(entity).__name__, **result}
|
|
|
|
|
|
def _entity_from_dict(data: dict) -> Entity:
|
|
cls = {"Player": Player, "Enemy": Enemy, "Item": Item}[data["kind"]]
|
|
kwargs = {k: v for k, v in data.items() if k != "kind"}
|
|
for name in _TUPLE_FIELDS & kwargs.keys():
|
|
if kwargs[name] is not None:
|
|
kwargs[name] = tuple(kwargs[name])
|
|
for name in _ITEM_FIELDS & kwargs.keys():
|
|
value = kwargs[name]
|
|
if isinstance(value, list):
|
|
kwargs[name] = [_entity_from_dict(i) for i in value]
|
|
elif value is not None:
|
|
kwargs[name] = _entity_from_dict(value)
|
|
return cls(**kwargs)
|
|
|
|
def _floor_to_dict(game_map: GameMap) -> dict:
|
|
return {
|
|
"width": game_map.width,
|
|
"height": game_map.height,
|
|
"tiles": [list(row) for row in game_map.tiles],
|
|
"explored": [list(row) for row in game_map.explored],
|
|
"rooms": [[r.x, r.y, r.width, r.height] for r in game_map.rooms],
|
|
"entities": [_entity_to_dict(e) for e in game_map.entities],
|
|
"stairs_down": list(game_map.stairs_down) if game_map.stairs_down else None,
|
|
"floor_index": game_map.floor_index,
|
|
"spawn": list(game_map.spawn),
|
|
}
|
|
|
|
|
|
def _floor_from_dict(data: dict) -> GameMap:
|
|
return GameMap(
|
|
width=data["width"],
|
|
height=data["height"],
|
|
tiles=[array("b", row) for row in data["tiles"]],
|
|
explored=[array("b", row) for row in data["explored"]],
|
|
rooms=[Rect(x, y, w, h) for x, y, w, h in data["rooms"]],
|
|
entities=[_entity_from_dict(e) for e in data["entities"]],
|
|
visible=[array("b", [0]) * data["width"] for _ in range(data["height"])],
|
|
stairs_down=tuple(data["stairs_down"]) if data["stairs_down"] else None,
|
|
floor_index=data["floor_index"],
|
|
spawn=tuple(data["spawn"]),
|
|
)
|
|
|
|
|
|
def _rng_state_to_list(state: tuple) -> list:
|
|
version, key, gauss = state
|
|
return [version, list(key), gauss]
|
|
|
|
|
|
def _rng_state_from_list(data: list) -> tuple:
|
|
version, key, gauss = data
|
|
return (version, tuple(key), gauss)
|
|
|
|
|
|
def session_to_dict(session: GameSession) -> dict:
|
|
return {
|
|
"player": _entity_to_dict(session.player),
|
|
"dungeon": [_floor_to_dict(m) for m in session.dungeon],
|
|
"current_floor": session.current_floor,
|
|
"log": list(session.log),
|
|
"turn": session.turn,
|
|
"state": session.state,
|
|
"rng": _rng_state_to_list(session.rng.getstate()),
|
|
}
|
|
|
|
|
|
def session_from_dict(data: dict) -> GameSession:
|
|
session = GameSession(
|
|
player=_entity_from_dict(data["player"]),
|
|
dungeon=[_floor_from_dict(m) for m in data["dungeon"]],
|
|
current_floor=data["current_floor"],
|
|
log=list(data["log"]),
|
|
turn=data["turn"],
|
|
state=data["state"],
|
|
rng=random.Random(),
|
|
)
|
|
session.rng.setstate(_rng_state_from_list(data["rng"]))
|
|
session.update_fov()
|
|
return session
|
|
|
|
|
|
def save_game(session: GameSession, path: Path | None = None) -> None:
|
|
path = SAVE_PATH if path is None else path
|
|
path.write_text(json.dumps(session_to_dict(session)))
|
|
|
|
|
|
def load_game(path: Path | None = None) -> GameSession:
|
|
path = SAVE_PATH if path is None else path
|
|
return session_from_dict(json.loads(path.read_text()))
|
|
|
|
|
|
def has_save(path: Path | None = None) -> bool:
|
|
path = SAVE_PATH if path is None else path
|
|
return path.is_file()
|
|
|
|
|
|
def delete_save(path: Path | None = None) -> None:
|
|
path = SAVE_PATH if path is None else path
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
def _assert_sessions_equal(a: GameSession, b: GameSession) -> None:
|
|
assert a.turn == b.turn and a.current_floor == b.current_floor and a.state == b.state
|
|
assert a.log == b.log
|
|
pa, pb = a.player, b.player
|
|
for f in fields(Player):
|
|
assert getattr(pa, f.name) == getattr(pb, f.name), f"player.{f.name}"
|
|
assert pa.equipped_weapon == pb.equipped_weapon and pa.equipped_armor == pb.equipped_armor
|
|
for fa, fb in zip(a.dungeon, b.dungeon):
|
|
assert fa.tiles == fb.tiles and fa.explored == fb.explored
|
|
assert fa.stairs_down == fb.stairs_down and fa.spawn == fb.spawn
|
|
for ea, eb in zip(fa.entities, fb.entities):
|
|
assert type(ea) is type(eb)
|
|
for f in fields(ea):
|
|
assert getattr(ea, f.name) == getattr(eb, f.name), f"{ea}.{f.name}"
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import tempfile
|
|
|
|
from data.items import ITEM_CATALOG
|
|
from data.enemies import make_enemy
|
|
|
|
session = GameSession.new_game(seed=42)
|
|
session.player.hp = 33
|
|
session.player.xp = 27
|
|
axe = Item.from_def(ITEM_CATALOG["battle_axe"])
|
|
session.player.inventory.append(axe)
|
|
session.equip(axe)
|
|
session.player.strength_turns = 12
|
|
session.player.invisible_turns = 3
|
|
session.player_move_or_attack(1, 0)
|
|
session.current_map.entities.append(make_enemy("green_slime", 5, 5))
|
|
session.current_map.entities[0].last_known_position = (7, 9)
|
|
session.current_map.entities[0].hp -= 3
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = Path(tmp) / "save.json"
|
|
save_game(session, path)
|
|
assert has_save(path)
|
|
loaded = load_game(path)
|
|
_assert_sessions_equal(session, loaded)
|
|
|
|
loaded.current_map.entities.remove(loaded.current_map.entities[-1])
|
|
delete_save(path)
|
|
assert not has_save(path)
|
|
delete_save(path) # idempotent
|
|
|
|
# RNG continuity: identical inputs after load produce identical outcomes.
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
a = GameSession.new_game(seed=7)
|
|
save_game(a, Path(tmp) / "s.json")
|
|
b = load_game(Path(tmp) / "s.json")
|
|
for _ in range(20):
|
|
a.player_move_or_attack(1, 0)
|
|
b.player_move_or_attack(1, 0)
|
|
assert a.player.hp == b.player.hp and a.player.position == b.player.position
|
|
assert a.turn == b.turn == 20
|
|
print("serializers self-check: PASS")
|