~deciduously/fcalc

ref: ab5f3ffdbc8c819466fedac28c8317b6af8bd799 fcalc/src/recipe.rs -rw-r--r-- 6.5 KiB
ab5f3ffdBen Lovy ItemQuantity a month ago
                                                                                
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! A recipe tracks the cost to produce an item.

use crate::{item::*, FcalcError};
use lazy_static::lazy_static;
use serde::Deserialize;
use std::{collections::HashMap, fmt, str::FromStr};

lazy_static! {
    pub static ref RECIPES: Recipes = Recipes::new();
}

/// Each recipe is made in a type of building
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
pub enum BuildingType {
    Assembler,
    Furnace,
}

impl FromStr for BuildingType {
    type Err = FcalcError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Furnace" => Ok(BuildingType::Furnace),
            "Assembler" => Ok(BuildingType::Assembler),
            _ => Err(FcalcError::InvalidBuildingType),
        }
    }
}

impl fmt::Display for BuildingType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// A formula for building a product
#[derive(Clone, Debug, Deserialize)]
pub struct RawRecipe {
    inputs: Vec<String>,
    output: String,
    time: f64,
    building_type: String,
}

/// An item with a quantity
#[derive(Clone, Debug, PartialEq)]
pub struct ItemQuantity {
    item: Item,
    quantity: u32,
}

impl ItemQuantity {
    fn new(item: Item, quantity: u32) -> Self {
        Self { item, quantity }
    }
}

impl fmt::Display for ItemQuantity {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let plural = if self.quantity > 1 { "s" } else { "" };
        write!(f, "{} {}{}", self.quantity, self.item, plural)
    }
}

impl FromStr for ItemQuantity {
    type Err = FcalcError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let split = s.split(' ').collect::<Vec<&str>>();
        if split.len() < 2 {
            return Err(FcalcError::ItemQuantityError);
        }
        // Put the rest back together
        let item_str = split[1..].iter().fold(String::new(), |mut acc, el| {
            acc.push_str(el);
            acc.push(' ');
            acc
        });
        // Lop off last space
        let item_str = &item_str[0..item_str.len() - 1];
        let item = ITEMS.lookup(&item_str).expect("Unknown item");
        let quantity = split[0].parse::<u32>().expect("u32");
        Ok(Self::new(item, quantity))
    }
}

/// A formula for building a product
#[derive(Clone, Debug, PartialEq)]
pub struct Recipe {
    pub inputs: Vec<ItemQuantity>,
    pub output: ItemQuantity,
    time: f64,
    building_type: BuildingType,
}

impl From<RawRecipe> for Recipe {
    fn from(raw: RawRecipe) -> Self {
        let inputs = raw
            .inputs
            .iter()
            .map(|el| ItemQuantity::from_str(el).unwrap())
            .collect();
        let output = ItemQuantity::from_str(&raw.output).unwrap();
        let building_type = BuildingType::from_str(&raw.building_type).unwrap();
        Self {
            inputs,
            output,
            time: raw.time,
            building_type,
        }
    }
}

/// This impl is used to produce new recipes.
/// The passed ItemQuantity is the target output.
impl From<ItemQuantity> for Recipe {
    fn from(iq: ItemQuantity) -> Self {
        unimplemented!()
    }
}

impl fmt::Display for Recipe {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut inputs = String::new();
        for input in &self.inputs {
            inputs.push_str(&input.to_string());
            inputs.push_str(", ");
        }
        let inputs = &inputs[0..inputs.len() - 2];
        write!(
            f,
            "{} => {} | {}, {} seconds",
            inputs, self.output, self.building_type, self.time
        )
    }
}

/// Each building type has several tiers
#[derive(Debug, Deserialize)]
pub struct Building {
    building_type: BuildingType,
    name: String,
    crafting_speed: f64,
}

/// Top-level to read recipes.toml
#[derive(Debug, Deserialize)]
pub struct RawRecipes {
    buildings: Vec<Building>,
    recipes: Vec<RawRecipe>,
}

impl RawRecipes {
    fn new() -> Self {
        Self::default()
    }
}

impl Default for RawRecipes {
    fn default() -> Self {
        let input = include_str!("recipes.toml");
        toml::from_str(input).expect("Could not read recipes input file.")
    }
}

/// Recipe lookup
#[derive(Debug)]
pub struct Recipes {
    recipes: HashMap<Item, Recipe>,
}

impl From<RawRecipes> for Recipes {
    fn from(raw: RawRecipes) -> Self {
        let mut recipes = HashMap::new();
        for raw in &raw.recipes {
            let recipe = Recipe::from(raw.clone());
            recipes.insert(recipe.output.item.clone(), recipe);
        }
        Self { recipes }
    }
}

impl Recipes {
    fn new() -> Self {
        let raw = RawRecipes::new();
        Self::from(raw)
    }

    pub fn lookup(&self, product: &Item) -> Option<&Recipe> {
        self.recipes.get(product)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use pretty_assertions::assert_eq;
    #[test]
    fn it_loads_all_recipes() {
        assert_eq!(RECIPES.recipes.len(), 1);
    }
    #[test]
    fn itemquantity_from_str() {
        assert_eq!(ItemQuantity::from_str("1 Iron Ore").unwrap(), ItemQuantity {
            item: Item {
                name: "Iron Ore".to_string(),
                raw: true
            },
            quantity: 1
        });
        assert_eq!(ItemQuantity::from_str("35 Iron Plate").unwrap(), ItemQuantity {
            item: Item {
                name: "Iron Plate".to_string(),
                raw: false
            },
            quantity: 35
        });
    }
    #[test]
    fn it_retrieves_defined_simple_recipe() {
        let product = ITEMS.lookup("Iron Plate").unwrap();
        let recipe = RECIPES.lookup(&product).unwrap();
        let expected = Recipe {
            inputs: vec![ItemQuantity::from_str("1 Iron Ore").unwrap()],
            output: ItemQuantity::from_str("1 Iron Plate").unwrap(),
            time: 3.2,
            building_type: BuildingType::Furnace
        };
        assert_eq!(recipe, &expected);
    }
    #[test]
    fn it_multiplies_simple_recipe() {
        let product = ITEMS.lookup("Iron Plate").unwrap();
        let target = ItemQuantity::from_str("3 Iron Plate").unwrap();
        let recipe = Recipe::from(target);
        let expected = Recipe {
            inputs: vec![ItemQuantity::from_str("3 Iron Ore").unwrap()],
            output: ItemQuantity::from_str("3 Iron Plate").unwrap(),
            time: 3.2,
            building_type: BuildingType::Furnace
        };
        assert_eq!(recipe, expected);
    }
    // #[test]
    // fn it_expands_defined_compound_recipe() {
    // 
    // }
    // #[test]
    // fn it_expands_custom_compound_recipe() {
    //     
    // }
}