Skip to content

Instantly share code, notes, and snippets.

@jsocol
Last active May 6, 2019 16:14
Show Gist options
  • Save jsocol/f86f35accdcc3e66d88f657679c55fc4 to your computer and use it in GitHub Desktop.
Save jsocol/f86f35accdcc3e66d88f657679c55fc4 to your computer and use it in GitHub Desktop.
import functools
import operator
import random
class D():
"""A die.
Simulates an n-sided die, e.g. to create a d6, pass 6:
>>> d6 = D(6)
>>> d8 = D(8)
To roll, you can call d6.roll() (or just d6()):
>>> d6.roll()
<<< 4
>>> d6()
<<< 2
But the best way to use these is to do math with dice. For
example, if you need to roll 3d8 + 4:
>>> 3 * d8 + 4
<<< 22
Or add dice:
>>> d8 + d4
<<< 9
The die uses random.randint so the examples above are not guaranteed.
"""
def __init__(self, sides):
self.sides = sides
def roll(self):
"""Roll the dice!"""
return random.randint(1, self.sides)
def __mul__(self, n):
"""Roll n (an integer) number of dice."""
return functools.reduce(operator.add, [self.roll() for _ in range(n)])
__rmul__ = __mul__
def __add__(self, n):
"""Add an integer or another die."""
if isinstance(n, D):
n = n.roll()
return n + self.roll()
__radd__ = __add__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment