Skip to content

Commit

Permalink
Config serialization/deserialization for PostFlopGame
Browse files Browse the repository at this point in the history
  • Loading branch information
bkushigian committed Oct 11, 2024
1 parent 5980a21 commit af09e54
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/game/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1460,4 +1460,49 @@ impl PostFlopGame {
pub fn get_state(&self) -> &State {
&self.state
}

/// This is a temporary function that is _not_ guaranteed to be supported in
/// future versions. It returns a JSON object with a game's `TreeConfig` and
/// `CardConfig`.
pub fn configs_as_json(&self) -> Result<serde_json::Value, String> {
let tree_config = serde_json::to_value(self.tree_config());
let tree_config = tree_config.map_err(|e| {
format!(
"Couldn't serialize TreeConfig {:?} to JSON:\n{}",
self.tree_config(),
e
)
})?;
let card_config = serde_json::to_value(self.card_config());
let card_config = card_config.map_err(|e| {
format!(
"Couldn't serialize CardConfig {:?} to JSON:\n{}",
self.card_config(),
e
)
})?;
let mut map = serde_json::Map::new();
map.insert("tree_config".to_string(), tree_config);
map.insert("card_config".to_string(), card_config);
let json_config = serde_json::Value::Object(map);
Ok(json_config)
}

pub fn game_from_configs_json(configs_json: serde_json::Value) -> Result<PostFlopGame, String> {
let map = configs_json.as_object().ok_or({
"Config JSON must be a JSON object with keys \"tree_config\" and \"card_config\""
})?;
let tree_config = map
.get("tree_config")
.ok_or("Config JSON must contain key \"tree_config\"")?;
let card_config = map
.get("card_config")
.ok_or("Config JSON must contain key \"card_config\"")?;
let tree_config: TreeConfig = serde_json::from_value(tree_config.clone())
.map_err(|_| "Error deserializing tree_config")?;
let card_config: CardConfig = serde_json::from_value(card_config.clone())
.map_err(|_| "Error deserializing card_config")?;
let action_tree = ActionTree::new(tree_config)?;
PostFlopGame::with_config(card_config, action_tree)
}
}

0 comments on commit af09e54

Please sign in to comment.