diff --git a/src/ai_chess/chess_game.py b/src/ai_chess/chess_game.py new file mode 100644 index 0000000..e8d0819 --- /dev/null +++ b/src/ai_chess/chess_game.py @@ -0,0 +1,287 @@ +from __future__ import annotations + +import io +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any + +import chess +import chess.pgn + +from ai_chess.sides import Side + + +@dataclass +class MoveResult: + ok: bool + reason: str | None = None + detail: str | None = None + san: str | None = None + uci: str | None = None + fen: str | None = None + ascii: str | None = None + history: list[dict[str, Any]] = field(default_factory=list) + status: dict[str, Any] = field(default_factory=dict) + illegal: bool = False # set when allow_illegal_moves applied an unsafe move + + def to_dict(self) -> dict[str, Any]: + return { + "ok": self.ok, + **({"reason": self.reason, "detail": self.detail} if not self.ok else {}), + **({"san": self.san, "uci": self.uci, "fen": self.fen, + "ascii": self.ascii, "history": self.history, + "status": self.status, + "illegal": self.illegal} if self.ok else {}), + } + + +@dataclass +class HistoryEntry: + ply: int + san: str | None + uci: str + comment: str | None + side: str + + def to_dict(self) -> dict[str, Any]: + return {"ply": self.ply, "san": self.san, "uci": self.uci, + "comment": self.comment, "side": self.side} + + +class ChessGame: + def __init__(self, game_id: str, agents: dict[str, dict] | None = None): + self.game_id = game_id + self.board = chess.Board() + self.history: list[HistoryEntry] = [] + self.agents = agents or {} + self.pending_draw_by: Side | None = None + self.started_at = datetime.now(timezone.utc).isoformat() + self.ended_at: str | None = None + self.termination: str | None = None + self.result: str | None = None + + # ---------- state ---------- + + @property + def side_to_move(self) -> Side: + return Side.WHITE if self.board.turn == chess.WHITE else Side.BLACK + + def _ascii_board(self) -> str: + return str(self.board) + + def _status(self) -> dict[str, Any]: + return { + "result": self.result, + "termination": self.termination, + "in_check": self.board.is_check(), + "halfmove_clock": self.board.halfmove_clock, + "fullmove_number": self.board.fullmove_number, + "legal_moves_count": self.board.legal_moves.count(), + "pending_draw_offer_by": ( + self.pending_draw_by.value if self.pending_draw_by else None + ), + } + + def get_state(self) -> dict[str, Any]: + return { + "id": self.game_id, + "fen": self.board.fen(), + "ascii": self._ascii_board(), + "side_to_move": self.side_to_move.value, + "history": [h.to_dict() for h in self.history], + "status": self._status(), + "agents": self.agents, + "started_at": self.started_at, + "ended_at": self.ended_at, + } + + # ---------- mutations ---------- + + def try_move( + self, + side: Side, + move_str: str, + comment: str | None = None, + *, + allow_illegal: bool = False, + ) -> MoveResult: + if self.is_game_over(): + return MoveResult(ok=False, reason="game_over", detail=self.termination) + if side != self.side_to_move: + return MoveResult( + ok=False, + reason="not_your_turn", + detail=f"side_to_move={self.side_to_move.value}", + ) + + parsed = self._parse_move(move_str) + if parsed is None and not allow_illegal: + return MoveResult( + ok=False, + reason="illegal_move", + detail=f"could not parse/validate {move_str!r}", + ) + + illegal_applied = False + if parsed is None: + # allow_illegal — try to apply raw piece relocation by UCI + uci = move_str.strip().lower() + try: + mv = chess.Move.from_uci(uci) + except Exception: + return MoveResult( + ok=False, + reason="illegal_move", + detail=f"cannot parse UCI even in illegal mode: {move_str!r}", + ) + # Force-apply via push (bypass legality) + self.board.push(mv) + san = None + illegal_applied = True + self.history.append(HistoryEntry( + ply=len(self.history) + 1, san=None, uci=mv.uci(), + comment=comment, side=side.value, + )) + else: + san = self.board.san(parsed) + self.board.push(parsed) + self.history.append(HistoryEntry( + ply=len(self.history) + 1, san=san, uci=parsed.uci(), + comment=comment, side=side.value, + )) + + # any move retracts pending draw offer + self.pending_draw_by = None + + self._check_game_over_natural() + + return MoveResult( + ok=True, + san=san, + uci=(parsed.uci() if parsed else move_str), + fen=self.board.fen(), + ascii=self._ascii_board(), + history=[h.to_dict() for h in self.history], + status=self._status(), + illegal=illegal_applied, + ) + + def _parse_move(self, move_str: str) -> chess.Move | None: + s = move_str.strip() + # try SAN + try: + mv = self.board.parse_san(s) + return mv + except Exception: + pass + # try UCI + try: + mv = chess.Move.from_uci(s.lower()) + if mv in self.board.legal_moves: + return mv + except Exception: + pass + return None + + # ---------- resign / draw ---------- + + def resign(self, side: Side, comment: str | None = None) -> dict[str, Any]: + if self.is_game_over(): + return {"ok": False, "reason": "game_over"} + self.result = "0-1" if side is Side.WHITE else "1-0" + self.termination = "resignation" + self.ended_at = datetime.now(timezone.utc).isoformat() + self.history.append(HistoryEntry( + ply=len(self.history) + 1, san=None, uci="resign", + comment=comment, side=side.value, + )) + return {"ok": True, "result": self.result, "termination": self.termination} + + def offer_draw(self, side: Side, comment: str | None = None) -> dict[str, Any]: + if self.is_game_over(): + return {"ok": False, "reason": "game_over"} + if self.pending_draw_by is side: + return {"ok": False, "reason": "already_offered"} + if self.pending_draw_by is side.opposite(): + return self.accept_draw(side, comment=comment) + self.pending_draw_by = side + return {"ok": True, "pending_draw_offer_by": side.value} + + def accept_draw(self, side: Side, comment: str | None = None) -> dict[str, Any]: + if self.is_game_over(): + return {"ok": False, "reason": "game_over"} + if self.pending_draw_by is None or self.pending_draw_by is side: + return {"ok": False, "reason": "no_pending_offer"} + self.result = "1/2-1/2" + self.termination = "agreement" + self.ended_at = datetime.now(timezone.utc).isoformat() + self.history.append(HistoryEntry( + ply=len(self.history) + 1, san=None, uci="agreement", + comment=comment, side=side.value, + )) + self.pending_draw_by = None + return {"ok": True, "result": self.result, "termination": "agreement"} + + def decline_draw(self, side: Side) -> dict[str, Any]: + if self.pending_draw_by is None or self.pending_draw_by is side: + return {"ok": False, "reason": "no_pending_offer"} + self.pending_draw_by = None + return {"ok": True} + + # ---------- internals ---------- + + def is_game_over(self) -> bool: + return self.result is not None + + def _check_game_over_natural(self) -> None: + if self.board.is_checkmate(): + self.result = "0-1" if self.board.turn == chess.WHITE else "1-0" + self.termination = "checkmate" + elif self.board.is_stalemate(): + self.result = "1/2-1/2" + self.termination = "stalemate" + elif self.board.is_insufficient_material(): + self.result = "1/2-1/2" + self.termination = "insufficient_material" + elif self.board.is_fivefold_repetition() or self.board.can_claim_threefold_repetition(): + self.result = "1/2-1/2" + self.termination = "threefold_repetition" + elif self.board.is_seventyfive_moves() or self.board.can_claim_fifty_moves(): + self.result = "1/2-1/2" + self.termination = "fifty_move_rule" + if self.result and not self.ended_at: + self.ended_at = datetime.now(timezone.utc).isoformat() + + # ---------- export ---------- + + def to_pgn(self) -> str: + game = chess.pgn.Game() + white = self.agents.get("white", {}) + black = self.agents.get("black", {}) + game.headers["Event"] = "ai-chess local" + game.headers["Site"] = "localhost" + game.headers["Date"] = self.started_at[:10].replace("-", ".") + game.headers["White"] = f"{white.get('agent','?')}/{white.get('model','?')}" + game.headers["Black"] = f"{black.get('agent','?')}/{black.get('model','?')}" + game.headers["Result"] = self.result or "*" + if self.termination: + game.headers["Termination"] = self.termination + + node = game + b = chess.Board() + for h in self.history: + if h.uci in ("resign", "agreement"): + continue + try: + mv = chess.Move.from_uci(h.uci) + except Exception: + continue + node = node.add_variation(mv) + if h.comment: + node.comment = h.comment + b.push(mv) + + out = io.StringIO() + exporter = chess.pgn.FileExporter(out) + game.accept(exporter) + return out.getvalue() diff --git a/tests/test_chess_game.py b/tests/test_chess_game.py new file mode 100644 index 0000000..36cb5b7 --- /dev/null +++ b/tests/test_chess_game.py @@ -0,0 +1,78 @@ +import pytest + +from ai_chess.chess_game import ChessGame, MoveResult +from ai_chess.sides import Side + + +def test_new_game_state(): + g = ChessGame(game_id="g1") + state = g.get_state() + assert state["side_to_move"] == "white" + assert state["history"] == [] + assert state["status"]["result"] is None + assert "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" in state["fen"] + + +def test_legal_move_white_san(): + g = ChessGame(game_id="g1") + r = g.try_move(Side.WHITE, "e4") + assert r.ok is True + assert r.san == "e4" + assert r.uci == "e2e4" + assert g.get_state()["side_to_move"] == "black" + assert g.get_state()["history"][0]["san"] == "e4" + + +def test_legal_move_uci(): + g = ChessGame(game_id="g1") + r = g.try_move(Side.WHITE, "e2e4") + assert r.ok is True + assert r.san == "e4" + + +def test_not_your_turn(): + g = ChessGame(game_id="g1") + r = g.try_move(Side.BLACK, "e5") + assert r.ok is False + assert r.reason == "not_your_turn" + + +def test_illegal_move_default_rejected(): + g = ChessGame(game_id="g1") + r = g.try_move(Side.WHITE, "e2e5") # pawn can't move two from e2 to e5 + assert r.ok is False + assert r.reason == "illegal_move" + + +def test_history_contains_comment(): + g = ChessGame(game_id="g1") + g.try_move(Side.WHITE, "e4", comment="готовься") + h = g.get_state()["history"] + assert h[0]["san"] == "e4" + assert h[0]["comment"] == "готовься" + + +def test_game_over_checkmate_fools_mate(): + g = ChessGame(game_id="g1") + moves = [ + (Side.WHITE, "f3"), + (Side.BLACK, "e5"), + (Side.WHITE, "g4"), + (Side.BLACK, "Qh4"), + ] + for side, mv in moves: + r = g.try_move(side, mv) + assert r.ok, (mv, r) + st = g.get_state() + assert st["status"]["result"] == "0-1" + assert st["status"]["termination"] == "checkmate" + + +def test_move_after_game_over(): + g = ChessGame(game_id="g1") + for side, mv in [(Side.WHITE, "f3"), (Side.BLACK, "e5"), + (Side.WHITE, "g4"), (Side.BLACK, "Qh4")]: + g.try_move(side, mv) + r = g.try_move(Side.WHITE, "a3") + assert r.ok is False + assert r.reason == "game_over"