chessai.core.board

  1import os
  2import re
  3import typing
  4
  5import edq.util.serial
  6
  7import chessai.core.action
  8import chessai.core.castling
  9import chessai.core.coordinate
 10import chessai.core.piece
 11import chessai.core.types
 12import chessai.util.reflection
 13
 14THIS_DIR: str = os.path.join(os.path.dirname(os.path.realpath(__file__)))
 15BOARDS_DIR: str = os.path.join(THIS_DIR, '..', 'resources', 'boards')
 16
 17SEPARATOR_PATTERN: re.Pattern = re.compile(r'^\s*-{3,}\s*$')
 18
 19FILE_EXTENSION = '.board'
 20
 21DEFAULT_BOARD_CLASS: str = 'chessai.core.board.Board'
 22
 23DEFAULT_BOARD_FILES: int = 8
 24DEFAULT_BOARD_RANKS: int = 8
 25
 26DEFAULT_BOARD_SIZE: int = DEFAULT_BOARD_RANKS * DEFAULT_BOARD_FILES
 27
 28class Board(edq.util.serial.DictConverter):
 29    """ The board holds the current coordinates of pieces on the board. """
 30
 31    def __init__(self,
 32            pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] | None = None,
 33            _pieces: dict[int, dict[int, chessai.core.piece.Piece]] | None = None,
 34            num_files: int = DEFAULT_BOARD_FILES,
 35            num_ranks: int = DEFAULT_BOARD_RANKS,
 36            **kwargs: typing.Any) -> None:
 37        """
 38        Construct a board with the given dimensions and pieces.
 39        """
 40
 41        check_valid = True
 42
 43        if (_pieces is not None):
 44            clean_pieces = _pieces
 45            check_valid = False
 46        else:
 47            if (pieces is None):
 48                pieces = {}
 49
 50            clean_pieces = {file: {} for file in range(num_files)}
 51
 52            for (coordinate, piece) in pieces.items():
 53                if (coordinate.file not in clean_pieces):
 54                    raise ValueError('Cannot place a piece that is out of bounds:'
 55                                    + f" files '{num_files}', ranks '{num_ranks}',"
 56                                    + f" file: '{coordinate.file}'.")
 57
 58                clean_pieces[coordinate.file][coordinate.rank] = piece
 59
 60        self.pieces: dict[int, dict[int, chessai.core.piece.Piece]] = clean_pieces
 61        """ The pieces on the board, first keyed by the file and then by the rank. """
 62
 63        self.num_files: int = num_files
 64        """ The number of files of the chess board. """
 65
 66        self.num_ranks: int = num_ranks
 67        """ The number of ranks of the chess board. """
 68
 69        self._needs_copy: bool = False
 70        """ Flags if the board needs to make a copy of itself before mutating state. """
 71
 72        if (check_valid and (not self.is_valid())):
 73            raise ValueError('Cannot construct an invalid board:'
 74                + f" files '{self.num_files}', ranks '{self.num_ranks}',"
 75                + f" pieces '{self.pieces}'.")
 76
 77    def is_valid(self) -> bool:
 78        """ Checks if all of the pieces are in a valid position. """
 79
 80        for (file, rank_dict) in self.pieces.items():
 81            for (rank, _) in rank_dict.items():
 82                if (not self.is_within_bounds(file, rank)):
 83                    return False
 84
 85        return True
 86
 87    def get(self, file: int, rank: int) -> chessai.core.piece.Piece | None:
 88        """ Gets the piece at the given file and rank pair. """
 89
 90        if (file not in self.pieces):
 91            return None
 92
 93        return self.pieces[file].get(rank, None)
 94
 95    def get_coordinate_map(self) -> dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece]:
 96        """ Gets all pieces on the board in a dictionary of coordinates to pieces. """
 97
 98        piece_items: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = {}
 99
