Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- def evaluate_position(board, evaluated_positions):
- fen = board.fen()
- # Check for terminal position evaluations
- if board.is_checkmate():
- return -1000 if board.turn else 1000 # Checkmate
- if board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
- return 0 # Draw
- # Use memoization to avoid re-evaluating known positions
- if fen in evaluated_positions:
- return evaluated_positions[fen]
- evaluations = []
- for move in board.legal_moves:
- board.push(move)
- next_fen = board.fen()
- if next_fen in evaluated_positions: # Check if the resulting position has been evaluated before
- eval = evaluated_positions[next_fen]
- else:
- eval = evaluate_position(board, evaluated_positions)
- evaluated_positions[next_fen] = eval # Store this evaluation
- if eval is not None:
- evaluations.append(eval)
- board.pop()
- # It's possible for evaluations to be empty if every move leads to a non-evaluable position
- if not evaluations:
- return None # This line is critical; we return None if we cannot evaluate the position
- # Adjust whose turn it is to calculate the correct evaluation
- # After popping the move, it's the opposite of the current board.turn
- if not board.turn: # If it's currently white's turn, we maximize because we just evaluated black's moves
- evaluation = max(evaluations)
- else: # If it's currently black's turn, we minimize because we just evaluated white's moves
- evaluation = min(evaluations)
- evaluated_positions[fen] = evaluation
- return evaluation
- # Example usage
- evaluated_positions = {}
- initial_fen = "6K1/Q7/6k1/8/8/8/8/8 w - - 0 1"
- board = chess.Board(initial_fen)
- evaluation = evaluate_position(board, evaluated_positions)
- print(f"Evaluation for the position: {evaluation}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement