Newer
Older
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
use bevy::prelude::Resource;
use bevy::utils::hashbrown::hash_map::Entry;
use bevy::utils::HashMap;
use num_traits::AsPrimitive;
use serde::{Deserialize, Serialize};
use crate::ui::components::IconContent;
pub type ItemName = String;
#[derive(Resource, Clone, Debug, Default, Serialize, Deserialize)]
pub struct TradingState {
pub items: HashMap<ItemName, usize>,
pub gold: isize,
}
#[derive(Resource, Clone, Debug, Default, Serialize, Deserialize)]
pub struct HungerState {
pub sustenance: usize,
pub starvation_ticks: f32,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TradeGood {
pub name: String,
pub icon: IconContent,
}
impl TradingState {
pub fn spend_gold(&mut self, amount: impl AsPrimitive<isize>) -> bool {
if self.gold < amount.as_() {
false
} else {
self.adjust_gold(amount);
true
}
}
pub fn adjust_gold(&mut self, adjustment: impl AsPrimitive<isize>) {
self.gold += adjustment.as_();
}
pub fn remove_items(
&mut self,
identifier: impl ToString,
amount: impl AsPrimitive<usize>,
) -> bool {
match self.items.entry(identifier.to_string()) {
Entry::Occupied(mut e) => {
let amount = amount.as_();
if e.get() >= &amount {
*e.get_mut() -= amount;
if e.get() == &0 {
e.remove();
}
true
} else {
false
}
}
Entry::Vacant(_) => false,
}
}
pub fn add_items(&mut self, identifier: impl ToString, amount: impl AsPrimitive<usize>) {
*self.items.entry(identifier.to_string()).or_insert(0) += amount.as_()
}
pub fn try_buy_items(
&mut self,
cost: impl AsPrimitive<isize>,
identifier: impl ToString,
amount: impl AsPrimitive<usize>,
) -> bool {
if self.spend_gold(cost) {
self.add_items(identifier, amount);
true
} else {
false
}
}
pub fn try_sell_items(
&mut self,
value: impl AsPrimitive<isize>,
identifier: impl ToString,
amount: impl AsPrimitive<usize>,
) -> bool {
if self.remove_items(identifier, amount) {
self.adjust_gold(value);
true
} else {
false
}
}
}