summaryrefslogtreecommitdiff
path: root/src/components/item.rs
blob: 9e61567444df154058e4e4bf91aef37c3de8379a (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

use specs::{Component, DenseVecStorage};
use crate::{Template};

use super::equipment::Equippable;

#[derive(Component, Debug, Clone)]
pub struct Item {
	pub ent: Template,
	pub name: String,
	pub action: ItemAction
}



use serde_json::{json, Value};

#[derive(Debug, Clone, PartialEq)]
pub enum ItemAction {
	Eat(i64),
	Build(Template),
	Equip(Equippable),
	None
}

use ItemAction::{Eat, Build, Equip, None};

impl ItemAction {
	pub fn to_json(&self) -> Value {
		match self {
			Eat(health) => json!(["eat", health]),
			Build(template) => json!(["build", template.to_json()]),
			Equip(equippable) => json!(["equip", equippable.to_json()]),
			None => json!(["none", null])
		}
	}
	
	pub fn from_json(val: &Value) -> Option<Self> {
		let typ = val.get(0)?;
		let arg = val.get(1)?;
		Some(match typ.as_str()? {
			"eat" => Eat(arg.as_i64()?),
			"build" => Build(Template::from_json(arg).ok()?),
			"none" => None,
			"equip" => Equip(Equippable::from_json(arg)?),
			_ => {return Option::None}
		})
	}
}


#[cfg(test)]
mod tests {
	use super::*;
	use crate::hashmap;
	use super::super::equipment::*;
	
	#[test]
	fn equip_from_json() {
		assert_eq!(
			ItemAction::from_json(&json!(["equip", {"slot": "hand", "stats": {"strength": 10}}])),
			Some(ItemAction::Equip(Equippable {slot: Slot::Hand, stats: hashmap!(Stat::Strength => 10)}))
		);
		assert_eq!(
			ItemAction::from_json(&json!(["equip", {"slot": "hand", "stats": {"attack": 50}}])),
			Option::None
		);
	}
}