A simple and flexible Elixir library for rolling dice with configurable implementations by Backgammon Galaxy.
This library has been extracted from the main codebase of Backgammon Galaxy to make the dice rolling functionality available as an open source component. The implementation has been battle-tested in production and provides a robust, secure, and configurable solution for dice rolling in Elixir applications.
The package is available on GitHub. You can install it by adding dice_roller to your list of dependencies in mix.exs:
def deps do
[
{:dice_roller, git: "https://github.com/Backgammon-Galaxy/dice_roller.git", tag: "v1.0.0"}
]
endWe recommend using tags for version management to ensure reproducible builds.
# Roll two dice (default)
DiceRoller.roll()
# => [3, 5]
# Roll two dice allowing doubles
DiceRoller.roll(false)
# => [2, 2]
# Roll two dice excluding doubles
DiceRoller.roll(true)
# => [4, 1]The library uses a behaviour pattern allowing you to configure different implementations.
By default, the library uses DiceRoller.CryptoRandom which provides cryptographically secure random dice rolls.
The implementation can be configured in your config files:
# config/config.exs
config :dice_roller, impl: DiceRoller.CryptoRandom
# config/test.exs (for testing)
config :dice_roller, impl: DiceRoller.CryptoRandom
# config/prod.exs (for production)
config :dice_roller, impl: DiceRoller.CryptoRandomYou can also change the implementation at runtime:
# Temporarily use a different implementation
original_impl = Application.get_env(:dice_roller, :impl)
Application.put_env(:dice_roller, :impl, DiceRoller.CryptoRandom)
# Use the dice roller
result = DiceRoller.roll()
# Restore original implementation
Application.put_env(:dice_roller, :impl, original_impl)-
Uses
:crypto.strong_rand_bytes/1for cryptographically secure randomness -
Suitable for production use
-
Excludes doubles when
exclude_doubles: trueWhen
exclude_doubles: true, this function is specifically designed for Backgammon match initialization where:- First dice value determines the host player's opening move
- Second dice value determines the guest player's opening move
- Both players must have different opening moves (no doubles allowed)
- Ensures fair and varied opening moves for both players
You can create your own implementations by implementing the DiceRoller.Behaviour:
defmodule MyCustomDiceRoller do
@behaviour DiceRoller.Behaviour
def roll(exclude_doubles \\ false) do
# Your custom implementation
[roll_single_dice(), roll_single_dice()]
end
defp roll_single_dice do
# Your custom dice rolling logic
end
end- Elixir 1.17+
- Erlang 26.0+
-
Install dependencies:
mix deps.get
-
Run tests:
mix test -
Generate documentation:
mix docs
This project uses asdf for version management. Install the required versions:
asdf installThis project is licensed under the MIT License - see the LICENSE file for details.