Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chess
- from collections import deque, defaultdict
- def simplify_fen(fen):
- parts = fen.split(' ')
- return ' '.join(parts[:4]) # Reset side to move, castling, en passant, counters
- def generate_moves_and_distances(board):
- initial_fen = simplify_fen(board.fen())
- queue = deque([(initial_fen, 0)])
- distances = defaultdict(lambda: defaultdict(lambda: float('inf')))
- visited = set()
- while queue:
- current_fen, current_depth = queue.popleft()
- if current_fen in visited:
- continue
- visited.add(current_fen)
- distances[initial_fen][current_fen] = current_depth
- current_board = chess.Board(current_fen)
- for move in current_board.legal_moves:
- current_board.push(move)
- next_fen = simplify_fen(current_board.fen())
- if next_fen not in visited or distances[initial_fen][next_fen] > current_depth + 1:
- distances[initial_fen][next_fen] = current_depth + 1
- queue.append((next_fen, current_depth + 1))
- current_board.pop()
- return distances
- # Main usage
- initial_fen = "1K6/8/8/3k4/8/8/8/8 w - - 0 1" # Example initial position
- initial_fen = "2K5/8/8/3k4/6Q1/8/8/8 w - - 0 1"
- initial_fen = simplify_fen(initial_fen)
- board = chess.Board(initial_fen)
- AB = generate_moves_and_distances(board)
- def print_distances_less_than_two(AB, initial_fen):
- for fen2 in AB[initial_fen]:
- if AB[initial_fen][fen2] < 2:
- print(f"From {initial_fen} to {fen2}: {AB[initial_fen][fen2]} moves")
- print_distances_less_than_two(AB, initial_fen)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement