2Contains functions for importing / exporting a GameSummary from / to .json file.
7from pathlib
import Path
8from typing
import Any, Type
9from xiangqi_bindings
import PieceColor, PieceType
14 if isinstance(obj, PieceColor):
16 if isinstance(obj, PieceType):
18 if isinstance(obj, np.ndarray):
21 raise NotImplementedError(
22 f
"Objects of type {type(obj)} are not supported"
27 if type
is PieceColor:
28 return PieceColor(obj)
31 if type
is np.ndarray:
39 raise NotImplementedError(f
"Objects of type {type} are not supported")
42encoder = msgspec.json.Encoder(enc_hook=enc_hook)
43decoder = msgspec.json.Decoder(GameSummary, dec_hook=dec_hook)
46def import_game_summary(path: Path) -> GameSummary:
47 with path.open(mode=
"rb")
as input_file:
48 encoded_summary = input_file.read()
49 return decoder.decode(encoded_summary)
52def export_game_summary(game_summary: GameSummary, path: Path):
54 raise FileExistsError(f
"{path} already exists")
55 path.parent.mkdir(parents=
True, exist_ok=
True)
56 encoded_summary = encoder.encode(game_summary)
57 with path.open(mode=
"wb")
as output_file:
58 output_file.write(encoded_summary)
60 print(f
"\nSummary data saved to:\n{str(path.resolve())}")
65if __name__ ==
"__main__":
66 my_piece_color = PieceColor.kRed
67 my_int = int(my_piece_color)
Any dec_hook(Type type, Any obj)