Advertisement
max2201111

snad korektni merge AR s minimax

May 9th, 2024
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.98 KB | Science | 0 0
  1. import chess
  2. import time
  3.  
  4. def ten_moves_rule(board):
  5.     """Custom rule to evaluate a draw condition based on the last ten moves, considering no captures or pawn moves."""
  6.     history = list(board.move_stack)
  7.     if len(history) < 10:
  8.         return False
  9.     for move in history[-10:]:
  10.         if board.is_capture(move):
  11.             return False
  12.         if board.piece_type_at(move.from_square) == chess.PAWN:
  13.             return False
  14.     return True
  15.  
  16. def evaluate_board(board, depth):
  17.     """Evaluate the board state for minimax decision-making."""
  18.     if board.is_checkmate():
  19.         return -1000 + depth if board.turn == chess.WHITE else 1000 - depth
  20.     elif board.is_stalemate():
  21.         return 1
  22.     elif board.is_insufficient_material():
  23.         return 2
  24.     elif ten_moves_rule(board):
  25.         return 3
  26.     return 4  # Default heuristic if none of the above conditions are met
  27.  
  28. def minimax(node, AR, depth, alpha, beta, maximizing_player, memo):
  29.     current_time = time.time()
  30.     last_print_time = AR['last_print_time']
  31.     if current_time - last_print_time[0] >= 1:
  32.         elapsed_hours, remainder = divmod(current_time - AR['start_time'], 3600)
  33.         elapsed_minutes, elapsed_seconds = divmod(remainder, 60)
  34.         print(f"\r{int(elapsed_hours):02d}h {int(elapsed_minutes):02d}m {int(elapsed_seconds):02d}s", end='', flush=True)
  35.         last_print_time[0] = current_time
  36.  
  37.     AR['position_count'][0] += 1
  38.     if AR['position_count'][0] % 1000000 == 0:
  39.         print(f"\nProzkoumano {AR['position_count'][0]} pozic.")
  40.  
  41.     board = chess.Board(AR[node]['fen'])
  42.     key = (node, maximizing_player, depth, alpha, beta)
  43.     if key in memo:
  44.         return memo[key][0], memo[key][1]
  45.  
  46.     if depth == 0 or board.is_game_over():
  47.         eval = evaluate_board(board, AR[node]['depth'])
  48.         memo[key] = ([], eval)
  49.         return [], eval
  50.  
  51.     best_eval = float('-inf') if maximizing_player else float('inf')
  52.     best_sequence = []
  53.     for move in board.legal_moves:
  54.         board.push(move)
  55.         next_node = board.fen()
  56.         if next_node not in AR:
  57.             AR[next_node] = {
  58.                 'fen': next_node,
  59.                 'parent': node,
  60.                 'color': chess.WHITE if board.turn else chess.BLACK,
  61.                 'children': [],
  62.                 'result': None,
  63.                 'depth': AR[node]['depth'] + 1,
  64.                 'score': None
  65.             }
  66.         sequence, eval = minimax(next_node, AR, depth - 1, alpha, beta, not maximizing_player, memo)
  67.         board.pop()
  68.         if maximizing_player:
  69.             if eval > best_eval:
  70.                 best_eval = eval
  71.                 best_sequence = [(move, board.san(move))] + sequence
  72.             alpha = max(alpha, eval)
  73.             if beta <= alpha:
  74.                 break
  75.         else:
  76.             if eval < best_eval:
  77.                 best_eval = eval
  78.                 best_sequence = [(move, board.san(move))] + sequence
  79.             beta = min(beta, eval)
  80.             if beta <= alpha:
  81.                 break
  82.  
  83.     memo[key] = (best_sequence, best_eval)
  84.     return best_sequence, best_eval
  85.  
  86. start_time = time.time()
  87. AR = {
  88.     'start_time': start_time,
  89.     'position_count': [0],
  90.     'last_print_time': [start_time]
  91. }
  92. memo = {}
  93. start_fen = "7k/8/3Q4/5K2/8/8/8/8 w - - 0 1"
  94. board = chess.Board(start_fen)
  95.  
  96. AR[start_fen] = {
  97.     'fen': start_fen,
  98.     'parent': None,
  99.     'color': chess.WHITE if board.turn == chess.WHITE else chess.BLACK,
  100.     'children': [],
  101.     'result': None,
  102.     'depth': 0,
  103.     'score': None
  104. }
  105.  
  106. print("Počáteční šachovnice:")
  107. print(board)
  108. print("Počáteční FEN:", board.fen(), "\n")
  109.  
  110. sequence, final_score = minimax(start_fen, AR, 9, float('-inf'), float('inf'), True, memo)
  111. print("\n\nOptimal move sequence:")
  112. for move, san in sequence:
  113.     print("Move:", san)
  114.     board.push(move)
  115.     print("Board:\n", board)
  116.     print("FEN:", board.fen())
  117.     print("Evaluation:", evaluate_board(board, 0), "\n")
  118. print("Final evaluation score:", final_score)
  119.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement