Let's now add a method to our class so that we can actually simulate rolling it.
import random
class Dice:
def __init__(self, probs):
self.probs = probs
def roll(self, n=1):
sides = list(self.probs.keys())
probabilities = list(self.probs.values())
return random.choices(sides, weights=probabilities, k=n)
If you've never seen this before it may look a bit strange. So let's go over a few things:
- The
.roll
method accepts aself
just like__init__
. - Because
.roll
receivesself
we can refer to the dictionary with all relevant dice values because these are attached toself.probs
. - We use the
random.choices
function from therandom
module in Python to handle the simulation.
With this class definition we can create dice objects and start simulating!
dice = Dice({1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6})
dice.roll(n=10)