ExDiceRoller v1.0.0-rc.2 ExDiceRoller.Compilers.Roll View Source

Handles compiling dice roll expressions.

iex> expr = "1d6"
"1d6"
iex> {:ok, tokens} = ExDiceRoller.Tokenizer.tokenize(expr)
{:ok, [{:int, 1, '1'}, {:roll, 1, 'd'}, {:int, 1, '6'}]}
iex> {:ok, parse_tree} = ExDiceRoller.Parser.parse(tokens)
{:ok, {:roll, 1, 6}}
iex> fun = ExDiceRoller.Compilers.Roll.compile(parse_tree)
iex> fun.([])
3
iex> fun.([])
2

Exploding Dice

Some systems use a dice mechanic known as ‘exploding dice’. The mechanic works as follows:

  1. a multi-sided die, in this case a six-sided die, is rolled
  2. if the value is anything other than six, they record the result and skip to step 5
  3. if the value is six, the result is recorded, and the die is rolled again
  4. steps 1 and 3 are repeated until step 2 is reached
  5. the sum total result of all rolls is recorded and used

You can utilize this mechanic by specifying the :explode option for ExDiceRoller.roll/2 calls, or specifying the e flag when using the ~a sigil. This option can be used with any ExDiceRoller roll option.

It should also be noted that the exploding dice mechanic is not applied to a one-sided die, since that would result in an infinite loop.

Examples:

iex> expr = "1d6"
"1d6"
iex> {:ok, tokens} = ExDiceRoller.Tokenizer.tokenize(expr)
{:ok, [{:int, 1, '1'}, {:roll, 1, 'd'}, {:int, 1, '6'}]}
iex> {:ok, parse_tree} = ExDiceRoller.Parser.parse(tokens)
{:ok, {:roll, 1, 6}}
iex> fun = ExDiceRoller.Compilers.Roll.compile(parse_tree)
iex> fun.(opts: [:explode])
3
iex> fun.(opts: [:explode])
2
iex> fun.(opts: [:explode])
10

iex> import ExDiceRoller.Sigil
iex> ~a/1d10/re
9
iex> ~a/1d10/re
14

Keeping Dice Rolls

A batch of dice being rolled can be returned as either their sum total, or as individual results. The former is the default handling of rolls by ExDiceRoller. The latter, keeping each die rolled, requires the option :keep. Note that a list of die roll results will be returned when using the :keep option.

iex> expr = "5d6"
"5d6"
iex> {:ok, tokens} = ExDiceRoller.Tokenizer.tokenize(expr)
{:ok, [{:int, 1, '5'}, {:roll, 1, 'd'}, {:int, 1, '6'}]}
iex> {:ok, parse_tree} = ExDiceRoller.Parser.parse(tokens)
{:ok, {:roll, 5, 6}}
iex> fun = ExDiceRoller.Compilers.Roll.compile(parse_tree)
iex> fun.(opts: [:keep])
[3, 2, 6, 4, 5]

Kept Rolls and List Comprehensions

Kept rolls also support list comprehensions. See ExDiceRoller.ListComprehension for more information.