1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! RFYL implements the common dice notation used in many role playing game systems.
//! 
//! ## Supported input
//! - Basic standard dice notation: `d8`, `2d12`.
//! - Addition: `d4 + 2d6`.
//! - Subtraction: `d100 - 15`.
//! - Multiplication: `d12 * 2`.
//! - Division: `d100 / 15`. (Note that fractional values are rounded to the nearest integer.)
//! - Brackets: `(d100 + d12) / 15`.
//! - Complex dice notation: `1d4 + 2d6 * 3d2 / 4d8 + (2d6 + 3d8) - 16 * (1 / 1d4)`.
//! - Percentile dice shorthand: `d%` = `d100`.
//! - Boolean dice: `1d1` = `0` or `1`.
//! 
//! ## Example
//! 
//! ```
//! use rfyl::roll;
//! 
//! // This would actually probably come from user input, or be computed in some other way.
//! let requested_roll = String::from("(1d20 * 2) + (1d4 + 1) / 2");
//! 
//! // Rolling can fail, for instance if an illegal digit is supplied.
//! // Therefore, roll() returns a Result which must be unwrapped.
//! let roll = roll(requested_roll).unwrap();
//! 
//! // On a successful roll, roll() returns a DiceRolls struct which can be
//! // interrogated for its formula and result.
//! println!("{}: {}", roll.get_rolls_formula_string_as_infix(), roll.get_result());
//! // Should print "[[1d20 * 2] + [[1d4 + 1] * 2]]: 10" (for arbitrary values of 10).
//! ```
//! 
//! See the included command line program ([src/bin.rs](https://github.com/trnglina/RFYL/blob/master/src/bin.rs)) for further examples of how to use the [DiceRolls](struct.DiceRolls.html) struct.

extern crate rand;
use self::rand::{thread_rng, Rng};

pub mod rpn;
pub mod infix;
mod tokens;

use tokens::match_token;
use rpn::{parse_into_rpn};
use infix::{parse_into_infix};

/// The result of rolling some dice.
#[derive(Clone)]
pub struct DiceRolls {
    rolls: Vec<DiceRoll>,
    formula: Vec<String>,
    rolls_formula: Vec<String>,
}

impl DiceRolls {
    /// Returns an i32 as the result of the formula including any calculational
    /// operators.
    pub fn get_result(&self) -> i32 {
        return rpn::solve_rpn_formula(self.formula.clone());
    }

    /// Returns an i32 as the simple sum of all rolls.
    pub fn get_sum_of_rolls(&self) -> i32 {
        let mut total = 0;
        for roll in &self.rolls {
            total += roll.result;
        }
        return total;
    }

    /// Returns a formatted String showing the dice and the rolled results.
    pub fn get_rolls_string(&self) -> String {
        let mut rolls_string = String::new();
        for (i, roll) in self.rolls.iter().enumerate() {
            if i == self.rolls.len() - 1 {
                rolls_string.push_str(format!("d{} -> [{}]", roll.sides, roll.result).as_ref());
                break;
            }
            rolls_string.push_str(format!("d{} -> [{}], ", roll.sides, roll.result).as_ref());
        }
        return rolls_string;
    }

    /// Returns a postfix formatted String showing the formula, with all dice replaced with their rolled values.
    pub fn get_formula_string_as_rpn(&self) -> String {
        let mut formula_string = String::new();
        for (i, fragment) in self.formula.iter().enumerate() {
            if match_token(fragment) > 0 {
                formula_string.push_str(format!("{} ", fragment).as_ref());
                continue;
            }

            if i == self.formula.len() - 1 {
                formula_string.push_str(format!("[{}]", fragment).as_ref());
                break;
            }

            formula_string.push_str(format!("[{}] ", fragment).as_ref());
        }
        return formula_string;
    }

    /// Returns an infix formatted String showing the formula, with all dice replaced with their rolled values.
    pub fn get_formula_string_as_infix(&self) -> String {
        return parse_into_infix(self.formula.clone()).replace("( ", "[").replace(" )", "]");
    }

    /// Returns a postfix formatted String showing the formula with the original dice notation instead of the rolled result.
    pub fn get_rolls_formula_string_as_rpn(&self) -> String {
        let mut formula_string = String::new();
        for (i, fragment) in self.rolls_formula.iter().enumerate() {
            if match_token(fragment) > 0 {
                formula_string.push_str(format!("{} ", fragment).as_ref());
                continue;
            }

            if i == self.rolls_formula.len() - 1 {
                formula_string.push_str(format!("[{}]", fragment).as_ref());
                break;
            }

            formula_string.push_str(format!("[{}] ", fragment).as_ref());
        }
        return formula_string;
    }

    /// Returns a infix formatted String showing the formula with the original dice notation instead of the rolled result.
    pub fn get_rolls_formula_string_as_infix(&self) -> String {
        return parse_into_infix(self.rolls_formula.clone()).replace("( ", "[").replace(" )", "]");
    }
}

#[derive(Clone, Copy)]
struct DiceRoll {
    sides: i32,
    result: i32,
}

/// Returns a DiceRolls object based on the provided formula.
///
/// # Arguments
/// * `input` - A string that provides the dice notation to work off.
pub fn roll(input: String) -> Result<DiceRolls, Box<std::error::Error>> {
    let formula_vector = parse_into_rpn(input.trim().as_ref());
    return resolve_rolls_vector(formula_vector);
}

