feat(persistence): save/list/load games (PGN + JSON)
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from ai_chess.chess_game import ChessGame
|
||||
|
||||
|
||||
def save_game(games_dir: Path, game: ChessGame) -> None:
|
||||
games_dir = Path(games_dir)
|
||||
games_dir.mkdir(parents=True, exist_ok=True)
|
||||
(games_dir / f"{game.game_id}.pgn").write_text(game.to_pgn())
|
||||
meta = {
|
||||
"id": game.game_id,
|
||||
"started_at": game.started_at,
|
||||
"ended_at": game.ended_at,
|
||||
"result": game.result,
|
||||
"termination": game.termination,
|
||||
"agents": game.agents,
|
||||
"moves_count": len([h for h in game.history if h.uci not in ("resign", "agreement")]),
|
||||
}
|
||||
(games_dir / f"{game.game_id}.json").write_text(json.dumps(meta, indent=2))
|
||||
|
||||
|
||||
def list_games(games_dir: Path) -> list[dict[str, Any]]:
|
||||
games_dir = Path(games_dir)
|
||||
if not games_dir.exists():
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for p in games_dir.glob("*.json"):
|
||||
try:
|
||||
out.append(json.loads(p.read_text()))
|
||||
except Exception:
|
||||
continue
|
||||
out.sort(key=lambda g: g.get("id", ""), reverse=True)
|
||||
return out
|
||||
|
||||
|
||||
def load_game(games_dir: Path, game_id: str) -> dict[str, Any]:
|
||||
games_dir = Path(games_dir)
|
||||
meta = json.loads((games_dir / f"{game_id}.json").read_text())
|
||||
pgn = (games_dir / f"{game_id}.pgn").read_text()
|
||||
return {"meta": meta, "pgn": pgn}
|
||||
Reference in New Issue
Block a user