bevy_adventure/
state.rs

1use std::{
2    collections::HashMap,
3    str::FromStr,
4};
5
6use bevy::prelude::*;
7
8pub struct WorldStatePlugin;
9
10impl Plugin for WorldStatePlugin {
11    fn build(&self, app: &mut App) {
12        app ////
13            .register_type::<WorldState>()
14            .register_type::<HashMap<String, String>>()
15            ////
16            .init_resource::<WorldState>();
17    }
18}
19
20/// Stringly-typed key value store for tracking game progression.
21///
22/// Use it when you want to persist state for interactives (or anything else that needs to work with interactives).
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24#[derive(Resource, Debug, Default, Reflect)]
25#[reflect(Resource)]
26pub struct WorldState {
27    map: HashMap<String, String>,
28}
29
30impl WorldState {
31    /// Retrieve a value from the map for a given key.
32    ///
33    /// The output is parsed from the stored string.
34    pub fn get<T: FromStr>(&self, key: &str) -> Option<T> {
35        self.map
36            .get(&key.to_owned())
37            .and_then(|v| v.parse::<T>().ok())
38    }
39
40    /// Retrieve a bool value from the map for a given key.
41    ///
42    /// Returns false if the key does not exist.
43    pub fn get_bool(&self, key: &str) -> bool {
44        self.get(key).unwrap_or_default()
45    }
46
47    /// Insert a value into the map.
48    ///
49    /// The value is converted to a string, so it must implement `ToString`.
50    #[allow(clippy::needless_pass_by_value)]
51    pub fn insert<T: ToString>(&mut self, key: &str, value: T) {
52        self.map.insert(key.to_owned(), value.to_string());
53    }
54
55    /// Alias for insert.
56    pub fn set<T: ToString>(&mut self, key: &str, value: T) {
57        self.insert(key, value);
58    }
59}