diff --git a/src/ai_chess/stockfish_engine.py b/src/ai_chess/stockfish_engine.py new file mode 100644 index 0000000..d481ddf --- /dev/null +++ b/src/ai_chess/stockfish_engine.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import asyncio +import shutil +from typing import Any + + +class StockfishEngine: + def __init__(self, path: str | None = None) -> None: + self.path = path or shutil.which("stockfish") or "stockfish" + self._proc: asyncio.subprocess.Process | None = None + self._lock = asyncio.Lock() + + async def start(self) -> None: + if self._proc is not None: + return + self._proc = await asyncio.create_subprocess_exec( + self.path, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + await self._send("uci") + await self._wait_for("uciok", timeout=5.0) + await self._send("isready") + await self._wait_for("readyok", timeout=5.0) + + async def stop(self) -> None: + if self._proc is None: + return + try: + await self._send("quit") + await asyncio.wait_for(self._proc.wait(), timeout=2.0) + except Exception: + try: + self._proc.kill() + except ProcessLookupError: + pass + self._proc = None + + async def _send(self, line: str) -> None: + assert self._proc and self._proc.stdin + self._proc.stdin.write((line + "\n").encode()) + await self._proc.stdin.drain() + + async def _wait_for(self, marker: str, *, timeout: float) -> str: + assert self._proc and self._proc.stdout + + async def read() -> str: + buf = [] + while True: + line = (await self._proc.stdout.readline()).decode().rstrip("\n") + buf.append(line) + if line.startswith(marker): + return "\n".join(buf) + if not line and self._proc.stdout.at_eof(): + return "\n".join(buf) + + return await asyncio.wait_for(read(), timeout=timeout) + + async def analyze(self, fen: str, *, depth: int = 15) -> dict[str, Any]: + async with self._lock: + await self._send(f"position fen {fen}") + await self._send(f"go depth {depth}") + best_uci: str | None = None + cp: int | None = None + mate: int | None = None + pv: list[str] = [] + assert self._proc and self._proc.stdout + while True: + line = (await self._proc.stdout.readline()).decode().rstrip("\n") + if not line: + break + if line.startswith("info"): + tokens = line.split() + # parse score + if "score" in tokens: + i = tokens.index("score") + kind = tokens[i + 1] + val = int(tokens[i + 2]) + if kind == "cp": + cp = val + mate = None + elif kind == "mate": + mate = val + cp = None + if "pv" in tokens: + j = tokens.index("pv") + pv = tokens[j + 1 :] + elif line.startswith("bestmove"): + parts = line.split() + if len(parts) >= 2 and parts[1] != "(none)": + best_uci = parts[1] + break + return {"cp": cp, "mate": mate, "best_uci": best_uci, "pv": pv} diff --git a/tests/test_stockfish_engine.py b/tests/test_stockfish_engine.py new file mode 100644 index 0000000..d2b75e1 --- /dev/null +++ b/tests/test_stockfish_engine.py @@ -0,0 +1,35 @@ +import shutil + +import pytest + +from ai_chess.stockfish_engine import StockfishEngine + + +pytestmark = pytest.mark.skipif( + shutil.which("stockfish") is None, + reason="stockfish not installed", +) + + +@pytest.mark.asyncio +async def test_startpos_eval(): + eng = StockfishEngine() + await eng.start() + try: + r = await eng.analyze("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", depth=6) + assert r["best_uci"] is not None + assert r["cp"] is not None or r["mate"] is not None + finally: + await eng.stop() + + +@pytest.mark.asyncio +async def test_mate_eval(): + eng = StockfishEngine() + await eng.start() + try: + # Mate in 1: white to move, Qh5#-style position + r = await eng.analyze("4k3/8/8/8/8/8/4Q3/4K3 w - - 0 1", depth=10) + assert (r["mate"] is not None and r["mate"] > 0) or (r["cp"] is not None and r["cp"] > 500) + finally: + await eng.stop()