File size: 2,894 Bytes
e80b55d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""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