Advertisement
MalioSwift

[python] dice roll implementation

Jun 16th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. import secrets # Cryptographically secure random number generator. Likely a bit excessive.
  2.  
  3. class dice:
  4. @classmethod
  5. def roll(cls, roll = {}, explode = {}):
  6. """
  7. Function that creates a random number as if rolling dice.
  8.  
  9. :param to_roll: A dictionary in the form of {sides: number of dice}
  10. Use 1 sided dice for constant modifier
  11. :param to_explode: A dictionary in the form of {sides:number of dice}
  12. Will add an additional die in the case of a die rolling the max die_roll.
  13. :return:
  14. The sum of the rolls of the dice
  15. """
  16. result = 0
  17.  
  18. for die_max, count in roll.items():
  19. if die_max<1:
  20. continue
  21. for _ in range(0, count):
  22. result += cls._roll(die_max)
  23. for die_max, count in explode.items():
  24. if die_max <= 1: # Will explode infinitely
  25. continue
  26. for _ in range(0, count):
  27. die_roll = die_max
  28. while die_roll == die_max:
  29. die_roll = cls._roll(die_max)
  30. result += die_roll
  31. return result
  32.  
  33. @classmethod
  34. def _roll(cls, die):
  35. return secrets.randbelow(die)+1
  36.  
  37. if __name__ == '__main__':
  38. print("Rolling 6d6")
  39. to_roll = {6: 6}
  40. print("Result: %s"%(dice.roll(to_roll),))
  41.  
  42. print("Rolling exploding 6d6")
  43. to_roll = {6: 6}
  44. print("Result: %s" % (dice.roll(explode = to_roll),))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement