feat(chess_game): ChessGame core (try_move, history, checkmate)
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user