dicenotation/rolling/
mod.rs

1// Copyright 2018 Mattias Cibien
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use rand;
9use rand::distributions::range::SampleRange;
10use rand::Rng;
11use super::DiceData;
12
13use num_traits::int::PrimInt;
14use num_traits::zero;
15// TODO: not sure if this is correct
16use num_iter::range;
17use num_traits::one;
18
19pub fn roll<T>(dice_data: DiceData<T>) -> T
20where
21    T: PrimInt + SampleRange,
22{
23    let mut rng = rand::thread_rng();
24
25    roll_with_fn(dice_data, |a, b| { rng.gen_range(a,b) })
26}
27
28pub fn roll_with_fn<T,F>(dice_data: DiceData<T>, mut function: F) -> T
29where
30    T: PrimInt + SampleRange,
31    F: FnMut(T,T) -> T,
32{
33    let mut result: T = zero();
34
35    for _i in range(zero(), dice_data.num_dice) {
36        let roll: T = function(zero(), dice_data.num_faces) + one();
37        result = result + roll;
38    }
39
40    if dice_data.modifier {
41        result = result + dice_data.modifier_val;
42    } else {
43        result = result - dice_data.modifier_val;
44    }
45
46    result
47}
48
49#[cfg(test)]
50mod test;