diff options
author | David Gay <eapoems@riseup.net> | 2023-09-30 21:52:43 -0400 |
---|---|---|
committer | David Gay <eapoems@riseup.net> | 2023-09-30 21:52:43 -0400 |
commit | 7fd92266002a4164dc7aeeb99f85a88767306904 (patch) | |
tree | 3ab347684262463c1ad7feee5561d2e2ec4ac9a9 /src/dice.rs | |
parent | 3fd68c771a704efc3123d11af2a9c15564fab9a9 (diff) |
RollResult struct
Diffstat (limited to 'src/dice.rs')
-rw-r--r-- | src/dice.rs | 37 |
1 files changed, 32 insertions, 5 deletions
diff --git a/src/dice.rs b/src/dice.rs index b238a0b..06771ee 100644 --- a/src/dice.rs +++ b/src/dice.rs @@ -1,5 +1,33 @@ +use std::fmt; +use std::fmt::Formatter; use rand::Rng; +pub struct RollResult { + rolls: Vec<u32>, +} + +impl RollResult { + fn new() -> Self { + RollResult { + rolls: Vec::new(), + } + } + + fn add_roll(&mut self, roll: u32) { + self.rolls.push(roll); + } + + fn total(&self) -> u32 { + self.rolls.iter().sum() + } +} + +impl fmt::Display for RollResult { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.total()) + } +} + /// Roll a single die with the specified number of sides. pub fn roll_die(sides: u32) -> u32 { let mut rng = rand::thread_rng(); @@ -7,8 +35,7 @@ pub fn roll_die(sides: u32) -> u32 { } /// Parse and roll dice from a dice formula (e.g. "4d6+2" or "d12*3"). -// TODO: Have rolls return a RollResult or something. -pub fn roll_formula(formula: &str) -> Option<u32> { +pub fn roll_formula(formula: &str) -> Option<RollResult> { let delimiters = ['d', '+', '-', '*', '/']; // Only d implemented right now. let parts: Vec<&str> = formula.split(|c| delimiters.contains(&c)).collect(); @@ -30,12 +57,12 @@ pub fn roll_formula(formula: &str) -> Option<u32> { Err(_) => return None, }; - let mut total = 0; + let mut roll_result = RollResult::new(); for _ in 0..num_dice { let roll = roll_die(sides); - total += roll; + roll_result.add_roll(roll); } - Some(total) + Some(roll_result) } |