Create src/modeling/chess_utils.py
Browse files- src/modeling/chess_utils.py +62 -0
src/modeling/chess_utils.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Callable, Iterable, List, Union
|
2 |
+
|
3 |
+
import chess
|
4 |
+
|
5 |
+
|
6 |
+
def uci_to_board(
|
7 |
+
uci_moves: Union[str, Iterable],
|
8 |
+
*,
|
9 |
+
force=False,
|
10 |
+
fail_silent=False,
|
11 |
+
verbose=True,
|
12 |
+
as_board_stack=False,
|
13 |
+
map_function: Callable = lambda x: x,
|
14 |
+
reset_halfmove_clock = False,
|
15 |
+
) -> Union[chess.Board, List[Union[chess.Board, Any]]]:
|
16 |
+
"""Returns a chess.Board object from a string of UCI moves
|
17 |
+
Params:
|
18 |
+
force: If true, illegal moves are forcefully made. O/w, the rror is thrown
|
19 |
+
verbose: Alert user via prints that illegal moves were attempted."""
|
20 |
+
board = chess.Board()
|
21 |
+
forced_moves = []
|
22 |
+
did_force = False
|
23 |
+
board_stack = [map_function(board.copy())]
|
24 |
+
|
25 |
+
if isinstance(uci_moves, str):
|
26 |
+
uci_moves = uci_moves.split(" ")
|
27 |
+
|
28 |
+
for i, move in enumerate(uci_moves):
|
29 |
+
try:
|
30 |
+
move_obj = board.parse_uci(move)
|
31 |
+
if reset_halfmove_clock:
|
32 |
+
board.halfmove_clock = 0
|
33 |
+
board.push(move_obj)
|
34 |
+
except (chess.IllegalMoveError, chess.InvalidMoveError) as ex:
|
35 |
+
if force:
|
36 |
+
did_force = True
|
37 |
+
forced_moves.append((i, move))
|
38 |
+
piece = board.piece_at(chess.parse_square(move[:2]))
|
39 |
+
board.set_piece_at(chess.parse_square(move[:2]), None)
|
40 |
+
board.set_piece_at(chess.parse_square(move[2:4]), piece)
|
41 |
+
elif fail_silent:
|
42 |
+
if as_board_stack:
|
43 |
+
return board_stack
|
44 |
+
else:
|
45 |
+
return map_function(board)
|
46 |
+
else:
|
47 |
+
if verbose:
|
48 |
+
print(f"Failed on (move_id, uci): ({i},{move})")
|
49 |
+
if as_board_stack:
|
50 |
+
return board_stack
|
51 |
+
else:
|
52 |
+
return map_function(board)
|
53 |
+
else:
|
54 |
+
raise ex
|
55 |
+
board_stack.append(map_function(board.copy()))
|
56 |
+
if verbose and did_force:
|
57 |
+
print(f"Forced (move_id, uci): {forced_moves}")
|
58 |
+
|
59 |
+
if as_board_stack:
|
60 |
+
return board_stack
|
61 |
+
else:
|
62 |
+
return map_function(board)
|