### Install d20tek-dicenotation NuGet Package
Source: https://github.com/d20tek/dicenotation/blob/main/README.md
Use this command in the Package Manager Console to install the library.
```powershell
PM > Install-Package d20tek-dicenotation -Version 5.1.1
```
--------------------------------
### Install DiceCli Globally
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Installs the DiceCli tool globally using the .NET CLI. This command makes the 'dice-cli' command available in any terminal session.
```bash
dotnet tool install --global DiceCli
```
--------------------------------
### Run DiceCli Interactively
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Starts an interactive session with DiceCli. In this mode, you can continuously enter dice notations without re-typing the base command.
```bash
dice-cli
```
--------------------------------
### Update DiceCli Globally
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Updates the globally installed DiceCli tool to the latest version. Run this command to ensure you have the most recent features and bug fixes.
```bash
dotnet tool update --global DiceCli
```
--------------------------------
### Roll Dice from UI Input
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10.md
Handles UI input for dice number, sides, and modifier to create and roll a Dice expression. Requires setup of UI elements like Combobox and NumericUpDown.
```csharp
///
/// Click handler for the Roll button for basic dice definition.
///
/// sender
/// event args
private void RollButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// setup the dice expression
DiceType diceType = (DiceType)this.DiceTypeCombobox.SelectedItem;
var expression = DiceExpression.Create()
.AddDice(diceType.DiceSides, (int)this.DiceNumberNumeric.Value)
.AddConstant((int)this.DiceModifierNumeric.Value);
// roll the dice and save the results
DiceResult result = this.diceService.Roll(expression, this.dieRoller);
this.DiceRollResults.Insert(0, result);
}
```
--------------------------------
### Handle Dice Roll Input in MVC Controller
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWebMvc.md
Controller actions for handling GET and POST requests to create dice rolls. Manages session state for roll results.
```csharp
///
/// Creates a die roll from dice expression.
/// GET: Roll/Create
///
/// View
public ActionResult Create()
{
this.vmDiceRoller.RollResults = this.Session[CurrentDiceResultsListSessionKey] as IList ?? new List();
return this.View(this.vmDiceRoller);
}
///
/// Creates a die roll from dice expression.
/// POST: Roll/Create
///
/// Forms collection.
/// View
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
this.vmDiceRoller.RollResults = this.Session[CurrentDiceResultsListSessionKey] as IList ?? new List();
this.vmDiceRoller.RollCommand(collection[DiceExpressionFormKey]);
this.Session[CurrentDiceResultsListSessionKey] = this.vmDiceRoller.RollResults;
return this.View(this.vmDiceRoller);
}
catch
{
return this.View(this.vmDiceRoller);
}
}
```
--------------------------------
### DiceCli Help Information
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Displays the usage instructions and available commands for DiceCli. Use this to understand the tool's capabilities and syntax.
```bash
d20> --help
USAGE:
dice-cli [OPTIONS] [COMMAND]
OPTIONS:
-h, --help Prints help information
-v, --version Prints version information
COMMANDS:
start Starts an interactive prompt for this sample CLI
roll Rolls the dice described by the notation string
notation Display details about how dice notations are defined and written
favorites Commands to manage and use favorite rolls
```
--------------------------------
### Run Dice Notation Command-Line Tool
Source: https://github.com/d20tek/dicenotation/blob/main/docs/BuildProject.md
Execute the command-line tool to test dice notation parsing and evaluation. Use different arguments to explore functionality.
```bash
dotnet dicenotation.dll d20+3
```
```bash
dotnet dicenotation.dll 4d6k3 -v
```
--------------------------------
### Setting Up IDieRollers With Roll Tracker
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10Tracker.md
Instantiate a DieRollTracker and pass it to the IDieRoller constructor to enable roll tracking. Pass null to disable tracking.
```csharp
IDieRollTracker diceTracker = new DieRollTracker();
IDieRoller roller = null;
roller = new RandomDieRoller(tracker);
DiceResult result = new Dice().Roll("d20+3");
```
--------------------------------
### DiceCli Favorites Command Help
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Displays detailed help for the 'favorites' subcommand, outlining its usage for managing saved dice roll configurations.
```bash
d20> favorites -h
DESCRIPTION:
Commands to manage and use favorite rolls
USAGE:
dice-cli favorites [OPTIONS]
EXAMPLES:
dice-cli favorites list
dice-cli favorites add -i attack-roll -n Attack (Longsword) -e 1d20+5
dice-cli favorites edit -i attack-roll -n Attack (Short sword) -e 1d20+7
dice-cli favorites delete -i damage-roll
dice-cli favorites roll -i attack-roll
OPTIONS:
-h, --help Prints help information
COMMANDS:
list Lists all favorite rolls
add Adds a new favorite roll
edit Edits an existing favorite roll
delete Removes a favorite roll by name
roll Rolls a favorite roll by name
```
--------------------------------
### Loading Tracker Data from JSON
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10Tracker.md
Load previously saved frequency data from a JSON text file back into the service's memory using LoadFromJsonAsync.
```csharp
// load any cached dice frequency data.
AppServices appServices = AppServices.Instance;
string jsonText = await appServices.FileService.ReadFileAsync(Constants.DieFrequencyDataFilename);
await appServices.DiceFrequencyTracker.LoadFromJsonAsync(jsonText);
```
--------------------------------
### Persisting Tracker Data to JSON
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10Tracker.md
Save the frequency data to a text file in JSON format using the ToJsonAsync method and a file service.
```csharp
string jsonText = await this.diceFrequencyTracker.ToJsonAsync();
await this.fileService.WriteFileAsync(Constants.DieFrequencyDataFilename, jsonText);
```
--------------------------------
### Use Different Die Rollers
Source: https://context7.com/d20tek/dicenotation/llms.txt
Select from built-in die rollers (Random, Crypto, MathNet, Constant) or implement your own by inheriting from IDieRoller. This allows for different random number generation strategies or deterministic testing.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
IDice dice = new Dice();
string notation = "4d6k3";
// 1. RandomDieRoller — uses System.Random (default)
var random = new RandomDieRoller();
Console.WriteLine(dice.Roll(notation, random).Value);
// 2. CryptoDieRoller — uses System.Security.Cryptography.RandomNumberGenerator
var crypto = new CryptoDieRoller();
Console.WriteLine(dice.Roll(notation, crypto).Value);
// 3. MathNetDieRoller — uses MathNet.Numerics Mersenne Twister by default
var mathNet = new MathNetDieRoller();
Console.WriteLine(dice.Roll(notation, mathNet).Value);
// 4. ConstantDieRoller — always returns the same value (ideal for unit tests)
var constant = new ConstantDieRoller(rollValue: 3);
DiceResult testResult = dice.Roll("4d6k3+2", constant);
// 4 dice all roll 3, keep best 3 → 3+3+3+2 = 11
Console.WriteLine(testResult.Value); // 11 (deterministic)
// 5. Custom roller — implement IDieRoller
public class MaxDieRoller : IDieRoller
{
public int Roll(int sides, int? factor = null) => sides; // always max
}
IDieRoller maxRoller = new MaxDieRoller();
Console.WriteLine(dice.Roll("2d6+1", maxRoller).Value); // 13 (6+6+1)
```
--------------------------------
### Querying Frequency Data with LINQ
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10Tracker.md
Retrieve and filter frequency data using an IList and LINQ queries. Performance-intensive methods are asynchronous to maintain application responsiveness.
```csharp
///
/// Called when navigated to this page.
///
/// event args
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.UpdateBusyProgress(true);
this.frequencyData = await new DiceFrequencyTracker().GetFrequencyDataViewAsync();
this.DataContext = this;
if (this.RollerTypes.Count == 1)
{
this.RollerTypesCombobox.SelectedIndex = 0;
}
this.UpdateBusyProgress(false);
}
///
/// Updates the display state of the busy progress indicator.
///
/// Is the app busy
private void UpdateBusyProgress(bool busy)
{
this.BusyProgressBar.Visibility = busy ? Visibility.Visible : Visibility.Collapsed;
this.ShowStatsButton.IsEnabled = !busy;
}
///
/// Updates the frequency data based on the filters selected
/// on this page.
///
private void UpdateFrequencyData()
{
string selectedRollerType = this.RollerTypesCombobox.SelectedValue as string;
string selectedDiceSides = this.DiceSidesCombobox.SelectedValue as string;
var list = from d in this.frequencyData
where d.RollerType == selectedRollerType && d.DieSides == selectedDiceSides
select d;
this.Items = list.ToList();
this.StatsListView.ItemsSource = this.Items;
}
```
--------------------------------
### Configure Dice Notation Defaults
Source: https://context7.com/d20tek/dicenotation/llms.txt
Customize library-wide defaults for die sides, result bounds, and the default die roller using DiceConfiguration. This affects how dice notation is parsed and rolled.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
// Custom configuration: crypto roller, d6 default, minimum result of 1
var config = new DiceConfiguration(
dieSides: 6,
boundedMinResult: 1,
hasBoundedResult: true,
dieRoller: new CryptoDieRoller());
IDice dice = new Dice(config);
// "3d" uses default 6-sided die because DefaultDieSides = 6
DiceResult result = dice.Roll("3d+5");
Console.WriteLine(result.Value); // 8–23, never below 1
// Change defaults at runtime
config.SetDefaultDieSides(8);
config.SetBoundedMinimumResult(0);
config.SetHasBoundedResult(false);
config.SetDefaultDieRoller(new RandomDieRoller());
Console.WriteLine(config.DefaultDieSides); // 8
Console.WriteLine(config.HasBoundedResult); // False
Console.WriteLine(config.BoundedResultMinimum); // 0
```
--------------------------------
### Track Individual Dice Rolls with DieRollTracker
Source: https://context7.com/d20tek/dicenotation/llms.txt
Use DieRollTracker to record every individual die roll. Set TrackerDataLimit to manage memory. Pass the tracker to a roller and roll dice to gather data. Data can be retrieved asynchronously, filtered, and analyzed for frequency. Supports JSON serialization for persistence.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
var tracker = new DieRollTracker();
tracker.TrackerDataLimit = 1000; // keep last 1000 rolls
// Pass tracker to the roller constructor
var roller = new RandomDieRoller(tracker);
IDice dice = new Dice();
// Roll many times to gather data
for (int i = 0; i < 50; i++)
dice.Roll("2d6", roller);
// Retrieve all recorded rolls (optionally filter by roller type or die sides)
IList allRolls = await tracker.GetTrackingDataAsync();
IList d6Rolls = await tracker.GetTrackingDataAsync(dieSides: "6");
Console.WriteLine($"Total rolls recorded: {allRolls.Count}"); // 100 (50 × 2d6)
foreach (var roll in d6Rolls.Take(3))
Console.WriteLine($"{roll.RollerType} | d{roll.DieSides} → {roll.Result} at {roll.Timpstamp}");
// RandomDieRoller | d6 → 4 at 2024-06-01 10:23:01
// Frequency analysis
IList freq = await tracker.GetFrequencyDataViewAsync();
foreach (var entry in freq.Where(f => f.DieSides == "6"))
Console.WriteLine($"d6={entry.Result}: {entry.Count} times ({entry.Percentage}%)");
// Persist and restore
string json = await tracker.ToJsonAsync();
await tracker.LoadFromJsonAsync(json);
tracker.Clear();
```
--------------------------------
### Build Dice Expressions with DiceExpression
Source: https://context7.com/d20tek/dicenotation/llms.txt
Use the fluent DiceExpression builder to construct reusable dice expressions. Supports standard dice, fudge dice, multipliers, keep/drop selectors, and exploding dice.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
IDice dice = new Dice();
var roller = new RandomDieRoller();
// Standard ability score generation: 4d6 keep best 3
var abilityScore = DiceExpression.Create()
.AddDice(sides: 6, numberDice: 4, choose: 3);
// Exploding dice: 6d6! (reroll on max result)
var exploding = DiceExpression.Create()
.AddDice(sides: 6, numberDice: 6, exploding: 6);
// Fudge/FATE dice: 4f (values -1, 0, +1)
var fudge = DiceExpression.Create()
.AddFudgeDice(numberDice: 4);
// Complex expression: (2d10 + d6) with constant modifier
var complex = DiceExpression.Create()
.AddDice(sides: 10, numberDice: 2)
.AddDice(sides: 6)
.AddConstant(-2);
Console.WriteLine(abilityScore.ToString()); // 4d6k3
Console.WriteLine(exploding.ToString()); // 6d6!6
Console.WriteLine(fudge.ToString()); // 4f
Console.WriteLine(complex.ToString()); // 2d10 + d6 - 2
// Concat two expressions
var combined = DiceExpression.Create().AddDice(6).Concat(
DiceExpression.Create().AddConstant(4));
Console.WriteLine(combined.ToString()); // d6 + 4
// Clear and reuse
abilityScore.Clear().AddDice(sides: 8, numberDice: 3);
Console.WriteLine(dice.Roll(abilityScore, roller).Value); // 3-24
```
--------------------------------
### Format Dice Roll Results with HTML Helper
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWebMvc.md
An HTML helper extension method to format a list of term results into a string representation using a converter from d20Tek.DiceNotation.
```csharp
///
/// Html helper class to format term results lists.
///
public static class TermResultListHelper
{
private static TermResultListConverter converter = new TermResultListConverter();
///
/// Formats the specified list of term results into the corresponding text format.
///
/// Html helper
/// Term results to convert
/// Text representation for the list.
public static string DisplayResultsFor(this HtmlHelper helper, IReadOnlyList results)
{
string result = (string)converter.Convert(results, typeof(string), null, "en-us");
return result;
}
}
```
--------------------------------
### Programmatic Dice Expression Creation
Source: https://github.com/d20tek/dicenotation/blob/main/README.md
Build dice expressions using a fluent API. This is useful for creating complex dice rolls in code.
```csharp
IDice dice = new Dice();
// equivalent of dice expression: 4d6k3 + d8 + 5
var expression = DiceExpression.Create().AddDice(6, 4, choose: 3)
.AddDice(8)
.AddConstant(5);
DiceResult result = dice.Roll(expression, new RandomDieRoller());
Console.WriteLine("Roll result = " + result.Value);
```
--------------------------------
### Roll a Single Dice String
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Executes a dice roll using a specified notation string. This is a basic command for rolling dice directly from the command line.
```bash
dice-cli roll "1d20+5"
```
--------------------------------
### Track Dice Roll Frequencies Efficiently with AggregateRollTracker
Source: https://context7.com/d20tek/dicenotation/llms.txt
Use AggregateRollTracker for memory-efficient tracking of only aggregated roll counts. Ideal for long-running applications. Initialize the tracker, pass it to a roller, and perform rolls. Retrieve aggregated statistics synchronously. Supports synchronous JSON round-tripping.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
var aggTracker = new AggregateRollTracker();
var roller = new CryptoDieRoller(aggTracker);
IDice dice = new Dice();
for (int i = 0; i < 200; i++)
dice.Roll("3d6", roller);
IList stats = aggTracker.GetFrequencyDataView();
foreach (var s in stats.OrderBy(x => x.Result))
Console.WriteLine($"d{s.DieSides}=${s.Result}: {s.Count}x ({s.Percentage}%)");
// d6=1: 31x (15.5%)
// d6=2: 28x (14.0%)
// ...
// JSON round-trip (synchronous)
string json = aggTracker.ToJson();
aggTracker.Clear();
aggTracker.LoadFromJson(json);
Console.WriteLine(aggTracker.GetFrequencyDataView().Count); // restored
```
--------------------------------
### Roll Dice from Notation String
Source: https://context7.com/d20tek/dicenotation/llms.txt
Parses and immediately evaluates a dice roll from a string. An optional IDieRoller can be provided; otherwise, the default configured roller is used. Handles basic rolls, complex expressions, and errors.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
using d20Tek.DiceNotation.Results;
IDice dice = new Dice();
IDieRoller roller = new RandomDieRoller();
// Basic attack roll: 1d20 + 4
DiceResult attackRoll = dice.Roll("d20+4", roller);
Console.WriteLine($"Attack roll: {attackRoll.Value}"); // e.g. Attack roll: 17
// Damage roll: 2d6 + 3
DiceResult damageRoll = dice.Roll("2d6+3", roller);
Console.WriteLine($"Damage: {damageRoll.Value}"); // e.g. Damage: 11
Console.WriteLine($"Expression: {damageRoll.DiceExpression}"); // 2d6+3
Console.WriteLine($"Breakdown: {damageRoll.RollsDisplayText}"); // e.g. [4, 6] + 3
// Error handling — invalid notation
DiceResult bad = dice.Roll("notdice", roller);
if (bad.HasError)
Console.WriteLine($"Error: {bad.Error}");
// Percentile dice
DiceResult percentile = dice.Roll("d%+5", roller);
Console.WriteLine($"Percentile: {percentile.Value}"); // 1-105
```
--------------------------------
### Dice Expression Parsing from String
Source: https://github.com/d20tek/dicenotation/blob/main/README.md
Parse and evaluate dice expressions directly from a string. This is a convenient way to handle dice notation.
```csharp
IDice dice = new Dice();
DiceResult result = dice.Roll("d20+4", new RandomDieRoller());
Console.WriteLine("Roll result = " + result.Value);
```
--------------------------------
### Roll Dice from Expression String
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10.md
Parses and rolls dice based on a provided dice expression string. Includes error handling for invalid expressions, displaying a message dialog upon failure. Requires a UI Textbox for input and a MessageDialog for errors.
```csharp
///
/// Click handler for the Roll button to handle dice expression rolls.
///
/// sender
/// event args
private async void RollExpressionButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
try
{
// roll the dice (based on dice expression string) and save the results.
DiceResult result = this.diceService.Roll(this.DiceExpressionTextbox.Text, this.dieRoller);
this.DiceRollResults.Insert(0, result);
}
catch (Exception ex)
{
// if there's an error in parsing the expression string, show an error message. string message = "There was a error parsing the dice expression: " +
this.DiceExpressionTextbox.Text +
"\r\nException Text: " + ex.Message +
"\r\nPlease correct the expression and try again.";
MessageDialog dialog = new MessageDialog(message, "Dice Parsing Error");
await dialog.ShowAsync();
}
}
```
--------------------------------
### XAML Resources and ListView ItemTemplate with Converters
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10.md
Defines XAML resources for DiceResultConverter and TermResultListConverter and uses them within a ListView's ItemTemplate to display dice roll results and individual rolls. Ensure the converter namespace is correctly mapped.
```xaml
...
```
--------------------------------
### Dice.Roll(string notation, IDieRoller? dieRoller = null)
Source: https://context7.com/d20tek/dicenotation/llms.txt
Parses a dice notation string and immediately evaluates a roll. An optional dieRoller argument selects the random source; if omitted, the default roller configured on DiceConfiguration is used.
```APIDOC
## Dice.Roll(string notation, IDieRoller? dieRoller = null)
### Description
Parses a dice notation string and immediately evaluates a roll. The optional `dieRoller` argument selects the random source; if omitted, the default roller configured on `DiceConfiguration` is used.
### Method
`Dice.Roll`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
using d20Tek.DiceNotation.Results;
IDice dice = new Dice();
IDieRoller roller = new RandomDieRoller();
// Basic attack roll: 1d20 + 4
DiceResult attackRoll = dice.Roll("d20+4", roller);
Console.WriteLine($"Attack roll: {attackRoll.Value}");
// Damage roll: 2d6 + 3
DiceResult damageRoll = dice.Roll("2d6+3", roller);
Console.WriteLine($"Damage: {damageRoll.Value}");
Console.WriteLine($"Expression: {damageRoll.DiceExpression}");
Console.WriteLine($"Breakdown: {damageRoll.RollsDisplayText}");
// Error handling — invalid notation
DiceResult bad = dice.Roll("notdice", roller);
if (bad.HasError)
Console.WriteLine($"Error: {bad.Error}");
// Percentile dice
DiceResult percentile = dice.Roll("d%+5", roller);
Console.WriteLine($"Percentile: {percentile.Value}");
```
### Response
#### Success Response (200)
`DiceResult` object containing the total value and a detailed breakdown of the roll.
#### Response Example
```json
{
"Value": 17,
"DiceExpression": "d20+4",
"RollsDisplayText": "[13] + 4",
"HasError": false,
"Error": null
}
```
```
--------------------------------
### Math Grouping in Dice Notation
Source: https://context7.com/d20tek/dicenotation/llms.txt
Notation for using parentheses to group mathematical operations within dice expressions.
```text
(1+2)d6+1 → (1+2)=3, then 3d6+1
```
```text
(2d10+2)x10 → roll 2d10+2, multiply result by 10
```
```text
4d6 x d10 → multiply 4d6 result by 1d10 result
```
--------------------------------
### Basic Dice Notation
Source: https://context7.com/d20tek/dicenotation/llms.txt
Standard dice roll notation including number of dice, sides, and simple modifiers.
```text
d6 → 1 six-sided die
```
```text
3d6 → 3 six-sided dice, summed
```
```text
d20+4 → 1d20 plus constant 4
```
```text
2d8-1 → 2d8 minus 1
```
```text
4d6x2 → 4d6 multiplied by 2
```
```text
6d6/3 → 6d6 divided by 3
```
```text
d% → percentile die (1–100)
```
```text
3d → 3 dice using default sides (d6)
```
--------------------------------
### Configuring Die Roll Tracker Data Limit
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWin10Tracker.md
Set the TrackerDataLimit property on the DieRollTracker to control the maximum number of rolls tracked in memory. The default is 250000.
```csharp
diceTracker.TrackerDataLimit = 25000;
```
--------------------------------
### Roll Dice from Fluent Expression
Source: https://context7.com/d20tek/dicenotation/llms.txt
Rolls a DiceExpression built programmatically using the fluent builder API. Useful for constructing complex dice rolls dynamically. Inspect individual term results after rolling.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
IDice dice = new Dice();
IDieRoller roller = new RandomDieRoller();
// Equivalent to: 4d6k3 + d8 + 5
DiceExpression expr = DiceExpression.Create()
.AddDice(sides: 6, numberDice: 4, choose: 3) // keep highest 3 of 4d6
.AddDice(sides: 8) // + 1d8
.AddConstant(5); // + 5
DiceResult result = dice.Roll(expr, roller);
Console.WriteLine($"Expression: {expr}"); // 4d6k3 + d8 + 5
Console.WriteLine($"Total: {result.Value}"); // e.g. Total: 19
// Inspect individual term results
foreach (var term in result.Results)
Console.WriteLine($" [{term.Type}] rolled {term.Value} × {term.Scalar}");
// Output:
// [DiceTerm] rolled 4 × 1
// [DiceTerm] rolled 3 × 1 <- dropped die, AppliesToResultCalculation = false
// [DiceTerm] rolled 7 × 1
// [DiceTerm] rolled 5 × 1
// [ConstantTerm] rolled 5 × 1
```
--------------------------------
### DiceRoller View Model for MVC
Source: https://github.com/d20tek/dicenotation/blob/main/docs/SampleWebMvc.md
ViewModel class to manage dice expression input, roll results, and perform dice rolling operations. Initializes services and dice rolling components.
```csharp
public class DiceRollerViewModel
{
#region Members
private IDice dice;
private IDieRoller dieRoller;
#endregion
///
/// Initializes a new instance of the class.
///
public DiceRollerViewModel()
{
AppServices services = AppServices.Instance;
this.dice = services.DiceService;
string rollerType = services.AppSettingsService.CurrentDieRollerType;
this.dieRoller = services.DieRollerFactory.GetDieRoller(rollerType, services.DiceFrequencyTracker);
}
#region Properties
///
/// Gets or sets the dice expression text.
///
[Display(Name = "Dice Expression")]
[Required]
public string DiceExpression { get; set; }
///
/// Gets or sets the list of roll results.
///
public IList RollResults { get; set; } = new List();
#endregion
#region Commands
///
/// Command method to roll the dice and save the results.
///
/// String expression to roll.
public void RollCommand(string expression)
{
this.DiceExpression = expression;
DiceResult result = this.dice.Roll(this.DiceExpression, this.dieRoller);
this.RollResults.Insert(0, result);
}
#endregion
}
```
--------------------------------
### Fudge / FATE Dice Notation
Source: https://context7.com/d20tek/dicenotation/llms.txt
Notation for Fudge or FATE dice, which have faces representing -1, 0, and +1.
```text
4f → 4 fudge dice
```
```text
3f+1 → 3 fudge dice plus 1
```
```text
6fk4 → 6 fudge dice, keep highest 4
```
--------------------------------
### Inspect Dice Roll Output with DiceResult
Source: https://context7.com/d20tek/dicenotation/llms.txt
The DiceResult object returned by IDice.Roll() provides the final value, term breakdowns, expression, and roller information. Iterate through the 'Results' property for per-term details, including whether they were counted or dropped. Check the 'HasError' property for parsing or roll failures.
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
using d20Tek.DiceNotation.Results;
IDice dice = new Dice();
DiceResult result = dice.Roll("4d6k3+5", new RandomDieRoller());
Console.WriteLine(result.Value); // Final total, e.g. 16
Console.WriteLine(result.DiceExpression); // "4d6k3+5"
Console.WriteLine(result.DieRollerUsed); // "d20Tek.DiceNotation.DieRoller.RandomDieRoller"
Console.WriteLine(result.RollsDisplayText);// Human-readable, e.g. "[2, 4, 5] (dropped: [1]) + 5"
Console.WriteLine(result.HasError); // false
// Iterate term results
foreach (TermResult term in result.Results)
{
string applies = term.AppliesToResultCalculation ? "counted" : "dropped";
Console.WriteLine($" {term.Type}: {term.Value} (scalar={term.Scalar}) [{applies}]");
}
// DiceTerm: 5 (scalar=1) [counted]
// DiceTerm: 4 (scalar=1) [counted]
// DiceTerm: 2 (scalar=1) [counted]
// DiceTerm: 1 (scalar=1) [dropped]
// ConstantTerm: 5 (scalar=1) [counted]
// Error result pattern
DiceResult err = dice.Roll("bad!!notation", new RandomDieRoller());
if (err.HasError)
Console.WriteLine($"Roll failed: {err.Error}"); // Roll failed:
```
--------------------------------
### Keep / Drop Dice Notation
Source: https://context7.com/d20tek/dicenotation/llms.txt
Notation for keeping or dropping dice based on their results.
```text
4d6k3 → roll 4d6, keep highest 3
```
```text
6d6p2 → roll 6d6, drop lowest 2
```
```text
4d6l1 → roll 4d6, keep lowest 1
```
--------------------------------
### Exploding Dice Notation
Source: https://context7.com/d20tek/dicenotation/llms.txt
Notation for dice that re-roll when a maximum or specific value is achieved.
```text
6d6! → roll 6d6, re-roll any result equal to max (6)
```
```text
4d8!7 → roll 4d8, re-roll any result >= 7
```
--------------------------------
### Dice.Roll(DiceExpression expression, IDieRoller? dieRoller = null)
Source: https://context7.com/d20tek/dicenotation/llms.txt
Rolls a DiceExpression built programmatically using the fluent builder API. Each call to AddDice or AddConstant appends a term to the expression.
```APIDOC
## Dice.Roll(DiceExpression expression, IDieRoller? dieRoller = null)
### Description
Rolls a `DiceExpression` built programmatically using the fluent builder API. Each call to `AddDice` or `AddConstant` appends a term to the expression.
### Method
`Dice.Roll`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
using d20Tek.DiceNotation;
using d20Tek.DiceNotation.DieRoller;
IDice dice = new Dice();
IDieRoller roller = new RandomDieRoller();
// Equivalent to: 4d6k3 + d8 + 5
DiceExpression expr = DiceExpression.Create()
.AddDice(sides: 6, numberDice: 4, choose: 3) // keep highest 3 of 4d6
.AddDice(sides: 8) // + 1d8
.AddConstant(5); // + 5
DiceResult result = dice.Roll(expr, roller);
Console.WriteLine($"Expression: {expr}");
Console.WriteLine($"Total: {result.Value}");
// Inspect individual term results
foreach (var term in result.Results)
Console.WriteLine($" [{term.Type}] rolled {term.Value} × {term.Scalar}");
```
### Response
#### Success Response (200)
`DiceResult` object containing the total value and a detailed breakdown of the roll.
#### Response Example
```json
{
"Value": 19,
"DiceExpression": "4d6k3 + d8 + 5",
"RollsDisplayText": "[4, 6, 5] + 3 + 7 + 5",
"HasError": false,
"Error": null,
"Results": [
{
"Type": "DiceTerm",
"Value": 4,
"Scalar": 1
},
{
"Type": "DiceTerm",
"Value": 3,
"Scalar": 1
},
{
"Type": "DiceTerm",
"Value": 7,
"Scalar": 1
},
{
"Type": "DiceTerm",
"Value": 5,
"Scalar": 1
},
{
"Type": "ConstantTerm",
"Value": 5,
"Scalar": 1
}
]
}
```
```
--------------------------------
### Roll a Saved Favorite Roll
Source: https://github.com/d20tek/dicenotation/blob/main/samples/DiceCli/README.md
Executes a previously saved favorite dice roll by its identifier. This allows for quick access to commonly used dice combinations.
```bash
dice-cli favorites roll "attack-roll'
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.