100        for (file, rank_dict) in self.pieces.items():
101            for (rank, piece) in rank_dict.items():
102                piece_items[chessai.core.coordinate.Coordinate(file, rank)] = piece
103
104        return piece_items
105
106    def has_piece(self, coordinate: chessai.core.coordinate.Coordinate) -> bool:
107        """ Returns if the given coordinate has a piece. """
108
109        if (coordinate.file not in self.pieces):
110            return False
111
112        return (self.pieces[coordinate.file].get(coordinate.rank, None) is not None)
113
114    def all_pieces(self) -> list[chessai.core.piece.Piece]:
115        """ Gets all of the pieces on the board. """
116
117        pieces: list[chessai.core.piece.Piece] = []
118
119        for (_, rank_dict) in self.pieces.items():
120            for (_, piece) in rank_dict.items():
121                pieces.append(piece)
122
123        return pieces
124
125    def all_coordinates(self) -> list[chessai.core.coordinate.Coordinate]:
126        """ Gets all of the coordinates with a piece on the board. """
127
128        coordinates: list[chessai.core.coordinate.Coordinate] = []
129
130        for (file, rank_dict) in self.pieces.items():
131            for (rank, _) in rank_dict.items():
132                coordinates.append(chessai.core.coordinate.Coordinate(file, rank))
133
134        return coordinates
135
136    def push(self, action: chessai.core.action.MoveAction) -> bool:
137        """
138        Apply an action to the board.
139        Returns whether the action captured a piece.
140        """
141
142        self._copy_for_write()
143
144        piece = self.pieces[action.start_coordinate.file].pop(action.start_coordinate.rank, None)
145        if (piece is None):
146            raise ValueError(f"There is no piece at the action's start coordinate: '{action.start_coordinate.uci()}'.")
147
148        # Convert to the promotion piece.
149        if (isinstance(action, chessai.core.action.PromotionAction) and (action.promotion is not None)):
150            piece = action.promotion
151
152        if (not self.is_within_bounds(action.end_coordinate.file, action.end_coordinate.rank)):
153            raise ValueError("Cannot push an action that moves the piece off of the board of size"
154                + f" '{self.num_files}x{self.num_ranks}': '{action.end_coordinate}'.")
155
156        target_piece = self.pieces[action.end_coordinate.file].get(action.end_coordinate.rank, None)
157
158        self.pieces[action.end_coordinate.file][action.end_coordinate.rank] = piece
159
160        return (target_piece is not None)
161
162    def remove(self, coordinate: chessai.core.coordinate.Coordinate) -> None:
163        """
164        Remove the piece from the given coordinate.
165        If there is no piece at the coordinate, the board is unchanged.
166        """
167
168        self._copy_for_write()
169
170        self.pieces[coordinate.file].pop(coordinate.rank, None)
171
172    def set(self, piece: chessai.core.piece.Piece, coordinate: chessai.core.coordinate.Coordinate) -> None:
173        """ Adds a piece to the specified coordinate, which must be within bounds. """
174
175        self._copy_for_write()
176
177        if (not self.is_within_bounds(coordinate.file, coordinate.rank)):
178            raise ValueError("Cannot remove a piece from an out of bounds coordinate on a board of size"
179                + f" '{self.num_files}x{self.num_ranks}': '{coordinate}'.")
180
181        self.pieces[coordinate.file][coordinate.rank] = piece
182
183    def is_within_bounds(self, file: int, rank: int) -> bool:
184        """ Checks whether the given file and rank are within the bounds of the board. """
185
186        if ((file < 0) or (file >= self.num_files)):
187            return False
188
189        if ((rank < 0) or (rank >= self.num_ranks)):
190            return False
191
192        return True
193
194    def is_capture(self, action: chessai.core.action.MoveAction) -> bool:
195        """ Returns if the move captures a piece. """
196
197        return (self.get(action.end_coordinate.file, action.end_coordinate.rank) is not None)
198
199    def to_fen_piece_field(self) -> str:
200        """ Convert the board into the piece-placement field of a FEN string. """
201
202        ranks: list[str] = []
203
204        for rank_index in range(self.num_ranks):
205            # FEN ranks come from highest first, so we descend from (num_ranks - 1) to rank 0.
206            rank = (self.num_ranks - 1) - rank_index
207            empty_count = 0
208
209            for file in range(self.num_files):
210                piece = self.pieces[file].get(rank, None)
211
212                if (piece is None):
213                    empty_count += 1
214                else:
215                    if (empty_count > 0):
216                        ranks.append(str(empty_count))
217                        empty_count = 0
218
219                    symbol = piece.symbol()
220                    if (symbol is None):
221                        raise ValueError(f"Cannot serialize piece '{piece}' at rank '{rank}' and file '{file}'.")
222
223                    ranks.append(symbol)
224
225            if (empty_count > 0):
226                ranks.append(str(empty_count))
227
228            # Add rank separator except after last rank.
229            if (rank_index < (self.num_ranks - 1)):
230                ranks.append('/')
231
232        return ''.join(ranks)
233
234    def copy(self,
235            context: typing.Union[edq.util.serial.SerializationContext, None] = None,
236            ) -> 'Board':
237        """ Create a deep copy of the board. """
238
239        new_board = Board(None, self.pieces, self.num_files, self.num_ranks)
240
241        new_board._needs_copy = True
242
243        return new_board
244
245    def _copy_for_write(self) -> None:
246        if (not self._needs_copy):
247            return
248
249        self.pieces = {file: rank.copy() for (file, rank) in self.pieces.items()}
250        self._needs_copy = False
THIS_DIR: str = '/home/runner/work/chessai/chessai/chessai/core'
BOARDS_DIR: str = '/home/runner/work/chessai/chessai/chessai/core/../resources/boards'
SEPARATOR_PATTERN: re.Pattern = re.compile('^\\s*-{3,}\\s*$')
FILE_EXTENSION = 'chessai.core.board'
DEFAULT_BOARD_CLASS: str = 'Board'
DEFAULT_BOARD_FILES: int = 8
DEFAULT_BOARD_RANKS: int = 8
DEFAULT_BOARD_SIZE: int = 64
class Board(edq.util.serial.DictConverter):
 29class Board(edq.util.serial.DictConverter):
 30    """ The board holds the current coordinates of pieces on the board. """
 31
 32    def __init__(self,
 33            pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] | None = None,
 34            _pieces: dict[int, dict[int, chessai.core.piece.Piece]] | None = None,
 35            num_files: int = DEFAULT_BOARD_FILES,
 36            num_ranks: int = DEFAULT_BOARD_RANKS,
 37            **kwargs: typing.Any) -> None:
 38        """
 39        Construct a board with the given dimensions and pieces.
 40        """
 41
 42        check_valid = True
 43
 44        if (_pieces is not None):
 45            clean_pieces = _pieces
 46            check_valid = False
 47        else:
 48            if (pieces is None):
 49                pieces = {}
 50
 51            clean_pieces = {file: {} for file in range(num_files)}
 52
 53            for (coordinate, piece) in pieces.items():
 54                if (coordinate.file not in clean_pieces):
 55                    raise ValueError('Cannot place a piece that is out of bounds:'
 56                                    + f" files '{num_files}', ranks '{num_ranks}',"
 57                                    + f" file: '{coordinate.file}'.")
 58
 59                clean_pieces[coordinate.file][coordinate.rank] = piece
 60
 61        self.pieces: dict[int, dict[int, chessai.core.piece.Piece]] = clean_pieces
 62        """ The pieces on the board, first keyed by the file and then by the rank. """
 63
 64        self.num_files: int = num_files
 65        """ The number of files of the chess board. """
 66
 67        self.num_ranks: int = num_ranks
 68        """ The number of ranks of the chess board. """
 69
 70        self._needs_copy: bool = False
 71        """ Flags if the board needs to make a copy of itself before mutating state. """
 72
 73        if (check_valid and (not self.is_valid())):
 74            raise ValueError('Cannot construct an invalid board:'
 75                + f" files '{self.num_files}', ranks '{self.num_ranks}',"
 76                + f" pieces '{self.pieces}'.")
 77
 78    def is_valid(self) -> bool:
 79        """ Checks if all of the pieces are in a valid position. """
 80
 81        for (file, rank_dict) in self.pieces.items():
 82            for (rank, _) in rank_dict.items():
 83                if (not self.is_within_bounds(file, rank)):
 84                    return False
 85
 86        return True
 87
 88    def get(self, file: int, rank: int) -> chessai.core.piece.Piece | None:
 89        """ Gets the piece at the given file and rank pair. """
 90
 91        if (file not in self.pieces):
 92            return None
 93
 94        return self.pieces[file].get(rank, None)
 95
 96    def get_coordinate_map(self) -> dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece]:
 97        """ Gets all pieces on the board in a dictionary of coordinates to pieces. """
 98
 99        piece_items: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = {}
100
101        for (file, rank_dict) in self.pieces.items():
102            for (rank, piece) in rank_dict.items():
103                piece_items[chessai.core.coordinate.Coordinate(file, rank)] = piece
104
105        return piece_items
106
107    def has_piece(self, coordinate: chessai.core.coordinate.Coordinate) -> bool:
108        """ Returns if the given coordinate has a piece. """
109
110        if (coordinate.file not in self.pieces):
111            return False
112
113        return (self.pieces[coordinate.file].get(coordinate.rank, None) is not None)
114
115    def all_pieces(self) -> list[chessai.core.piece.Piece]:
116        """ Gets all of the pieces on the board. """
117
118        pieces: list[chessai.core.piece.Piece] = []
119
120        for (_, rank_dict) in self.pieces.items():
121            for (_, piece) in rank_dict.items():
122                pieces.append(piece)
123
124        return pieces
125
126    def all_coordinates(self) -> list[chessai.core.coordinate.Coordinate]:
127        """ Gets all of the coordinates with a piece on the board. """
128
129        coordinates: list[chessai.core.coordinate.Coordinate] = []
130
131        for (file, rank_dict) in self.pieces.items():
132            for (rank, _) in rank_dict.items():
133                coordinates.append(chessai.core.coordinate.Coordinate(file, rank))
134
135        return coordinates
136
137    def push(self, action: chessai.core.action.MoveAction) -> bool:
138        """
139        Apply an action to the board.
140        Returns whether the action captured a piece.
141        """
142
143        self._copy_for_write()
144
145        piece = self.pieces[action.start_coordinate.file].pop(action.start_coordinate.rank, None)
146        if (piece is None):
147            raise ValueError(f"There is no piece at the action's start coordinate: '{action.start_coordinate.uci()}'.")
148
149        # Convert to the promotion piece.
150        if (isinstance(action, chessai.core.action.PromotionAction) and (action.promotion is not None)):
151            piece = action.promotion
152
153        if (not self.is_within_bounds(action.end_coordinate.file, action.end_coordinate.rank)):
154            raise ValueError("Cannot push an action that moves the piece off of the board of size"
155                + f" '{self.num_files}x{self.num_ranks}': '{action.end_coordinate}'.")
156
157        target_piece = self.pieces[action.end_coordinate.file].get(action.end_coordinate.rank, None)
158
159        self.pieces[action.end_coordinate.file][action.end_coordinate.rank] = piece
160
161        return (target_piece is not None)
162
163    def remove(self, coordinate: chessai.core.coordinate.Coordinate) -> None:
164        """
165        Remove the piece from the given coordinate.
166        If there is no piece at the coordinate, the board is unchanged.
167        """
168
169        self._copy_for_write()
170
171        self.pieces[coordinate.file].pop(coordinate.rank, None)
172
173    def set(self, piece: chessai.core.piece.Piece, coordinate: chessai.core.coordinate.Coordinate) -> None:
174        """ Adds a piece to the specified coordinate, which must be within bounds. """
175
176        self._copy_for_write()
177
178        if (not self.is_within_bounds(coordinate.file, coordinate.rank)):
179            raise ValueError("Cannot remove a piece from an out of bounds coordinate on a board of size"
180                + f" '{self.num_files}x{self.num_ranks}': '{coordinate}'.")
181
182        self.pieces[coordinate.file][coordinate.rank] = piece
183
184    def is_within_bounds(self, file: int, rank: int) -> bool:
185        """ Checks whether the given file and rank are within the bounds of the board. """
186
187        if ((file < 0) or (file >= self.num_files)):
188            return False
189
190        if ((rank < 0) or (rank >= self.num_ranks)):
191            return False
192
193        return True
194
195    def is_capture(self, action: chessai.core.action.MoveAction) -> bool:
196        """ Returns if the move captures a piece. """
197
198        return (self.get(action.end_coordinate.file, action.end_coordinate.rank) is not None)
199
200    def to_fen_piece_field(self) -> str:
201        """ Convert the board into the piece-placement field of a FEN string. """
202
203        ranks: list[str] = []
204
205        for rank_index in range(self.num_ranks):
206            # FEN ranks come from highest first, so we descend from (num_ranks - 1) to rank 0.
207            rank = (self.num_ranks - 1) - rank_index
208            empty_count = 0
209
210            for file in range(self.num_files):
211                piece = self.pieces[file].get(rank, None)
212
213                if (piece is None):
214                    empty_count += 1
215                else:
216                    if (empty_count > 0):
217                        ranks.append(str(empty_count))
218                        empty_count = 0
219
220                    symbol = piece.symbol()
221                    if (symbol is None):
222                        raise ValueError(f"Cannot serialize piece '{piece}' at rank '{rank}' and file '{file}'.")
223
224                    ranks.append(symbol)
225
226            if (empty_count > 0):
227                ranks.append(str(empty_count))
228
229            # Add rank separator except after last rank.
230            if (rank_index < (self.num_ranks - 1)):
231                ranks.append('/')
232
233        return ''.join(ranks)
234
235    def copy(self,
236            context: typing.Union[edq.util.serial.SerializationContext, None] = None,
237            ) -> 'Board':
238        """ Create a deep copy of the board. """
239
240        new_board = Board(None, self.pieces, self.num_files, self.num_ranks)
241
242        new_board._needs_copy = True
243
244        return new_board
245
246    def _copy_for_write(self) -> None:
247        if (not self._needs_copy):
248            return
249
250        self.pieces = {file: rank.copy() for (file, rank) in self.pieces.items()}
251        self._needs_copy = False

The board holds the current coordinates of pieces on the board.

Board( pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] | None = None, _pieces: dict[int, dict[int, chessai.core.piece.Piece]] | None = None, num_files: int = 8, num_ranks: int = 8, **kwargs: Any)
32    def __init__(self,
33            pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] | None = None,
34            _pieces: dict[int, dict[int, chessai.core.piece.Piece]] | None = None,
35            num_files: int = DEFAULT_BOARD_FILES,
36            num_ranks: int = DEFAULT_BOARD_RANKS,
37            **kwargs: typing.Any) -> None:
38        """
39        Construct a board with the given dimensions and pieces.
40        """
41
42        check_valid = True
43
44        if (_pieces is not None):
45            clean_pieces = _pieces
46            check_valid = False
47        else:
48            if (pieces is None):
49                pieces = {}
50
51            clean_pieces = {file: {} for file in range(num_files)}
52
53            for (coordinate, piece) in pieces.items():
54                if (coordinate.file not in clean_pieces):
55                    raise ValueError('Cannot place a piece that is out of bounds:'
56                                    + f" files '{num_files}', ranks '{num_ranks}',"
57                                    + f" file: '{coordinate.file}'.")
58
59                clean_pieces[coordinate.file][coordinate.rank] = piece
60
61        self.pieces: dict[int, dict[int, chessai.core.piece.Piece]] = clean_pieces
62        """ The pieces on the board, first keyed by the file and then by the rank. """
63
64        self.num_files: int = num_files
65        """ The number of files of the chess board. """
66
67        self.num_ranks: int = num_ranks
68        """ The number of ranks of the chess board. """
69
70        self._needs_copy: bool = False
71        """ Flags if the board needs to make a copy of itself before mutating state. """
72
73        if (check_valid and (not self.is_valid())):
74            raise ValueError('Cannot construct an invalid board:'
75                + f" files '{self.num_files}', ranks '{self.num_ranks}',"
76                + f" pieces '{self.pieces}'.")

Construct a board with the given dimensions and pieces.

pieces: dict[int, dict[int, chessai.core.piece.Piece]]

The pieces on the board, first keyed by the file and then by the rank.

num_files: int

The number of files of the chess board.

num_ranks: int

The number of ranks of the chess board.

def is_valid(self) -> bool:
78    def is_valid(self) -> bool:
79        """ Checks if all of the pieces are in a valid position. """
80
81        for (file, rank_dict) in self.pieces.items():
82            for (rank, _) in rank_dict.items():
83                if (not self.is_within_bounds(file, rank)):
84                    return False
85
86        return True

Checks if all of the pieces are in a valid position.

def get(self, file: int, rank: int) -> chessai.core.piece.Piece | None:
88    def get(self, file: int, rank: int) -> chessai.core.piece.Piece | None:
89        """ Gets the piece at the given file and rank pair. """
90
91        if (file not in self.pieces):
92            return None
93
94        return self.pieces[file].get(rank, None)

Gets the piece at the given file and rank pair.

def get_coordinate_map( self) -> dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece]:
 96    def get_coordinate_map(self) -> dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece]:
 97        """ Gets all pieces on the board in a dictionary of coordinates to pieces. """
 98
 99        piece_items: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = {}
100
101        for (file, rank_dict) in self.pieces.items():
102            for (rank, piece) in rank_dict.items():
103                piece_items[chessai.core.coordinate.Coordinate(file, rank)] = piece
104
105        return piece_items

