d20
D20 is a simple crate designed to evaluate roll expressions. A roll expression is an english-language string that reflects the intent of a dungeon or game master to perform a particular roll.
For example, in a tabletop game you may frequently hear phrases like "roll 2d10", or "roll 3d6 and add 5". These are roll expressions, and the components within them are what we call die roll terms. A die roll term is either a term that calls for the rolling of an n-sided die x times (e.g. 3d6) or a modifier that simply adds or subtracts a constant value from the larger expression.
Examples of valid roll expressions include:
- 3d6
- 2d10 + 5
- 1d20-3
- +6
- -2
- 3d10+5d100-21+7
Roll expressions can have arbitrary length and complexity, and it is perfectly legal for the final result of a roll expression to be negative after applying modifiers.
Usage
let r = roll_dice.unwrap;
assert!;
let r = roll_dice.unwrap;
assert_eq!;
// Malformed expressions return a descriptive error instead of panicking.
assert!;
Every failure mode is reported through the d20::D20Error enum, and no input —
however malformed — will ever panic. Counts, sides, and modifiers are supported
up to the documented MAX_DICE / MAX_SIDES / MAX_MODIFIER limits; values
beyond them return a clear error rather than overflowing.
Inspecting Results
A Roll exposes the per-term breakdown via terms: Vec<TermResult>. Each
TermResult is either a Dice { multiplier, sides, rolls } recording the
individual die results, or a Modifier(i32) constant — so the data is
self-describing (modifiers are not faked as single-element rolls):
use TermResult;
let r = roll_dice.unwrap;
for term in &r.terms
assert_eq!;
Iterating Roll
A valid Roll can be turned into an open-ended iterator via its rolls() method, providing successive
rolls of the given die roll expression.
Note that it will be necessary to constrain the iterator via take(n).
use *;
let raw_stats: = roll_dice.unwrap.rolls.take.collect;
println!;
println!;
println!;
println!;
println!;
println!;
println!;
Deterministic Rolls
For reproducible results (tests, replays), supply your own RNG via
roll_dice_with_rng / roll_range_with_rng:
use SeedableRng;
use StdRng;
let mut rng = seed_from_u64;
let a = roll_dice_with_rng.unwrap;
let b = roll_dice_with_rng.unwrap;
assert_eq!; // same seed => same roll
Range Rolls
If you are less concerned about dice rolls and require only a random number within a given range, roll_range()
will do just that.
let rg = roll_range.unwrap;
assert!;