Advertisement
max2201111

good optimal from fen1 to fen2

Apr 28th, 2024
991
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | Science | 0 0
  1. import chess
  2. from collections import deque, defaultdict
  3.  
  4. def simplify_fen(fen):
  5.     parts = fen.split(' ')
  6.     return ' '.join(parts[:4])  # Reset side to move, castling, en passant, counters
  7.  
  8. def generate_moves_and_distances(board):
  9.     initial_fen = simplify_fen(board.fen())
  10.     queue = deque([(initial_fen, 0)])
  11.     distances = defaultdict(lambda: defaultdict(lambda: float('inf')))
  12.     visited = set()
  13.  
  14.     while queue:
  15.         current_fen, current_depth = queue.popleft()
  16.        
  17.         if current_fen in visited:
  18.             continue
  19.         visited.add(current_fen)
  20.  
  21.         distances[initial_fen][current_fen] = current_depth
  22.  
  23.         current_board = chess.Board(current_fen)
  24.         for move in current_board.legal_moves:
  25.             current_board.push(move)
  26.             next_fen = simplify_fen(current_board.fen())
  27.             if next_fen not in visited or distances[initial_fen][next_fen] > current_depth + 1:
  28.                 distances[initial_fen][next_fen] = current_depth + 1
  29.                 queue.append((next_fen, current_depth + 1))
  30.             current_board.pop()
  31.  
  32.     return distances
  33.  
  34. # Main usage
  35. initial_fen = "1K6/8/8/3k4/8/8/8/8 w - - 0 1"  # Example initial position
  36.  
  37. initial_fen = "2K5/8/8/3k4/6Q1/8/8/8 w - - 0 1"
  38.  
  39. initial_fen = simplify_fen(initial_fen)
  40. board = chess.Board(initial_fen)
  41. AB = generate_moves_and_distances(board)
  42.  
  43. def print_distances_less_than_two(AB, initial_fen):
  44.     for fen2 in AB[initial_fen]:
  45.         if AB[initial_fen][fen2] < 2:
  46.             print(f"From {initial_fen} to {fen2}: {AB[initial_fen][fen2]} moves")
  47.  
  48. print_distances_less_than_two(AB, initial_fen)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement