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
use partial_function::LowerPartialFunction;
use rand::{thread_rng, Rng};
#[derive(Deserialize)]
pub struct LootTreeNode<R> {
pub chances: i32,
pub result: R,
}
#[derive(Deserialize)]
pub struct LootTreeBuilder<R> {
pub nodes: Vec<LootTreeNode<R>>,
}
impl<R: Clone + 'static> LootTreeBuilder<R> {
pub fn new() -> Self {
LootTreeBuilder { nodes: vec![] }
}
pub fn build(self) -> LootTree<R> {
let mut f = LowerPartialFunction::new();
let mut accum = 0;
for n in self.nodes.into_iter() {
let tmp = n.chances;
f = f.with(accum, move |_| n.result.clone());
accum = accum + tmp;
}
LootTree {
partial_func: f.build(),
max: accum,
}
}
}
pub struct LootTree<R> {
partial_func: LowerPartialFunction<i32, R>,
max: i32,
}
impl<R> LootTree<R> {
pub fn roll(&self) -> Option<R> {
let rng = thread_rng().gen_range(0, self.max);
self.partial_func.eval(rng)
}
}