WeightedRandom.Dice (weighted_random v1.0.0-alpha.1)

Copy Markdown View Source

Implement standard dice notation with ~d{num_dice, sides, optional_modifier}

alias WeightedRandom.Dice
import Dice

# This creates 4 x 6-sided dice
# In standard dice notation this would be written as "4d6"
d = ~d{4, 6}

Now let's make the number 2 have more weight Dice always use outcome_type: :value, not :index, so the target is 2

weights = [%{target: 2, amount: 50}]
d = Dice.add_weight(d, weights)

# Always remember to roll again so the new weight takes effect.
d = Dice.roll(d)

IO.inspect(Dice.results(d), label: "results")
# => [2, 2, 3, 2]
d.total
# => 9

Summary

Functions

Adds weight to ALL dice in the Dice struct.

Take a list of Dice structs, and combine them without rerolling

Directly create a Dice struct.

Given some dice, return a list showing the result of each one.

Takes a Dice struct and rerolls it.

Convenience sigil for creating dice

Types

t()

@type t() :: %WeightedRandom.Dice{
  dice: [
    %WeightedRandom.Die{
      preprocessed: term(),
      result: term(),
      sides: term(),
      weights: term()
    }
  ],
  modifier: integer(),
  subtotal: integer(),
  total: integer()
}

Functions

add_weight(dice, weight)

Adds weight to ALL dice in the Dice struct.

Examples

iex> :rand.seed(:exsss, {205, 301, 402})
iex> d = ~d{10, 20} 
iex> Enum.map(d.dice, &(&1.result))
[17, 1, 17, 11, 12, 13, 17, 13, 14, 3]
iex> d.total
118
iex> d = Dice.add_weight(d, [%{target: 2, weight: 50}])
iex> d = Dice.roll(d)
iex> Enum.map(d.dice, &(&1.result))
[10, 2, 2, 2, 2, 2, 2, 2, 2, 2]
iex> d.total
28

merge_dice(list)

Take a list of Dice structs, and combine them without rerolling

merge_dice(dice1, dice2)

new(body)

Directly create a Dice struct.

results(dice)

@spec results(dice :: t()) :: [integer()]

Given some dice, return a list showing the result of each one.

roll(d)

Takes a Dice struct and rerolls it.

Examples

iex> :rand.seed(:exsss, {200, 301, 402})
iex> dice = ~d{2, 12}
iex> dice.total
12
iex> Dice.roll(dice).total
20

sigil_d(str, opts \\ [])

Convenience sigil for creating dice

Examples

iex> :rand.seed(:exsss, {100, 101, 102})
iex> d = ~d{4, 6, 1} # Equal to 4d6+1 in standard dice notation
iex> [die1 | _] = d.dice
iex> die1.sides
6
iex> die1.result
2
iex> d.subtotal
9
iex> d.total
10