Skip to content

dice_roller

dice_roller

Dice roller module for rolling dice based on the nDn or Dn notation, supporting modifiers.

This module provides functionality for rolling dice using traditional RPG notations such as '3d6' (three six-sided dice) and '1d20+5' (one twenty-sided die plus a modifier of 5). It supports modifiers and the option to drop the lowest roll.

DiceRoll

Bases: namedtuple('RollResultBase', ['num_dice', 'num_sides', 'total', 'modifier', 'total_with_modifier', 'rolls'])

Represent the result of a dice roll.

This class is a named tuple containing details of a dice roll, including the number of dice, number of sides, base roll, modifier, total roll with modifier, and the individual rolls.

Attributes:

  • num_dice (int) –

    Number of dice rolled.

  • num_sides (int) –

    Number of sides on each die.

  • total (int) –

    Total value of the dice rolls without modifiers.

  • modifier (int) –

    Modifier value added to or subtracted from the total roll.

  • total_with_modifier (int) –

    Total value of the dice rolls including the modifier.

  • rolls (list) –

    List of individual die roll results.

pretty_print

pretty_print() -> str

Return a human-readable string representation of the dice roll, including the total roll and any modifiers.

Returns:

  • str ( str ) –

    A string describing the dice roll and its outcome (e.g., 'Rolled 3d6 and got 11 (11)', 'Rolled 1d20+3 and got 9 (6 + 3)').

roll_dice

roll_dice(notation: str, modifier: int = 0, drop_lowest: bool = False) -> DiceRoll

Roll dice based on the nDn or Dn notation and factor in optional modifiers.

Examples:

roll_dice('3d6') # DiceRoll object representing a roll of three six-sided dice.
roll_dice('1d20+5') # DiceRoll object for rolling one twenty-sided die with a +5 modifier.
roll_dice('20') # DiceRoll object for a guaranteed roll of 20.

Parameters:

  • notation (str) –

    A string representation of a dice roll in ndn format with optional modifiers like '3d6', '1d20+5', or '2d8-4', or a string representing an integer, like '1', '20', or '18'.

  • modifier (int, default: 0 ) –

    An optional additional integer modifier to add to the roll. Defaults to 0.

  • drop_lowest (bool, default: False ) –

    Whether to drop the lowest dice roll. Defaults to False.

Returns:

  • DiceRoll ( DiceRoll ) –

    A named tuple containing the number of dice, number of sides, base roll, modifier, total roll with modifier, and the individual rolls.

Raises:

  • ValueError

    If the notation or dice sides are invalid.