chessai.core.parser
1import os 2import re 3import typing 4 5import edq.util.serial 6 7import chessai.core.action 8import chessai.core.board 9import chessai.core.castling 10import chessai.core.coordinate 11import chessai.core.piece 12import chessai.core.types 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 17FEN_FILE_EXTENSION = '.fen' 18 19# FEN parsing patterns. 20DIMENSIONS_PATTERN: re.Pattern = re.compile(r'^#(\d+)x(\d+)$') 21 22class ParsedGameState: 23 """ 24 The parsed information that can be used to create a GameState. 25 26 By default, the gamestate is parsed from a FEN or a filepath that only contains a FEN. 27 28 FEN format: 29 [#<files>x<ranks>] <pieces> <turn> <castling> <en-passant> <halfmove-clock> <fullmove-number> 30 31 dimensions -- optional '#<files>x<ranks>' (e.g. '#8x8'); defaults to 8x8 if omitted 32 pieces -- ranks 8..1, files a..h; '/' separates ranks; digits = empty coordinates 33 turn -- 'w' or 'b' 34 castling -- 'KQkq' subset or '-' 35 en-passant -- target coordinate in algebraic notation or '-' 36 halfmove -- integer 37 fullmove -- integer (starts at 1, increments after Black's move) 38 39 The dimensions field is a chessai extension and is not part of the standard FEN spec. 40 Standard FEN strings (6 fields) are accepted without modification. 41 42 See: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation . 43 """ 44 45 __slots__ = ( 46 'pieces', 47 'turn', 48 'castling_rights', 49 'en_passant_coordinate', 50 'halfmove_clock', 51 'fullmove_number', 52 'num_files', 53 'num_ranks', 54 'options', 55 ) 56 57 def __init__(self, 58 pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece], 59 turn: chessai.core.types.Color, 60 castling_rights: chessai.core.castling.CastlingRights, 61 en_passant_coordinate: chessai.core.coordinate.Coordinate | None, 62 halfmove_clock: int, 63 fullmove_number: int, 64 num_files: int = chessai.core.board.DEFAULT_BOARD_FILES, 65 num_ranks: int = chessai.core.board.DEFAULT_BOARD_RANKS, 66 options: dict[str, typing.Any] | None = None, 67 ) -> None: 68 self.pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = pieces 69 """ The position of the pieces on the board. """ 70 71 self.turn: chessai.core.types.Color = turn 72 """ The current turn of the game. """ 73 74 self.castling_rights: chessai.core.castling.CastlingRights = castling_rights 75 """ The available castling rights in the game. """ 76 77 self.en_passant_coordinate: chessai.core.coordinate.Coordinate | None = en_passant_coordinate 78 """ The game's en-passant coordinate. """ 79 80 self.halfmove_clock: int = halfmove_clock 81 """ The game's halfmove clock. """ 82 83 self.fullmove_number: int = fullmove_number 84 """ The game's fullmove number. """ 85 86 self.num_files: int = num_files 87 """ The number of files in the FEN. """ 88 89 self.num_ranks: int = num_ranks 90 """ The number of ranks found in the FEN. """ 91 92 if (options is None): 93 options = {} 94 95 self.options: dict[str, typing.Any] = options 96 """ Any additional options found in the FEN. """ 97 98 def __eq__(self, other: object) -> bool: 99 if not isinstance(other, ParsedGameState): 100 raise ValueError(f"Cannot compare equality of a ParsedGameState with an object of another type: '{type(other)}'.") 101 102 return ( 103 self.pieces == other.pieces and 104 self.turn == other.turn and 105 self.castling_rights == other.castling_rights and 106 self.en_passant_coordinate == other.en_passant_coordinate and 107 self.halfmove_clock == other.halfmove_clock and 108 self.fullmove_number == other.fullmove_number and 109 self.num_files == other.num_files and 110 self.num_ranks == other.num_ranks 111 ) 112 113@typing.runtime_checkable 114class GameStateStringParser(typing.Protocol): 115 """ 116 A function that parses a filepath into the necessary information for a GameState to be constructed. 117 118 Not every game type will neeed a custom GameStateParser, 119 unless they do not conform to the defualt parser. 120 """ 121 122 def __call__(self, 123 text: str, 124 **kwargs: typing.Any) -> ParsedGameState: 125 ... 126 127@typing.runtime_checkable 128class GameStateParser(typing.Protocol): 129 """ 130 A function that parses a filepath into the necessary information for a GameState to be constructed. 131 132 Not every game type will neeed a custom GameStateParser, 133 unless they do not conform to the defualt parser. 134 """ 135 136 def __call__(self, 137 data: str, 138 default_dir: str, 139 default_extension: str, 140 string_parser: GameStateStringParser, 141 accepts_raw_string: bool = False, 142 options: dict[str, typing.Any] | None = None, 143 **kwargs: typing.Any) -> ParsedGameState: 144 ... 145 146def load_fen_from_string(text: str, **kwargs: typing.Any) -> ParsedGameState: 147 """ Load a FEN string from a string. """ 148 149 fields = text.strip().split() 150 if (len(fields) not in (6, 7)): 151 raise ValueError(f"FEN must have 6 or 7 fields, found '{len(fields)}': '{text}'.") 152 153 num_files = chessai.core.board.DEFAULT_BOARD_FILES 154 num_ranks = chessai.core.board.DEFAULT_BOARD_RANKS 155 156 if (len(fields) == 7): 157 (num_files, num_ranks) = _parse_fen_dimensions(fields.pop(0)) 158 159 pieces = _parse_fen_pieces(fields[0], num_files, num_ranks) 160 turn = _parse_fen_turn(fields[1]) 161 castling_rights = chessai.core.castling.CastlingRights.from_fen_string(fields[2]) 162 en_passant = _parse_fen_en_passant(fields[3]) 163 halfmove_clock = _parse_int_field(fields[4], 'halfmove clock', min_value = 0) 164 fullmove_number = _parse_int_field(fields[5], 'fullmove number', min_value = 1) 165 166 return ParsedGameState( 167 pieces = pieces, 168 turn = turn, 169 castling_rights = castling_rights, 170 en_passant_coordinate = en_passant, 171 halfmove_clock = halfmove_clock, 172 fullmove_number = fullmove_number, 173 num_files = num_files, 174 num_ranks = num_ranks, 175 options = kwargs, 176 ) 177 178def parse_fen(data: str, 179 default_dir: str = BOARDS_DIR, 180 default_extension: str = FEN_FILE_EXTENSION, 181 string_parser: GameStateStringParser = load_fen_from_string, 182 accepts_raw_string: bool = True, 183 options: dict[str, typing.Any] | None = None, 184 **kwargs: typing.Any) -> ParsedGameState: 185 """ 186 Parse a FEN string into a ParsedGameState. 187 188 Accepts standard 6-field FEN strings as well as the chessai extended 189 7-field format with an optional '#<files>x<ranks>' dimensions field. 190 191 Raises ValueError if the FEN is malformed. 192 193 See https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation . 194 """ 195 196 # Check if this might be directly parseable. 197 if (accepts_raw_string and (' ' in data.strip())): 198 # Parse the data directly. 199 return string_parser(data, options = options, **kwargs) 200 201 # Otherwise, load from a path. 202 return load_from_path( 203 data, 204 default_dir = default_dir, 205 default_extension = default_extension, 206 string_parser = string_parser, 207 **kwargs, 208 ) 209 210def load_from_path(path: str, 211 default_dir: str = BOARDS_DIR, 212 default_extension: str = FEN_FILE_EXTENSION, 213 string_parser: GameStateStringParser = load_fen_from_string, 214 **kwargs: typing.Any) -> ParsedGameState: 215 """ 216 Load a FEN string from a file. 217 218 If the given path does not exist, 219 try to prefix the path with the standard board directory and suffix with the standard extension. 220 """ 221 222 raw_path = path 223 224 # If the path does not exist, try the boards directory. 225 if (not os.path.exists(path)): 226 path = os.path.join(default_dir, path) 227 228 # If this path does not have a good extension, add one. 229 if (os.path.splitext(path)[-1] != default_extension): 230 path = path + default_extension 231 232 if (not os.path.exists(path)): 233 raise ValueError(f"Could not find {default_extension} file, path does not exist: '{raw_path}'.") 234 235 text = edq.util.dirent.read_file(path, strip = False) 236 return string_parser(text, **kwargs) 237 238def serialize_fen( 239 board: chessai.core.board.Board, 240 turn: chessai.core.types.Color, 241 castling_rights: chessai.core.castling.CastlingRights, 242 en_passant_coordinate: chessai.core.coordinate.Coordinate | None, 243 halfmove_clock: int, 244 fullmove_number: int, 245 partial: bool = False, 246 ) -> str: 247 """ 248 Serialize game state fields back into a FEN string. 249 250 For standard 8x8 boards the dimensions field is omitted, 251 producing a standard FEN string. 252 For non-standard board sizes the chessai dimensions extension is prepended. 253 254 Partial serializations exclude the clock and move number. 255 """ 256 257 piece_field = board.to_fen_piece_field() 258 259 if (turn == chessai.core.types.Color.WHITE): 260 turn_field = 'w' 261 else: 262 turn_field = 'b' 263 264 castling_field = castling_rights.to_fen_string() 265 266 if (en_passant_coordinate is not None): 267 ep_field = en_passant_coordinate.uci() 268 else: 269 ep_field = '-' 270 271 if (partial): 272 # Produce an augmented FEN, which is useful for comparing pseudo-unique gamestates. 273 return f"{piece_field} {turn_field} {castling_field} {ep_field}" 274 275 is_standard_size = ( 276 (board.num_files == chessai.core.board.DEFAULT_BOARD_FILES) 277 and (board.num_ranks == chessai.core.board.DEFAULT_BOARD_RANKS) 278 ) 279 280 if (not is_standard_size): 281 board_field = f"#{board.num_files}x{board.num_ranks} " 282 else: 283 board_field = '' 284 285 # Produce a standard FEN. 286 return f"{board_field}{piece_field} {turn_field} {castling_field} {ep_field} {halfmove_clock} {fullmove_number}" 287 288def _parse_fen_dimensions(dimensions_field: str) -> tuple[int, int]: 289 """ 290 Parse the optional chessai dimensions field '#<files>x<ranks>'. 291 292 Returns a (num_files, num_ranks) tuple. 293 Raises ValueError if the field is malformed or contains non-positive values. 294 """ 295 296 match = DIMENSIONS_PATTERN.fullmatch(dimensions_field) 297 if (match is None): 298 raise ValueError( 299 "FEN dimensions field must be '#<files>x<ranks>' (e.g. '#8x8')," 300 + f" got: '{dimensions_field}'." 301 ) 302 303 num_files = int(match.group(1)) 304 num_ranks = int(match.group(2)) 305 306 if (num_files < 1): 307 raise ValueError(f"FEN dimensions num_files must be >= 1, got: {num_files}.") 308 309 if (num_ranks < 1): 310 raise ValueError(f"FEN dimensions num_ranks must be >= 1, got: {num_ranks}.") 311 312 return (num_files, num_ranks) 313 314def _parse_fen_pieces( 315 piece_field: str, 316 num_files: int = chessai.core.board.DEFAULT_BOARD_FILES, 317 num_ranks: int = chessai.core.board.DEFAULT_BOARD_RANKS, 318 ) -> dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece]: 319 """ 320 Parse the piece-placement field of a FEN string. 321 322 FEN ranks are ordered 8..1 (rank 8 is first), files a..h left-to-right. 323 """ 324 325 ranks = piece_field.split('/') 326 if (len(ranks) != num_ranks): 327 raise ValueError( 328 f"FEN piece field must have {num_ranks} ranks" 329 + f" separated by '/', found '{len(ranks)}': '{piece_field}'." 330 ) 331 332 known_piece_symbols = chessai.core.piece.get_registered_piece_symbols() 333 pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = {} 334 335 # A regular expression to find series of digits (empty squares) and pieces, which are each a single non-digit character. 336 fen_token_re = re.compile(r'\d+|[^\d]') 337 338 for (rank_index, rank_str) in enumerate(ranks): 339 # FEN rank 8 is index 0 in the string, which is rank 7 in [0, 7]. 340 rank = (num_ranks - 1) - rank_index 341 file = 0 342 343 for fen_token in fen_token_re.findall(rank_str): 344 if (fen_token.isdigit()): 345 file += int(fen_token) 346 elif (fen_token in known_piece_symbols): 347 if (file >= num_files): 348 raise ValueError(f"Too many pieces on rank {rank + 1} in FEN: '{rank_str}'.") 349 350 coordinate = chessai.core.coordinate.Coordinate(file, rank) 351 pieces[coordinate] = chessai.core.piece.get_registered_piece(fen_token) 352 file += 1 353 else: 354 raise ValueError(f"Unknown character '{fen_token}' in FEN piece field: '{rank_str}'.") 355 356 if (file != num_files): 357 raise ValueError( 358 f"Rank {rank + 1} has {file} files, expected" 359 + f" {num_files}: '{rank_str}'." 360 ) 361 362 return pieces 363 364def _parse_fen_turn(turn_field: str) -> chessai.core.types.Color: 365 if (turn_field == 'w'): 366 return chessai.core.types.Color.WHITE 367 368 if (turn_field == 'b'): 369 return chessai.core.types.Color.BLACK 370 371 raise ValueError(f"FEN turn field must be 'w' or 'b', found: '{turn_field}'.") 372 373def _parse_fen_en_passant(ep_field: str) -> chessai.core.coordinate.Coordinate | None: 374 if (ep_field == '-'): 375 return None 376 377 try: 378 return chessai.core.coordinate.Coordinate.from_uci(ep_field) 379 except Exception as exc: 380 raise ValueError(f"Invalid FEN en-passant field: '{ep_field}'.") from exc 381 382def _parse_int_field(raw: str, label: str, min_value: int = 0) -> int: 383 try: 384 value = int(raw) 385 except ValueError as exc: 386 raise ValueError(f"FEN {label} must be an integer, found: '{raw}'.") from exc 387 388 if (value < min_value): 389 raise ValueError(f"FEN {label} must be >= {min_value}, found: '{value}'.") 390 391 return value
23class ParsedGameState: 24 """ 25 The parsed information that can be used to create a GameState. 26 27 By default, the gamestate is parsed from a FEN or a filepath that only contains a FEN. 28 29 FEN format: 30 [#<files>x<ranks>] <pieces> <turn> <castling> <en-passant> <halfmove-clock> <fullmove-number> 31 32 dimensions -- optional '#<files>x<ranks>' (e.g. '#8x8'); defaults to 8x8 if omitted 33 pieces -- ranks 8..1, files a..h; '/' separates ranks; digits = empty coordinates 34 turn -- 'w' or 'b' 35 castling -- 'KQkq' subset or '-' 36 en-passant -- target coordinate in algebraic notation or '-' 37 halfmove -- integer 38 fullmove -- integer (starts at 1, increments after Black's move) 39 40 The dimensions field is a chessai extension and is not part of the standard FEN spec. 41 Standard FEN strings (6 fields) are accepted without modification. 42 43 See: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation . 44 """ 45 46 __slots__ = ( 47 'pieces', 48 'turn', 49 'castling_rights', 50 'en_passant_coordinate', 51 'halfmove_clock', 52 'fullmove_number', 53 'num_files', 54 'num_ranks', 55 'options', 56 ) 57 58 def __init__(self, 59 pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece], 60 turn: chessai.core.types.Color, 61 castling_rights: chessai.core.castling.CastlingRights, 62 en_passant_coordinate: chessai.core.coordinate.Coordinate | None, 63 halfmove_clock: int, 64 fullmove_number: int, 65 num_files: int = chessai.core.board.DEFAULT_BOARD_FILES, 66 num_ranks: int = chessai.core.board.DEFAULT_BOARD_RANKS, 67 options: dict[str, typing.Any] | None = None, 68 ) -> None: 69 self.pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = pieces 70 """ The position of the pieces on the board. """ 71 72 self.turn: chessai.core.types.Color = turn 73 """ The current turn of the game. """ 74 75 self.castling_rights: chessai.core.castling.CastlingRights = castling_rights 76 """ The available castling rights in the game. """ 77 78 self.en_passant_coordinate: chessai.core.coordinate.Coordinate | None = en_passant_coordinate 79 """ The game's en-passant coordinate. """ 80 81 self.halfmove_clock: int = halfmove_clock 82 """ The game's halfmove clock. """ 83 84 self.fullmove_number: int = fullmove_number 85 """ The game's fullmove number. """ 86 87 self.num_files: int = num_files 88 """ The number of files in the FEN. """ 89 90 self.num_ranks: int = num_ranks 91 """ The number of ranks found in the FEN. """ 92 93 if (options is None): 94 options = {} 95 96 self.options: dict[str, typing.Any] = options 97 """ Any additional options found in the FEN. """ 98 99 def __eq__(self, other: object) -> bool: 100 if not isinstance(other, ParsedGameState): 101 raise ValueError(f"Cannot compare equality of a ParsedGameState with an object of another type: '{type(other)}'.") 102 103 return ( 104 self.pieces == other.pieces and 105 self.turn == other.turn and 106 self.castling_rights == other.castling_rights and 107 self.en_passant_coordinate == other.en_passant_coordinate and 108 self.halfmove_clock == other.halfmove_clock and 109 self.fullmove_number == other.fullmove_number and 110 self.num_files == other.num_files and 111 self.num_ranks == other.num_ranks 112 )
The parsed information that can be used to create a GameState.
By default, the gamestate is parsed from a FEN or a filepath that only contains a FEN.
FEN format:
[#
dimensions -- optional '#
The dimensions field is a chessai extension and is not part of the standard FEN spec. Standard FEN strings (6 fields) are accepted without modification.
See: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation .
58 def __init__(self, 59 pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece], 60 turn: chessai.core.types.Color, 61 castling_rights: chessai.core.castling.CastlingRights, 62 en_passant_coordinate: chessai.core.coordinate.Coordinate | None, 63 halfmove_clock: int, 64 fullmove_number: int, 65 num_files: int = chessai.core.board.DEFAULT_BOARD_FILES, 66 num_ranks: int = chessai.core.board.DEFAULT_BOARD_RANKS, 67 options: dict[str, typing.Any] | None = None, 68 ) -> None: 69 self.pieces: dict[chessai.core.coordinate.Coordinate, chessai.core.piece.Piece] = pieces 70 """ The position of the pieces on the board. """ 71 72 self.turn: chessai.core.types.Color = turn 73 """ The current turn of the game. """ 74 75 self.castling_rights: chessai.core.castling.CastlingRights = castling_rights 76 """ The available castling rights in the game. """ 77 78 self.en_passant_coordinate: chessai.core.coordinate.Coordinate | None = en_passant_coordinate 79 """ The game's en-passant coordinate. """ 80 81 self.halfmove_clock: int = halfmove_clock 82 """ The game's halfmove clock. """ 83 84 self.fullmove_number: int = fullmove_number 85 """ The game's fullmove number. """ 86 87 self.num_files: int = num_files 88 """ The number of files in the FEN. """ 89 90 self.num_ranks: int = num_ranks 91 """ The number of ranks found in the FEN. """ 92 93 if (options is None): 94 options = {} 95 96 self.options: dict[str, typing.Any] = options 97 """ Any additional options found in the FEN. """
The position of the pieces on the board.
114@typing.runtime_checkable 115class GameStateStringParser(typing.Protocol): 116 """ 117 A function that parses a filepath into the necessary information for a GameState to be constructed. 118 119 Not every game type will neeed a custom GameStateParser, 120 unless they do not conform to the defualt parser. 121 """ 122 123 def __call__(self, 124 text: str, 125 **kwargs: typing.Any) -> ParsedGameState: 126 ...
A function that parses a filepath into the necessary information for a GameState to be constructed.
Not every game type will neeed a custom GameStateParser, unless they do not conform to the defualt parser.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
128@typing.runtime_checkable 129class GameStateParser(typing.Protocol): 130 """ 131 A function that parses a filepath into the necessary information for a GameState to be constructed. 132 133 Not every game type will neeed a custom GameStateParser, 134 unless they do not conform to the defualt parser. 135 """ 136 137 def __call__(self, 138 data: str, 139 default_dir: str, 140 default_extension: str, 141 string_parser: GameStateStringParser, 142 accepts_raw_string: bool = False, 143 options: dict[str, typing.Any] | None = None, 144 **kwargs: typing.Any) -> ParsedGameState: 145 ...
A function that parses a filepath into the necessary information for a GameState to be constructed.
Not every game type will neeed a custom GameStateParser, unless they do not conform to the defualt parser.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
147def load_fen_from_string(text: str, **kwargs: typing.Any) -> ParsedGameState: 148 """ Load a FEN string from a string. """ 149 150 fields = text.strip().split() 151 if (len(fields) not in (6, 7)): 152 raise ValueError(f"FEN must have 6 or 7 fields, found '{len(fields)}': '{text}'.") 153 154 num_files = chessai.core.board.DEFAULT_BOARD_FILES 155 num_ranks = chessai.core.board.DEFAULT_BOARD_RANKS 156 157 if (len(fields) == 7): 158 (num_files, num_ranks) = _parse_fen_dimensions(fields.pop(0)) 159 160 pieces = _parse_fen_pieces(fields[0], num_files, num_ranks) 161 turn = _parse_fen_turn(fields[1]) 162 castling_rights = chessai.core.castling.CastlingRights.from_fen_string(fields[2]) 163 en_passant = _parse_fen_en_passant(fields[3]) 164 halfmove_clock = _parse_int_field(fields[4], 'halfmove clock', min_value = 0) 165 fullmove_number = _parse_int_field(fields[5], 'fullmove number', min_value = 1) 166 167 return ParsedGameState( 168 pieces = pieces, 169 turn = turn, 170 castling_rights = castling_rights, 171 en_passant_coordinate = en_passant, 172 halfmove_clock = halfmove_clock, 173 fullmove_number = fullmove_number, 174 num_files = num_files, 175 num_ranks = num_ranks, 176 options = kwargs, 177 )
Load a FEN string from a string.
179def parse_fen(data: str, 180 default_dir: str = BOARDS_DIR, 181 default_extension: str = FEN_FILE_EXTENSION, 182 string_parser: GameStateStringParser = load_fen_from_string, 183 accepts_raw_string: bool = True, 184 options: dict[str, typing.Any] | None = None, 185 **kwargs: typing.Any) -> ParsedGameState: 186 """ 187 Parse a FEN string into a ParsedGameState. 188 189 Accepts standard 6-field FEN strings as well as the chessai extended 190 7-field format with an optional '#<files>x<ranks>' dimensions field. 191 192 Raises ValueError if the FEN is malformed. 193 194 See https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation . 195 """ 196 197 # Check if this might be directly parseable. 198 if (accepts_raw_string and (' ' in data.strip())): 199 # Parse the data directly. 200 return string_parser(data, options = options, **kwargs) 201 202 # Otherwise, load from a path. 203 return load_from_path( 204 data, 205 default_dir = default_dir, 206 default_extension = default_extension, 207 string_parser = string_parser, 208 **kwargs, 209 )
Parse a FEN string into a ParsedGameState.
Accepts standard 6-field FEN strings as well as the chessai extended
7-field format with an optional '#
Raises ValueError if the FEN is malformed.
See https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation .
211def load_from_path(path: str, 212 default_dir: str = BOARDS_DIR, 213 default_extension: str = FEN_FILE_EXTENSION, 214 string_parser: GameStateStringParser = load_fen_from_string, 215 **kwargs: typing.Any) -> ParsedGameState: 216 """ 217 Load a FEN string from a file. 218 219 If the given path does not exist, 220 try to prefix the path with the standard board directory and suffix with the standard extension. 221 """ 222 223 raw_path = path 224 225 # If the path does not exist, try the boards directory. 226 if (not os.path.exists(path)): 227 path = os.path.join(default_dir, path) 228 229 # If this path does not have a good extension, add one. 230 if (os.path.splitext(path)[-1] != default_extension): 231 path = path + default_extension 232 233 if (not os.path.exists(path)): 234 raise ValueError(f"Could not find {default_extension} file, path does not exist: '{raw_path}'.") 235 236 text = edq.util.dirent.read_file(path, strip = False) 237 return string_parser(text, **kwargs)
Load a FEN string from a file.
If the given path does not exist, try to prefix the path with the standard board directory and suffix with the standard extension.
239def serialize_fen( 240 board: chessai.core.board.Board, 241 turn: chessai.core.types.Color, 242 castling_rights: chessai.core.castling.CastlingRights, 243 en_passant_coordinate: chessai.core.coordinate.Coordinate | None, 244 halfmove_clock: int, 245 fullmove_number: int, 246 partial: bool = False, 247 ) -> str: 248 """ 249 Serialize game state fields back into a FEN string. 250 251 For standard 8x8 boards the dimensions field is omitted, 252 producing a standard FEN string. 253 For non-standard board sizes the chessai dimensions extension is prepended. 254 255 Partial serializations exclude the clock and move number. 256 """ 257 258 piece_field = board.to_fen_piece_field() 259 260 if (turn == chessai.core.types.Color.WHITE): 261 turn_field = 'w' 262 else: 263 turn_field = 'b' 264 265 castling_field = castling_rights.to_fen_string() 266 267 if (en_passant_coordinate is not None): 268 ep_field = en_passant_coordinate.uci() 269 else: 270 ep_field = '-' 271 272 if (partial): 273 # Produce an augmented FEN, which is useful for comparing pseudo-unique gamestates. 274 return f"{piece_field} {turn_field} {castling_field} {ep_field}" 275 276 is_standard_size = ( 277 (board.num_files == chessai.core.board.DEFAULT_BOARD_FILES) 278 and (board.num_ranks == chessai.core.board.DEFAULT_BOARD_RANKS) 279 ) 280 281 if (not is_standard_size): 282 board_field = f"#{board.num_files}x{board.num_ranks} " 283 else: 284 board_field = '' 285 286 # Produce a standard FEN. 287 return f"{board_field}{piece_field} {turn_field} {castling_field} {ep_field} {halfmove_clock} {fullmove_number}"
Serialize game state fields back into a FEN string.
For standard 8x8 boards the dimensions field is omitted, producing a standard FEN string. For non-standard board sizes the chessai dimensions extension is prepended.
Partial serializations exclude the clock and move number.