Skip to main content

rpg_dice_roller/
lib.rs

1//! Roll dice with modifiers and apply expressions to them.
2//!
3//! ```rust
4//! # use rpg_dice_roller::{roll, roll_with, Dice, DiceKind, Modifier};
5//! # use rand::rngs::StdRng;
6//! # use rand::SeedableRng;
7//! #
8//! # fn main() -> Result<(), String> {
9//! // Roll 3 d20, make the minimum value 5, keep the lowest 2 rolls.
10//! let rolled = roll("3d20min5kl2")?;
11//! println!("{rolled} = {}", rolled.value()); // [6, 5^, 17d] = 11
12//!
13//! // Use a custom Rng that implements the rand::Rng trait
14//! let mut rng = StdRng::seed_from_u64(1);
15//! let rolled = roll_with("3d200", &mut rng)?;
16//! println!("{rolled} = {}", rolled.value()); // [165, 195, 160] = 520
17//!
18//! // Create Dice directly without parsing
19//! let dice = Dice::new(5, DiceKind::Standard(8), &[Modifier::Min(5)]);
20//! let rolled = dice.roll_all();
21//! println!("{rolled} = {}", rolled.value()); // [8, 6, 5^, 8, 5] = 32
22//!
23//! let rolled = dice.roll_once();
24//! println!("{rolled} = {}", rolled.value()); // [8] = 8
25//!
26//! # Ok(())
27//! # }
28//! ```
29
30mod evaluate;
31mod parse;
32
33pub use evaluate::expression::RolledExpression;
34pub use parse::{
35    ComparePoint, Dice, DiceKind, ExplodingKind, Expression, KeepKind, MathFn1, MathFn2, Modifier,
36};
37
38/// Parses the notation returning the parsed abstract syntax tree without
39/// rolling the dice.
40pub fn parse(notation: &str) -> Result<Expression, String> {
41    Expression::parse(notation)
42}
43
44/// Parses the notation returning the result of rolling all the dice parsed.
45pub fn roll(notation: &str) -> Result<RolledExpression, String> {
46    let expression = Expression::parse(notation)?;
47    Ok(expression.roll(&mut rand::thread_rng()))
48}
49
50/// Same as `roll()` but allows you to choose the rng you prefer to use.
51pub fn roll_with(notation: &str, rng: &mut impl rand::Rng) -> Result<RolledExpression, String> {
52    let expression = Expression::parse(notation)?;
53    Ok(expression.roll(rng))
54}