Dice

Classes

In Unit 2, we learned about types. Every object has a type, and an object's type determines what it can do. For example, adding integers works differently than adding strings. You are not limited to the built-in types; you can create new types by defining classes.

Unit 3 is all about games, and there are a number of objects which are useful for gaming. For example, dice.

💻 Open die.py and read the code:

1class Die:
2 def __init__(self):
3 self.roll()
4
5 def __str__(self):
6 return str(self.face)
7
8 def roll(self):
9 self.face = randint(1, 6)
10 return self.face

💻 Enter the interactive python environment and try using a die.

11% python
12>>> from die import Die
13>>> d = Die()
14>>> print(d)
155
16>>> d.roll()
172
18>>> d.roll()

A few things to note:

Dice stats

What are the odds of rolling five dice and having them all turn up as ones? You could use probability to solve this, but if you haven't learned probability yet, you could just run a simulation.

💻 Run dice_stats.py. This program takes five dice, rolls them a million times, and counts how many times they came up all ones. It takes a moment, so we added a nice little progress bar.

💻 Open dice_stats.py.

1from die import Die
2from tqdm import tqdm
3
4class FiveDice:
5 def __init__(self):
6 self.dice = [Die() for number in range(5)]
7
8 def roll(self):
9 for die in self.dice:
10 die.roll()
11 return self.faces()
12
13 def faces(self):
14 return [die.face for die in self.dice]
15
16 def all_ones(self):
17 for face in self.faces():
18 if face != 1:
19 return False
20 return True
21
22dice = FiveDice()
23successes = 0
24trials = 1000000
25for trial in tqdm(range(trials)):
26 dice.roll()
27 if dice.all_ones():
28 successes += 1
29
30print(successes/trials)

To make it easier to handle five dice, we created another class called FiveDice. When FiveDice is created, it creates a list of five dice. Then FiveDice.roll rolls all the dice, FiveDice.faces returns a list of the die faces, and FiveDice.all_ones checks to see whether all the faces are ones.

Yahtzee

💻 Run play.py. This is a Terminal-based version of Yahtzee, a simple dice game. If you have not played Yahtzee before, here are the rules. This version of Yahtzee is simplified: instead of three-of-a-kind, four-of-a-kind, full house, and all the rest, the only goals are Ones, Twos, and Threes. Still, kind of fun? My record is 22 points.

This version of Yahtzee uses a number of different classes:

Adding goals

Now let's add some more goals to make this game more fun. Implement some of the following goals, as described in the rule book.

Add new classes to yahtzee_goals.py, and then import them in play.py so they are included in the game.