From 63a2e051997f38fe615e4f2eb0775f9e6cdfb994 Mon Sep 17 00:00:00 2001 From: David Gay Date: Sat, 30 Sep 2023 22:12:52 -0400 Subject: DieRoll struct --- src/dice.rs | 26 ++++++++++++++++++++------ src/main.rs | 5 +++-- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/dice.rs b/src/dice.rs index 06771ee..1293a6f 100644 --- a/src/dice.rs +++ b/src/dice.rs @@ -2,8 +2,22 @@ use std::fmt; use std::fmt::Formatter; use rand::Rng; +pub struct DieRoll { + sides: u32, + face: u32, +} + +impl DieRoll { + fn new(sides: u32, face: u32) -> Self { + DieRoll { + sides, + face, + } + } +} + pub struct RollResult { - rolls: Vec, + rolls: Vec, } impl RollResult { @@ -13,12 +27,12 @@ impl RollResult { } } - fn add_roll(&mut self, roll: u32) { - self.rolls.push(roll); + fn add_roll(&mut self, roll: DieRoll) { + self.rolls.push(roll) } fn total(&self) -> u32 { - self.rolls.iter().sum() + self.rolls.iter().map(|die_roll| die_roll.face).sum() } } @@ -60,8 +74,8 @@ pub fn roll_formula(formula: &str) -> Option { let mut roll_result = RollResult::new(); for _ in 0..num_dice { - let roll = roll_die(sides); - roll_result.add_roll(roll); + let face = roll_die(sides); + roll_result.add_roll(DieRoll::new(sides, face)); } Some(roll_result) diff --git a/src/main.rs b/src/main.rs index 28558eb..88fa2ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,9 @@ mod dice; fn main() { - println!("Rolling d20:"); - match dice::roll_formula("d20") { + const TEST_FORMULA : &str = "3d6"; + println!("Rolling {}:", TEST_FORMULA); + match dice::roll_formula(TEST_FORMULA) { Some(result) => println!("{}", result), None => eprintln!("Error: Invalid roll formula, or die roll otherwise failed.") } -- cgit v1.2.3