Gets all pieces on the board in a dictionary of coordinates to pieces.

def has_piece(self, coordinate: chessai.core.coordinate.Coordinate) -> bool:
107    def has_piece(self, coordinate: chessai.core.coordinate.Coordinate) -> bool:
108        """ Returns if the given coordinate has a piece. """
109
110        if (coordinate.file not in self.pieces):
111            return False
112
113        return (self.pieces[coordinate.file].get(coordinate.rank, None) is not None)

Returns if the given coordinate has a piece.

def all_pieces(self) -> list[chessai.core.piece.Piece]:
115    def all_pieces(self) -> list[chessai.core.piece.Piece]:
116        """ Gets all of the pieces on the board. """
117
118        pieces: list[chessai.core.piece.Piece] = []
119
120        for (_, rank_dict) in self.pieces.items():
121            for (_, piece) in rank_dict.items():
122                pieces.append(piece)
123
124        return pieces

Gets all of the pieces on the board.

def all_coordinates(self) -> list[chessai.core.coordinate.Coordinate]:
126    def all_coordinates(self) -> list[chessai.core.coordinate.Coordinate]:
127        """ Gets all of the coordinates with a piece on the board. """
128
129        coordinates: list[chessai.core.coordinate.Coordinate] = []
130
131        for (file, rank_dict) in self.pieces.items():
132            for (rank, _) in rank_dict.items():
133                coordinates.append(chessai.core.coordinate.Coordinate(file, rank))
134
135        return coordinates

Gets all of the coordinates with a piece on the board.

def push(self, action: chessai.core.action.MoveAction) -> bool:
137    def push(self, action: chessai.core.action.MoveAction) -> bool:
138        """
139        Apply an action to the board.
140        Returns whether the action captured a piece.
141        """
142
143        self._copy_for_write()
144
145        piece = self.pieces[action.start_coordinate.file].pop(action.start_coordinate.rank, None)
146        if (piece is None):
147            raise ValueError(f"There is no piece at the action's start coordinate: '{action.start_coordinate.uci()}'.")
148
149        # Convert to the promotion piece.
150        if (isinstance(action, chessai.core.action.PromotionAction) and (action.promotion is not None)):
151            piece = action.promotion
152
153        if (not self.is_within_bounds(action.end_coordinate.file, action.end_coordinate.rank)):
154            raise ValueError("Cannot push an action that moves the piece off of the board of size"
155                + f" '{self.num_files}x{self.num_ranks}': '{action.end_coordinate}'.")
156
157        target_piece = self.pieces[action.end_coordinate.file].get(action.end_coordinate.rank, None)
158
159        self.pieces[action.end_coordinate.file][action.end_coordinate.rank] = piece
160
161        return (target_piece is not None)

