aboutsummaryrefslogtreecommitdiff
path: root/server/src/recipes.rs
blob: b99cd21ed9d0cda7bba9986dbe651f0b07236787 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::protocol::{ItemIndex, TileIndex};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default)]
#[serde(rename_all = "snake_case")]
pub enum Action {
    #[default]
    Never,
    Passive(f32),
    Active(f32),
    Instant,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Recipe<T = TileIndex, I = ItemIndex> {
    pub tile: T,
    #[serde(default)]
    pub inputs: Vec<I>,
    #[serde(default)]
    pub outputs: Vec<I>,
    #[serde(default)]
    pub action: Action,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Gamedata {
    pub recipes: Vec<Recipe>,
    pub item_names: Vec<String>,
    pub tile_names: Vec<String>,
}
pub fn build_gamedata(recipes_in: Vec<Recipe<String, String>>) -> Gamedata {
    let mut item_names = Vec::new();
    let mut tile_names = Vec::new();
    let mut recipes = Vec::new();

    for r in recipes_in {
        recipes.push(Recipe {
            action: r.action,
            tile: register(&mut tile_names, r.tile.clone()),
            inputs: r
                .inputs
                .clone()
                .into_iter()
                .map(|e| register(&mut item_names, e))
                .collect(),
            outputs: r
                .outputs
                .clone()
                .into_iter()
                .map(|e| register(&mut item_names, e))
                .collect(),
        })
    }

    Gamedata {
        recipes,
        item_names,
        tile_names,
    }
}
fn register(db: &mut Vec<String>, name: String) -> usize {
    if let Some(index) = db.iter().position(|e| e == &name) {
        index
    } else {
        let index = db.len();
        db.push(name);
        index
    }
}

impl Gamedata {
    pub fn get_tile(&self, name: &str) -> Option<TileIndex> {
        self.tile_names.iter().position(|t| t == name)
    }
}
impl Action {
    pub fn duration(&self) -> f32 {
        match self {
            Action::Instant | Action::Never => 0.,
            Action::Passive(x) | Action::Active(x) => *x,
        }
    }
}