Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- def simplify_fen_string(fen):
- """Simplify the FEN string to just include the position of pieces without turn, castling, etc."""
- parts = fen.split(' ')
- simplified_fen = ' '.join(parts[:4])
- return simplified_fen
- def evaluate_position(board):
- """Evaluate the board position to determine if it's a checkmate, stalemate, or ongoing game."""
- if board.is_checkmate():
- if board.turn == chess.WHITE:
- return -1000 # White is checkmated, black wins
- else:
- return 1000 # Black is checkmated, white wins
- elif board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
- return 0 # Game is a draw
- return None # Game is still ongoing
- def create_AR_entry(fen, result, parent):
- """Create an entry for the analysis record (AR)."""
- return {
- 'fen': fen,
- 'parent': parent,
- 'children': [],
- 'result': result,
- 'sequence': []
- }
- def generate_positions(board, AR, parent_fen):
- """Generate all possible game positions from the current board state."""
- current_fen = board.fen()
- if len(AR) % 100000 == 0:
- print(len(AR))
- if current_fen in AR:
- return # Avoid processing the same position twice
- result = evaluate_position(board)
- AR[current_fen] = create_AR_entry(simplify_fen_string(current_fen), result, parent_fen)
- if parent_fen:
- AR[parent_fen]['children'].append(current_fen)
- if result is not None:
- return # Stop further generation if the game has ended
- for move in board.legal_moves:
- board.push(move)
- generate_positions(board, AR, current_fen)
- board.pop()
- def propagate_upwards(AR, child_fen):
- """Recursively update parent nodes based on the results of child nodes."""
- child_node = AR[child_fen]
- parent_fen = child_node['parent']
- while parent_fen:
- parent_node = AR[parent_fen]
- if parent_node['result'] is None or abs(child_node['result']) < abs(parent_node['result']):
- parent_node['result'] = -child_node['result']
- parent_node['sequence'] = [child_fen] + child_node['sequence']
- child_fen = parent_fen
- child_node = parent_node
- parent_fen = child_node['parent']
- def back_propagation(AR):
- """Propagate the results from the leaf nodes to the root based on the analysis record."""
- for fen in AR:
- node = AR[fen]
- if node['result'] is not None and node['parent']:
- propagate_upwards(AR, fen)
- def main():
- initial_fen = "8/8/8/8/3Q4/5K2/8/4k3 w - - 0 1"
- board = chess.Board(initial_fen)
- AR = {}
- generate_positions(board, AR, None)
- back_propagation(AR)
- # Output results
- initial_entry = AR[initial_fen]
- print(f"Result for initial position: {initial_entry['result']}")
- print("Optimal sequence of moves:")
- for fen in initial_entry['sequence']:
- print(chess.Board(fen))
- print()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement