Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- import ast
- def simplify_fen_string(fen):
- parts = fen.split(' ')
- simplified_fen = ' '.join(parts[:4]) # Retaining position, turn, castling rights, and en passant
- return simplified_fen
- def ten_moves_rule(board):
- """Custom rule to evaluate a draw condition based on the last ten moves."""
- history = list(board.move_stack)
- if len(history) < 10:
- return False
- for move in history[-10:]:
- if board.is_capture(move):
- return False
- print("H")
- return True
- def evaluate_board(board, depth):
- if board.is_checkmate():
- return -1000 + depth if board.turn == chess.WHITE else 1000 - depth
- elif board.is_stalemate() or board.is_insufficient_material() or ten_moves_rule(board):
- return 0
- return 0
- def minimax(board, depth, alpha, beta, maximizing_player, depth2, depths, position_count, memo):
- position_count[0] += 1
- if position_count[0] % 1000000 == 0:
- print(f"Explored {position_count[0]} positions.")
- key = (board.fen(), maximizing_player, depth, alpha, beta)
- if key in memo:
- return memo[key]
- if depth == 0 or board.is_game_over():
- eval = evaluate_board(board, depth2)
- memo[key] = (None, eval)
- return None, eval
- best_move = None
- if maximizing_player:
- max_eval = float('-inf')
- for move in board.legal_moves:
- board.push(move)
- _, eval = minimax(board, depth - 1, alpha, beta, False, depth2 + 1, depths, position_count, memo)
- board.pop()
- if eval > max_eval:
- max_eval = eval
- best_move = move
- alpha = max(alpha, eval)
- if beta <= alpha:
- break
- memo[key] = (best_move, max_eval)
- if depth2 not in depths:
- depths.append(depth2)
- print(f"Depth of recursion: {depth2}")
- return best_move, max_eval
- else:
- min_eval = float('inf')
- for move in board.legal_moves:
- board.push(move)
- _, eval = minimax(board, depth - 1, alpha, beta, True, depth2 + 1, depths, position_count, memo)
- board.pop()
- if eval < min_eval:
- min_eval = eval
- best_move = move
- beta = min(beta, eval)
- if beta <= alpha:
- break
- memo[key] = (best_move, min_eval)
- if depth2 not in depths:
- depths.append(depth2)
- print(f"Depth of recursion: {depth2}")
- return best_move, min_eval
- # Initialization and main execution logic
- start_fen = "8/4Q1K1/8/8/3k4/8/2q5/8 w - - 0 1"
- start_fen = "8/4Q1K1/8/8/3k4/8/2q5/8 w - - 0 1"
- board = chess.Board(start_fen)
- depths = []
- position_count = [0]
- memo = {}
- best_move, best_score = minimax(board, 52, float('-inf'), float('inf'), True, 0, depths, position_count, memo)
- if best_move:
- move_san = board.san(best_move)
- print(f"The best move from position {start_fen} is {move_san} with a score of {best_score}.")
- else:
- print("No move found, or the game is over. Score: ", best_score)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement