feat: better state_handler
This commit is contained in:
31
diceplayer/state/state_handler.py
Normal file
31
diceplayer/state/state_handler.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import pickle
|
||||
from pathlib import Path
|
||||
|
||||
from diceplayer.config import PlayerConfig
|
||||
from diceplayer.environment import System
|
||||
from diceplayer.logger import logger
|
||||
from diceplayer.state.state_model import StateModel
|
||||
|
||||
|
||||
class StateHandler:
|
||||
def __init__(self, sim_dir: Path, state_file: str = "state.pkl"):
|
||||
self._state_file = sim_dir / state_file
|
||||
|
||||
def get_state(self, config: PlayerConfig) -> StateModel | None:
|
||||
if not self._state_file.exists():
|
||||
return None
|
||||
|
||||
with self._state_file.open(mode="r") as f:
|
||||
data = pickle.load(f)
|
||||
|
||||
model = StateModel.model_validate(data)
|
||||
|
||||
if hash(model.config) != hash(config):
|
||||
logger.warning("The configuration in the state file does not match the provided configuration.")
|
||||
return None
|
||||
|
||||
return model
|
||||
|
||||
def save_state(self, state: StateModel) -> None:
|
||||
with self._state_file.open(mode="wb") as f:
|
||||
pickle.dump(state.model_dump(), f)
|
||||
Reference in New Issue
Block a user