Xiangiqgame
AI engine for Xiangqi
Loading...
Searching...
No Matches
game_summary_io.py
Go to the documentation of this file.
1"""
2Contains functions for importing / exporting a GameSummary from / to .json file.
3"""
4
5import msgspec
6import numpy as np
7from pathlib import Path
8from typing import Any, Type
9from xiangqi_bindings import PieceColor, PieceType
10from xiangqipy.game import GameSummary
11
12
13def enc_hook(obj: Any) -> Any:
14 if isinstance(obj, PieceColor):
15 return int(obj)
16 if isinstance(obj, PieceType):
17 return int(obj)
18 if isinstance(obj, np.ndarray):
19 return obj.tolist()
20 else:
21 raise NotImplementedError(
22 f"Objects of type {type(obj)} are not supported"
23 )
24
25
26def dec_hook(type: Type, obj: Any) -> Any:
27 if type is PieceColor:
28 return PieceColor(obj)
29 if type is PieceType:
30 return PieceType(obj)
31 if type is np.ndarray:
32 return np.array(obj)
33 if type is np.int32:
34 return np.int32(obj)
35 if type is np.uint32:
36 return np.uint32(obj)
37
38 else:
39 raise NotImplementedError(f"Objects of type {type} are not supported")
40
41
42encoder = msgspec.json.Encoder(enc_hook=enc_hook)
43decoder = msgspec.json.Decoder(GameSummary, dec_hook=dec_hook)
44
45
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)
50
51
52def export_game_summary(game_summary: GameSummary, path: Path):
53 if path.exists():
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)
59
60 print(f"\nSummary data saved to:\n{str(path.resolve())}")
61
62 return path
63
64
65if __name__ == "__main__":
66 my_piece_color = PieceColor.kRed
67 my_int = int(my_piece_color)
68 print(my_int)
Any dec_hook(Type type, Any obj)
Contains Game class.
Definition: game.py:1