"""Minimal UCI wrapper for a Stockfish process.""" from __future__ import annotations import os import subprocess DEFAULT_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "engines", "stockfish", "stockfish", "stockfish-windows-x86-64-universal.exe", ) CREATE_NO_WINDOW = 0x08000000 class StockfishEngine: def __init__(self, path: str | None = None, skill: int = 3, movetime_ms: int = 400, threads: int = 1, hash_mb: int = 32): self.path = path or DEFAULT_PATH if not os.path.isfile(self.path): raise FileNotFoundError(self.path) self.skill = max(0, min(20, int(skill))) self.movetime_ms = max(50, int(movetime_ms)) self.proc = subprocess.Popen( [self.path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1, creationflags=CREATE_NO_WINDOW, ) self._send("uci") self._wait("uciok") self._send("setoption name Skill Level value {}".format(self.skill)) self._send("setoption name Threads value {}".format(max(1, threads))) self._send("setoption name Hash value {}".format(max(1, hash_mb))) self._send("isready") self._wait("readyok") self.new_game() def _send(self, line: str) -> None: if self.proc.poll() is not None: raise RuntimeError("Stockfish process is not running") self.proc.stdin.write(line + "\n") self.proc.stdin.flush() def _wait(self, token: str) -> None: while True: line = self.proc.stdout.readline() if not line: raise RuntimeError("Stockfish closed stdout") if line.strip() == token: return def new_game(self) -> None: self._send("ucinewgame") self._send("isready") self._wait("readyok") def best_move(self, board, depth: int | None = None) -> str: self._send("position fen " + board.fen()) if depth: self._send("go depth {}".format(max(1, int(depth)))) else: self._send("go movetime {}".format(self.movetime_ms)) while True: line = self.proc.stdout.readline() if not line: raise RuntimeError("Stockfish closed stdout") parts = line.strip().split() if parts and parts[0] == "bestmove": return parts[1] def close(self) -> None: try: if self.proc.poll() is None: self._send("quit") self.proc.wait(timeout=5) except Exception: pass finally: try: self.proc.kill() except Exception: pass