| from typing import Any, Callable, Iterable, List, Union | |
| import chess | |
| def uci_to_board( | |
| uci_moves: Union[str, Iterable], | |
| *, | |
| force=False, | |
| fail_silent=False, | |
| verbose=True, | |
| as_board_stack=False, | |
| map_function: Callable = lambda x: x, | |
| reset_halfmove_clock = False, | |
| ) -> Union[chess.Board, List[Union[chess.Board, Any]]]: | |
| """Returns a chess.Board object from a string of UCI moves | |
| Params: | |
| force: If true, illegal moves are forcefully made. O/w, the rror is thrown | |
| verbose: Alert user via prints that illegal moves were attempted.""" | |
| board = chess.Board() | |
| forced_moves = [] | |
| did_force = False | |
| board_stack = [map_function(board.copy())] | |
| if isinstance(uci_moves, str): | |
| uci_moves = uci_moves.split(" ") | |
| for i, move in enumerate(uci_moves): | |
| try: | |
| move_obj = board.parse_uci(move) | |
| if reset_halfmove_clock: | |
| board.halfmove_clock = 0 | |
| board.push(move_obj) | |
| except (chess.IllegalMoveError, chess.InvalidMoveError) as ex: | |
| if force: | |
| did_force = True | |
| forced_moves.append((i, move)) | |
| piece = board.piece_at(chess.parse_square(move[:2])) | |
| board.set_piece_at(chess.parse_square(move[:2]), None) | |
| board.set_piece_at(chess.parse_square(move[2:4]), piece) | |
| elif fail_silent: | |
| if as_board_stack: | |
| return board_stack | |
| else: | |
| return map_function(board) | |
| else: | |
| if verbose: | |
| print(f"Failed on (move_id, uci): ({i},{move})") | |
| if as_board_stack: | |
| return board_stack | |
| else: | |
| return map_function(board) | |
| else: | |
| raise ex | |
| board_stack.append(map_function(board.copy())) | |
| if verbose and did_force: | |
| print(f"Forced (move_id, uci): {forced_moves}") | |
| if as_board_stack: | |
| return board_stack | |
| else: | |
| return map_function(board) | |