Apply an action to the board. Returns whether the action captured a piece.

def remove(self, coordinate: chessai.core.coordinate.Coordinate) -> None:
163    def remove(self, coordinate: chessai.core.coordinate.Coordinate) -> None:
164        """
165        Remove the piece from the given coordinate.
166        If there is no piece at the coordinate, the board is unchanged.
167        """
168
169        self._copy_for_write()
170
171        self.pieces[coordinate.file].pop(coordinate.rank, None)

Remove the piece from the given coordinate. If there is no piece at the coordinate, the board is unchanged.

def set( self, piece: chessai.core.piece.Piece, coordinate: chessai.core.coordinate.Coordinate) -> None:
173    def set(self, piece: chessai.core.piece.Piece, coordinate: chessai.core.coordinate.Coordinate) -> None:
174        """ Adds a piece to the specified coordinate, which must be within bounds. """
175
176        self._copy_for_write()
177
178        if (not self.is_within_bounds(coordinate.file, coordinate.rank)):
179            raise ValueError("Cannot remove a piece from an out of bounds coordinate on a board of size"
180                + f" '{self.num_files}x{self.num_ranks}': '{coordinate}'.")
181
182        self.pieces[coordinate.file][coordinate.rank] = piece

Adds a piece to the specified coordinate, which must be within bounds.

def is_within_bounds(self, file: int, rank: int) -> bool:
184    def is_within_bounds(self, file: int, rank: int) -> bool:
185        """ Checks whether the given file and rank are within the bounds of the board. """
186
187        if ((file < 0) or (file >= self.num_files)):
188            return False
189
190        if ((rank < 0) or (rank >= self.num_ranks)):
191            return False
192
193        return True

Checks whether the given file and rank are within the bounds of the board.

def is_capture(self, action: chessai.core.action.MoveAction) -> bool:
195    def is_capture(self, action: chessai.core.action.MoveAction) -> bool:
196        """ Returns if the move captures a piece. """
197
198        return (self.get(action.end_coordinate.file, action.end_coordinate.rank) is not None)

Returns if the move captures a piece.

def to_fen_piece_field(self) -> str:
200    def to_fen_piece_field(self) -> str:
201        """ Convert the board into the piece-placement field of a FEN string. """
202
203        ranks: list[str] = []
204
205        for rank_index in range(self.num_ranks):
206            # FEN ranks come from highest first, so we descend from (num_ranks - 1) to rank 0.
207            rank = (self.num_ranks - 1) - rank_index
208            empty_count = 0
209
210            for file in range(self.num_files):
211                piece = self.pieces[file].get(rank, None)
212
213                if (piece is None):
214                    empty_count += 1
215                else:
216                    if (empty_count > 0):
217                        ranks.append(str(empty_count))
218                        empty_count = 0
219
220                    symbol = piece.symbol()
221                    if (symbol is None):
222                        raise ValueError(f"Cannot serialize piece '{piece}' at rank '{rank}' and file '{file}'.")
223
224                    ranks.append(symbol)
225
226            if (empty_count > 0):
227                ranks.append(str(empty_count))
228
229            # Add rank separator except after last rank.
230            if (rank_index < (self.num_ranks - 1)):
231                ranks.append('/')
232
233        return ''.join(ranks)

Convert the board into the piece-placement field of a FEN string.

def copy( self, context: Optional[edq.util.common.SerializationContext] = None) -> Board:
235    def copy(self,
236            context: typing.Union[edq.util.serial.SerializationContext, None] = None,
237            ) -> 'Board':
238        """ Create a deep copy of the board. """
239
240        new_board = Board(None, self.pieces, self.num_files, self.num_ranks)
241
242        new_board._needs_copy = True
243
244        return new_board

Create a deep copy of the board.