1 use rltk::RandomNumberGenerator;
2
3 pub struct RandomEntry {
4 name : String,
5 weight : i32
6 }
7
8 impl RandomEntry {
9 pub fn new<S:ToString>(name: S, weight: i32) -> RandomEntry {
10 RandomEntry{ name: name.to_string(), weight }
11 }
12 }
13
14 #[derive(Default)]
15 pub struct RandomTable {
16 entries : Vec<RandomEntry>,
17 total_weight : i32
18 }
19
20 impl RandomTable {
21 pub fn new() -> RandomTable {
22 RandomTable{ entries: Vec::new(), total_weight: 0 }
23 }
24
25 pub fn add<S:ToString>(mut self, name : S, weight: i32) -> RandomTable {
26 if weight > 0 {
27 self.total_weight += weight;
28 self.entries.push(RandomEntry::new(name.to_string(), weight));
29 }
30 self
31 }
32
33 pub fn roll(&self, rng : &mut RandomNumberGenerator) -> String {
34 if self.total_weight == 0 { return "None".to_string(); }
35 let mut roll = rng.roll_dice(1, self.total_weight)-1;
36 let mut index : usize = 0;
37
38 while roll > 0 {
39 if roll < self.entries[index].weight {
40 return self.entries[index].name.clone();
41 }
42
43 roll -= self.entries[index].weight;
44 index += 1;
45 }
46
47 "None".to_string()
48 }
49 }