File size: 2,111 Bytes
488376b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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)