Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import secrets # Cryptographically secure random number generator. Likely a bit excessive.
- class dice:
- @classmethod
- def roll(cls, roll = {}, explode = {}):
- """
- Function that creates a random number as if rolling dice.
- :param to_roll: A dictionary in the form of {sides: number of dice}
- Use 1 sided dice for constant modifier
- :param to_explode: A dictionary in the form of {sides:number of dice}
- Will add an additional die in the case of a die rolling the max die_roll.
- :return:
- The sum of the rolls of the dice
- """
- result = 0
- for die_max, count in roll.items():
- if die_max<1:
- continue
- for _ in range(0, count):
- result += cls._roll(die_max)
- for die_max, count in explode.items():
- if die_max <= 1: # Will explode infinitely
- continue
- for _ in range(0, count):
- die_roll = die_max
- while die_roll == die_max:
- die_roll = cls._roll(die_max)
- result += die_roll
- return result
- @classmethod
- def _roll(cls, die):
- return secrets.randbelow(die)+1
- if __name__ == '__main__':
- print("Rolling 6d6")
- to_roll = {6: 6}
- print("Result: %s"%(dice.roll(to_roll),))
- print("Rolling exploding 6d6")
- to_roll = {6: 6}
- print("Result: %s" % (dice.roll(explode = to_roll),))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement