Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- import time
- def ten_moves_rule(board):
- history = list(board.move_stack)
- if len(history) < 10:
- return False
- for move in history[-10:]:
- if board.is_capture(move) or board.piece_type_at(move.from_square) == chess.PAWN:
- return False
- 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():
- return 4
- elif board.is_insufficient_material():
- return 3
- elif ten_moves_rule(board):
- return 2
- return 1
- def minimax(board, depth, alpha, beta, maximizing_player, move_sequence, memo):
- if depth == 0 or board.is_game_over():
- return None, evaluate_board(board, depth), move_sequence
- best_move = None
- best_eval = float('-inf') if maximizing_player else float('inf')
- best_sequence = []
- for move in board.legal_moves:
- board.push(move)
- current_sequence = move_sequence + [move]
- _, eval, seq = minimax(board, depth - 1, alpha, beta, not maximizing_player, current_sequence, memo)
- board.pop()
- if (maximizing_player and eval > best_eval) or (not maximizing_player and eval < best_eval):
- best_eval = eval
- best_move = move
- best_sequence = seq
- if maximizing_player:
- alpha = max(alpha, eval)
- else:
- beta = min(beta, eval)
- if beta <= alpha:
- break
- return best_move, best_eval, best_sequence + [best_move] if best_move else best_sequence
- def print_board_sequence(start_fen, move_sequence):
- board = chess.Board(start_fen)
- print("Počáteční stav:")
- print(board, "\nFEN:", board.fen(), "\n")
- for move in move_sequence:
- if move and move in board.legal_moves: # Kontrola, zda je tah legální
- san = board.san(move) # Získání SAN tahu
- board.push(move) # Provedení tahu na šachovnici
- print("\nDalší tah:", san)
- print(board, "\nFEN:", board.fen(), "\n")
- else:
- # print("Nelegální nebo neexistující tah: {}", format(move))
- break # Přerušení smyčky v případě nelegálního tahu
- # Spouštěcí kód
- # Výpočet a tisk tahů
- #start_fen = "7k/8/3Q4/5K2/8/8/8/8 w
- # Initialization
- start_fen = "7k/8/3Q4/5K2/8/8/8/8 w - - 0 1"
- board = chess.Board(start_fen)
- memo = {}
- # Run minimax
- _, _, sequence = minimax(board, 3, float('-inf'), float('inf'), True, [], memo)
- print_board_sequence(start_fen, sequence[::-1]) # Print the sequence from the initial position
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement