added random_stockfish_strategy.py

This commit is contained in:
2024-01-31 10:19:49 +01:00
parent 82ec4971a6
commit 15ce6c5316
5 changed files with 52 additions and 6 deletions

View File

@@ -4,6 +4,7 @@ from chesspp.engine import *
from chesspp.lc0_strategy import Lc0Strategy
from chesspp.random_strategy import RandomStrategy
from chesspp.stockfish_strategy import StockFishStrategy
from chesspp.random_stockfish_strategy import RandomStockfishStrategy
from chesspp.i_strategy import IStrategy
import chess
@@ -20,6 +21,7 @@ class StrategyEnum(Enum):
Stockfish = 0
Lc0 = 1
Random = 2
RandomStockfish = 3
class EngineFactory:
@@ -33,6 +35,8 @@ class EngineFactory:
strategy = EngineFactory._get_lc0_strategy(lc0_path, rollout_depth)
case StrategyEnum.Random:
strategy = EngineFactory._get_random_strategy(rollout_depth)
case StrategyEnum.RandomStockfish:
strategy = EngineFactory._get_random_stockfish_strategy(stockfish_path, rollout_depth)
match engine_name:
case EngineEnum.ClassicMcts:
@@ -71,6 +75,10 @@ class EngineFactory:
def _get_stockfish_strategy(engine_path: str, rollout_depth: int) -> IStrategy:
return StockFishStrategy(engine_path, rollout_depth)
@staticmethod
def _get_random_stockfish_strategy(engine_path: str, rollout_depth: int) -> IStrategy:
return RandomStockfishStrategy(rollout_depth, engine_path)
@staticmethod
def _get_lc0_strategy(engine_path: str, rollout_depth: int) -> IStrategy:
return Lc0Strategy(engine_path, rollout_depth)

View File

@@ -0,0 +1,36 @@
import random
import chess
import chess.engine
from chesspp.i_strategy import IStrategy
from chesspp.eval import score_stockfish
class RandomStockfishStrategy(IStrategy):
def __init__(self, rollout_depth: int, path="../stockfish/stockfish-windows-x86-64-avx2",
random_seed: random.Random = random.Random()) -> None:
super().__init__(rollout_depth)
self._stockfish = None
self.path = path
self.random_seed = random_seed
def __del__(self):
if self._stockfish is not None:
self._stockfish.quit()
@property
def stockfish(self) -> chess.engine.SimpleEngine:
if self._stockfish is None:
self._stockfish = self.stockfish = chess.engine.SimpleEngine.popen_uci(self.path)
return self._stockfish
@stockfish.setter
def stockfish(self, stockfish):
self._stockfish = stockfish
def pick_next_move(self, board: chess.Board) -> chess.Move:
return self.random_seed.choice(list(board.legal_moves))
def analyze_board(self, board: chess.Board) -> int:
return score_stockfish(board, self.stockfish)

View File

@@ -1,4 +1,3 @@
import os
import chess
from chesspp.i_strategy import IStrategy
from chesspp.eval import score_stockfish