From 7fd92266002a4164dc7aeeb99f85a88767306904 Mon Sep 17 00:00:00 2001 From: David Gay Date: Sat, 30 Sep 2023 21:52:43 -0400 Subject: RollResult struct --- src/dice.rs | 37 ++++++++++++++++++++++++++++++++----- 1 file 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, +} + +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 { +pub fn roll_formula(formula: &str) -> Option { 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 { 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) } -- cgit v1.2.3