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
|
use std::collections::HashMap;
use serde_json::{json, Value};
use specs::{
Component,
HashMapStorage
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Slot {
Hand,
Body
}
impl Slot {
pub fn from_str(txt: &str) -> Option<Self> {
match txt {
"hand" => Some(Self::Hand),
"body" => Some(Self::Body),
_ => None
}
}
pub fn to_string(&self) -> String {
match self {
Self::Hand => "hand",
Self::Body => "body"
}.to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Stat {
Strength,
Defence
}
impl Stat {
pub fn from_str(txt: &str) -> Option<Self> {
match txt {
"strength" => Some(Self::Strength),
"defence" => Some(Self::Defence),
_ => None
}
}
pub fn to_string(&self) -> String {
match self {
Self::Strength => "strength",
Self::Defence => "defence"
}.to_string()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Equippable {
pub slot: Slot,
pub stats: HashMap<Stat, i64>
}
impl Equippable {
pub fn from_json(val: &Value) -> Option<Self> {
Some(Equippable{
slot: Slot::from_str(val.get("slot")?.as_str()?)?,
stats: val
.get("stats")?
.as_object()?
.into_iter()
.map(|(k, v)|
Some((Stat::from_str(k.as_str())?, v.as_i64()?))
)
.collect::<Option<HashMap<Stat, i64>>>()?
})
}
pub fn to_json(&self) -> Value {
json!({
"slot": self.slot.to_string(),
"stats": self.stats.iter().map(|(k, v)| (k.to_string(), *v)).collect::<HashMap<String, i64>>()
})
}
}
#[derive(Component, Debug, Clone)]
#[storage(HashMapStorage)]
pub struct Equipment {
pub slots: Vec<Slot>
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hashmap;
#[test]
fn slots() {
assert_eq!(Slot::from_str("hand"), Some(Slot::Hand));
assert_eq!(Slot::from_str("body"), Some(Slot::Body));
assert_eq!(Slot::from_str("hands"), None);
assert_eq!(Slot::from_str("head"), None);
}
#[test]
fn stats() {
assert_eq!(Stat::from_str("strength"), Some(Stat::Strength));
assert_eq!(Stat::from_str("defence"), Some(Stat::Defence));
assert_eq!(Stat::from_str("hand"), None);
assert_eq!(Stat::from_str("body"), None);
assert_eq!(Stat::from_str("attack"), None);
}
#[test]
fn equippable_from_json() {
assert_eq!(
Equippable::from_json(&json!({"slot": "hand", "stats": {"strength": 10}})),
Some(Equippable {slot: Slot::Hand, stats: hashmap!(Stat::Strength => 10)})
);
}
#[test]
fn bonus_value() {
assert_eq!(
Equipment{equipment: hashmap!(
Slot::Hand => Some(Equippable{
slot: Slot::Hand,
stats: hashmap!(Stat::Strength => 15)
}),
Slot::Body => None
)}.get_bonus(Stat::Strength),
15
);
}
}
|