random_table.rs 1.2 KB

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