Advertisement
max2201111

petr good

Mar 21st, 2024
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | Science | 0 0
  1. import chess
  2.  
  3. def evaluate_position(board, evaluated_positions):
  4.     fen = board.fen()
  5.  
  6.     # Check for terminal position evaluations
  7.     if board.is_checkmate():
  8.         return -1000 if board.turn else 1000  # Checkmate
  9.     if board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
  10.         return 0  # Draw
  11.  
  12.     # Use memoization to avoid re-evaluating known positions
  13.     if fen in evaluated_positions:
  14.         return evaluated_positions[fen]
  15.  
  16.     evaluations = []
  17.  
  18.     for move in board.legal_moves:
  19.         board.push(move)
  20.         next_fen = board.fen()
  21.         if next_fen in evaluated_positions:  # Check if the resulting position has been evaluated before
  22.             eval = evaluated_positions[next_fen]
  23.         else:
  24.             eval = evaluate_position(board, evaluated_positions)
  25.             evaluated_positions[next_fen] = eval  # Store this evaluation
  26.        
  27.         if eval is not None:
  28.             evaluations.append(eval)
  29.         board.pop()
  30.  
  31.     # It's possible for evaluations to be empty if every move leads to a non-evaluable position
  32.     if not evaluations:
  33.         return None  # This line is critical; we return None if we cannot evaluate the position
  34.  
  35.     # Adjust whose turn it is to calculate the correct evaluation
  36.     # After popping the move, it's the opposite of the current board.turn
  37.     if not board.turn:  # If it's currently white's turn, we maximize because we just evaluated black's moves
  38.         evaluation = max(evaluations)
  39.     else:  # If it's currently black's turn, we minimize because we just evaluated white's moves
  40.         evaluation = min(evaluations)
  41.  
  42.     evaluated_positions[fen] = evaluation
  43.     return evaluation
  44.  
  45. # Example usage
  46. evaluated_positions = {}
  47. initial_fen = "6K1/Q7/6k1/8/8/8/8/8 w - - 0 1"
  48. board = chess.Board(initial_fen)
  49.  
  50. evaluation = evaluate_position(board, evaluated_positions)
  51. print(f"Evaluation for the position: {evaluation}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement