from diceplayer.config import PlayerConfig from diceplayer.logger import logger from diceplayer.state.state_model import StateModel import pickle from pathlib import Path class StateHandler: def __init__(self, sim_dir: Path, state_file: str = "state.pkl"): if not sim_dir.exists(): sim_dir.mkdir(parents=True, exist_ok=True) self._state_file = sim_dir / state_file def get(self, config: PlayerConfig, force=False) -> StateModel | None: if not self._state_file.exists(): return None with open(self._state_file, mode="rb") as file: data = pickle.load(file) model = StateModel.model_validate(data) if config != model.config and not force: logger.warning( "The configuration in the state file does not match the provided configuration." ) return None return model def save(self, state: StateModel) -> None: with self._state_file.open(mode="wb") as f: pickle.dump(state.model_dump(), f) def delete(self) -> None: if self._state_file.exists(): self._state_file.unlink()