fn resolve_rolls_vector(rolls_vector: Vec<String>) -> Result<DiceRolls, Box<std::error::Error>> {
    let mut formula_vector: Vec<String> = Vec::new();
    let mut formula_vector_with_rolls: Vec<String> = Vec::new();
    let mut dice_rolls: Vec<DiceRoll> = Vec::new();

    for element in rolls_vector {
        // Ignore if element is recognised as a token.
        if match_token(element.as_ref()) > 0 {
            formula_vector.push(element.clone());
            formula_vector_with_rolls.push(element);
            continue;
        }

        let roll = resolve_roll_fragment(element.as_ref())?;

        for i_roll in roll.clone().rolls {
            dice_rolls.push(i_roll);
        }

        formula_vector.push(roll.get_sum_of_rolls().to_string());
        formula_vector_with_rolls.push(element);
    }

    return Ok(DiceRolls {
        rolls: dice_rolls,
        formula: formula_vector,
        rolls_formula: formula_vector_with_rolls,
    });
}

fn resolve_roll_fragment(input_fragment: &str) -> Result<DiceRolls, Box<std::error::Error>> {
    let mut rng = thread_rng();
    let mut dice_count_str = String::new();
    let mut dice_sides_str = String::new();
    let mut d_switch: bool = false;
    let mut dice_rolls: Vec<DiceRoll> = Vec::new();
    let mut sum: i32 = 0;
    let dice_count: i32;
    let dice_sides: i32;

    if input_fragment.parse::<i32>().is_ok() {
        let current_roll = DiceRoll {
            sides: 0,
            result: input_fragment.parse::<i32>().unwrap(),
        };

        dice_rolls.push(current_roll);
        sum += current_roll.result;
    } else {
        for (i, c) in input_fragment.chars().enumerate() {
            if !d_switch {
                if c.to_string() == "d" {
                    d_switch = true;
                    if i == 0 {
                        dice_count_str.push_str("1");
                    }
                    continue;
                }
                dice_count_str.push(c);
            } else {
                dice_sides_str.push(c);
            }
        }

        dice_count = dice_count_str.parse::<i32>()?;
        let dice_sides_result = dice_sides_str.parse::<i32>();
        if dice_sides_result.is_ok() {
            dice_sides = dice_sides_result.unwrap();            
        } else if match_token(dice_sides_str.as_ref()) == -3 {
            dice_sides = 100;
        } else {
            return Err(Box::new(dice_sides_result.unwrap_err()));
        }
                
        for _ in 0..dice_count {
            let result = {
                // gen_range(low, high) generates numbers in the range [low, high), 
                // so the high number must be one higher than the highest number 
                // that would appear on the die
                if dice_sides == 1 {
                    // Support "one sided" boolean dice                    
                    rng.gen_range(0, 2)
                } else {
                    // Support multi-sided dice
                    rng.gen_range(1, dice_sides + 1)
                }
            };
            let current_roll = DiceRoll {
                sides: dice_sides,
                result,
            };

            dice_rolls.push(current_roll);
            sum += current_roll.result;
        }
    }

    return Ok(DiceRolls {
        rolls: dice_rolls,
        formula: vec![sum.to_string()],
        rolls_formula: vec![input_fragment.to_string()],
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roll_from_string() {
        println!();
        let roll0 = roll("2d4".to_string()).unwrap();
        println!("Rolls:             {}", roll0.get_rolls_string());
        println!("RPN Formula:       {}", roll0.get_formula_string_as_rpn());
        println!("Formula:           {}", roll0.get_formula_string_as_infix());
        println!("RPN Rolls Formula: {}", roll0.get_rolls_formula_string_as_rpn());
        println!("Rolls Formula:     {}", roll0.get_rolls_formula_string_as_infix());
        println!("Result:            {}", roll0.get_result());
        println!();

        let roll1 = roll("(2d6 - 1d8) * (3d4 + 4d12)".to_string()).unwrap();
        println!("Rolls:             {}", roll1.get_rolls_string());
        println!("RPN Formula:       {}", roll1.get_formula_string_as_rpn());
        println!("Formula:           {}", roll1.get_formula_string_as_infix());
        println!("RPN Rolls Formula: {}", roll1.get_rolls_formula_string_as_rpn());
        println!("Rolls Formula:     {}", roll1.get_rolls_formula_string_as_infix());
        println!("Result:            {}", roll1.get_result());
        println!();

        let roll2 = roll("3d% + d%".to_string()).unwrap();
        println!("Rolls:             {}", roll2.get_rolls_string());
        println!("RPN Formula:       {}", roll2.get_formula_string_as_rpn());
        println!("Formula:           {}", roll2.get_formula_string_as_infix());
        println!("RPN Rolls Formula: {}", roll2.get_rolls_formula_string_as_rpn());
        println!("Rolls Formula:     {}", roll2.get_rolls_formula_string_as_infix());
        println!("Result:            {}", roll2.get_result());
        println!();

        let roll3 = roll("d100 / 15".to_string()).unwrap();
        println!("Rolls:             {}", roll3.get_rolls_string());
        println!("RPN Formula:       {}", roll3.get_formula_string_as_rpn());
        println!("Formula:           {}", roll3.get_formula_string_as_infix());
        println!("RPN Rolls Formula: {}", roll3.get_rolls_formula_string_as_rpn());
        println!("Rolls Formula:     {}", roll3.get_rolls_formula_string_as_infix());
        println!("Result:            {}", roll3.get_result());
        println!();

        let roll4 = roll("1d4 + 2d6 * 3d2 / 4d8 + (2d6 + 3d8) - 16 * (1 / 1d4)".to_string()).unwrap();
        println!("Rolls:             {}", roll4.get_rolls_string());
        println!("RPN Formula:       {}", roll4.get_formula_string_as_rpn());
        println!("Formula:           {}", roll4.get_formula_string_as_infix());
        println!("RPN Rolls Formula: {}", roll4.get_rolls_formula_string_as_rpn());
        println!("Rolls Formula:     {}", roll4.get_rolls_formula_string_as_infix());
        println!("Result:            {}", roll4.get_result());
        println!();
    }
}