Spaces:
Sleeping
Sleeping
File size: 13,970 Bytes
100a6dd | 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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | # chess_engine/ai/stockfish_wrapper.py
import chess
import chess.engine
from stockfish import Stockfish
from typing import Optional, Dict, List, Tuple, Any
from enum import Enum
import asyncio
import logging
from dataclasses import dataclass
class DifficultyLevel(Enum):
BEGINNER = 1
EASY = 3
MEDIUM = 5
HARD = 8
EXPERT = 12
MASTER = 15
@dataclass
class EngineConfig:
"""Configuration for Stockfish engine"""
depth: int = 10
time_limit: float = 1.0 # seconds
threads: int = 1
hash_size: int = 16 # MB
skill_level: int = 20 # 0-20 (20 is strongest)
contempt: int = 0
ponder: bool = False
@dataclass
class MoveAnalysis:
"""Analysis result for a move"""
best_move: str
evaluation: float
depth: int
principal_variation: List[str]
time_taken: float
nodes_searched: int
class StockfishWrapper:
"""
Wrapper for Stockfish chess engine with both python-chess and stockfish library support
"""
def __init__(self, stockfish_path: Optional[str] = None, config: Optional[EngineConfig] = None):
"""
Initialize Stockfish wrapper
Args:
stockfish_path: Path to Stockfish executable
config: Engine configuration
"""
self.config = config or EngineConfig()
self.stockfish_path = stockfish_path
self.engine = None
self.stockfish = None
self.is_initialized = False
# Setup logging
self.logger = logging.getLogger(__name__)
def initialize(self) -> bool:
"""
Initialize the Stockfish engine
Returns:
True if successful, False otherwise
"""
try:
# Try to initialize with stockfish library first
if self.stockfish_path:
self.stockfish = Stockfish(
path=self.stockfish_path,
depth=self.config.depth,
parameters={
"Threads": self.config.threads,
"Hash": self.config.hash_size,
"Skill Level": self.config.skill_level,
"Contempt": self.config.contempt,
"Ponder": self.config.ponder
}
)
else:
# Use default system Stockfish
self.stockfish = Stockfish(
depth=self.config.depth,
parameters={
"Threads": self.config.threads,
"Hash": self.config.hash_size,
"Skill Level": self.config.skill_level,
"Contempt": self.config.contempt,
"Ponder": self.config.ponder
}
)
# Test if engine is working
if self.stockfish.is_fen_valid("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"):
self.is_initialized = True
self.logger.info("Stockfish engine initialized successfully")
return True
else:
self.logger.error("Stockfish engine test failed")
return False
except Exception as e:
self.logger.error(f"Failed to initialize Stockfish: {e}")
return False
async def initialize_async(self) -> bool:
"""
Initialize the chess.engine for async operations
Returns:
True if successful, False otherwise
"""
try:
if self.stockfish_path:
self.engine = await chess.engine.SimpleEngine.popen_uci(self.stockfish_path)
else:
# Try common Stockfish paths
paths = [
"/usr/bin/stockfish",
"/usr/local/bin/stockfish",
"stockfish",
"stockfish.exe"
]
for path in paths:
try:
self.engine = await chess.engine.SimpleEngine.popen_uci(path)
break
except FileNotFoundError:
continue
if not self.engine:
raise FileNotFoundError("Stockfish executable not found")
# Configure engine
await self.engine.configure({
"Threads": self.config.threads,
"Hash": self.config.hash_size,
"Skill Level": self.config.skill_level,
"Contempt": self.config.contempt,
"Ponder": self.config.ponder
})
self.is_initialized = True
self.logger.info("Async Stockfish engine initialized successfully")
return True
except Exception as e:
self.logger.error(f"Failed to initialize async Stockfish: {e}")
return False
def get_best_move(self, board: chess.Board, time_limit: Optional[float] = None) -> Optional[str]:
"""
Get the best move for current position
Args:
board: Current chess board position
time_limit: Time limit in seconds (overrides config)
Returns:
Best move in UCI notation or None if error
"""
if not self.is_initialized or not self.stockfish:
return None
try:
# Set position
self.stockfish.set_fen_position(board.fen())
# Get best move
best_move = self.stockfish.get_best_move_time(
time_limit or self.config.time_limit * 1000 # Convert to milliseconds
)
return best_move
except Exception as e:
self.logger.error(f"Error getting best move: {e}")
return None
async def get_best_move_async(self, board: chess.Board, time_limit: Optional[float] = None) -> Optional[MoveAnalysis]:
"""
Get the best move asynchronously with detailed analysis
Args:
board: Current chess board position
time_limit: Time limit in seconds
Returns:
MoveAnalysis object or None if error
"""
if not self.is_initialized or not self.engine:
return None
try:
# Set up analysis parameters
limit = chess.engine.Limit(
time=time_limit or self.config.time_limit,
depth=self.config.depth
)
# Analyze position
info = await self.engine.analyse(board, limit)
# Get best move
result = await self.engine.play(board, limit)
# Extract information
evaluation = info.get("score", chess.engine.Cp(0))
pv = info.get("pv", [])
# Convert evaluation to numerical value
if evaluation.is_mate():
eval_value = 1000.0 if evaluation.mate() > 0 else -1000.0
else:
eval_value = evaluation.score() / 100.0 # Convert centipawns to pawns
return MoveAnalysis(
best_move=result.move.uci() if result.move else "",
evaluation=eval_value,
depth=info.get("depth", 0),
principal_variation=[move.uci() for move in pv],
time_taken=info.get("time", 0.0),
nodes_searched=info.get("nodes", 0)
)
except Exception as e:
self.logger.error(f"Error in async move analysis: {e}")
return None
def evaluate_position(self, board: chess.Board) -> Optional[float]:
"""
Evaluate current position
Args:
board: Current chess board position
Returns:
Evaluation in pawns (positive for white advantage)
"""
if not self.is_initialized or not self.stockfish:
return None
try:
self.stockfish.set_fen_position(board.fen())
evaluation = self.stockfish.get_evaluation()
if evaluation is None:
return 0.0
if evaluation["type"] == "cp":
return evaluation["value"] / 100.0 # Convert centipawns to pawns
elif evaluation["type"] == "mate":
return 1000.0 if evaluation["value"] > 0 else -1000.0
return 0.0
except Exception as e:
self.logger.error(f"Error evaluating position: {e}")
return None
def get_legal_moves_with_evaluation(self, board: chess.Board) -> List[Tuple[str, float]]:
"""
Get all legal moves with their evaluations
Args:
board: Current chess board position
Returns:
List of (move, evaluation) tuples
"""
if not self.is_initialized or not self.stockfish:
return []
moves_with_eval = []
try:
for move in board.legal_moves:
# Make move temporarily
board.push(move)
# Evaluate position
evaluation = self.evaluate_position(board)
# Undo move
board.pop()
if evaluation is not None:
moves_with_eval.append((move.uci(), -evaluation)) # Negate for opponent's perspective
# Sort by evaluation (best first)
moves_with_eval.sort(key=lambda x: x[1], reverse=True)
return moves_with_eval
except Exception as e:
self.logger.error(f"Error getting moves with evaluation: {e}")
return []
def set_difficulty_level(self, level: DifficultyLevel):
"""
Set AI difficulty level
Args:
level: Difficulty level enum
"""
skill_levels = {
DifficultyLevel.BEGINNER: 1,
DifficultyLevel.EASY: 3,
DifficultyLevel.MEDIUM: 8,
DifficultyLevel.HARD: 12,
DifficultyLevel.EXPERT: 17,
DifficultyLevel.MASTER: 20
}
depths = {
DifficultyLevel.BEGINNER: 3,
DifficultyLevel.EASY: 5,
DifficultyLevel.MEDIUM: 8,
DifficultyLevel.HARD: 12,
DifficultyLevel.EXPERT: 15,
DifficultyLevel.MASTER: 20
}
self.config.skill_level = skill_levels[level]
self.config.depth = depths[level]
# Update engine parameters if initialized
if self.is_initialized and self.stockfish:
self.stockfish.set_depth(self.config.depth)
self.stockfish.set_skill_level(self.config.skill_level)
def get_engine_info(self) -> Dict[str, Any]:
"""
Get engine information and statistics
Returns:
Dictionary with engine info
"""
if not self.is_initialized:
return {"status": "not_initialized"}
return {
"status": "initialized",
"config": {
"depth": self.config.depth,
"skill_level": self.config.skill_level,
"time_limit": self.config.time_limit,
"threads": self.config.threads,
"hash_size": self.config.hash_size
},
"stockfish_available": self.stockfish is not None,
"async_engine_available": self.engine is not None
}
def is_move_blunder(self, board: chess.Board, move: str, threshold: float = 2.0) -> bool:
"""
Check if a move is a blunder
Args:
board: Current chess board position
move: Move to check in UCI notation
threshold: Evaluation drop threshold for blunder detection
Returns:
True if move is a blunder
"""
if not self.is_initialized:
return False
try:
# Get current position evaluation
current_eval = self.evaluate_position(board)
if current_eval is None:
return False
# Make the move
move_obj = chess.Move.from_uci(move)
if move_obj not in board.legal_moves:
return True # Illegal move is definitely a blunder
board.push(move_obj)
# Get evaluation after move
new_eval = self.evaluate_position(board)
# Undo move
board.pop()
if new_eval is None:
return False
# Check if evaluation dropped significantly
# Note: negate new_eval because it's opponent's turn
eval_drop = current_eval - (-new_eval)
return eval_drop > threshold
except Exception as e:
self.logger.error(f"Error checking blunder: {e}")
return False
def close(self):
"""Close the engine connection"""
if self.engine:
asyncio.create_task(self.engine.quit())
self.is_initialized = False
self.logger.info("Stockfish engine closed")
def __enter__(self):
"""Context manager entry"""
self.initialize()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit"""
self.close() |