O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 24

Cooperating Classes

Classes are rarely used in isolation. Their power comes from interactions between objects, and choosing useful classes is the art of object-oriented design. The dice game Chuck-a-Luck provides a good example of a relatively simple game with enough complexity to warrant more than one class. Three dice are rolled, and the player needs to guess one of the numbers that will appear. If the number appears (either 1, 2, or 3 times), the player wins that many units; otherwise, the player loses one unit.

Listing 24.1: Chuck-a-Luck

 1 # chuck.py
 2
 3 from dice import Dice
 4
 5 class ChuckALuck:
 6 def __init__(self):
 7  self.dice = Dice(3)
 8  self.score = 0
 9
10 def play(self):
11  choice = int(input("Choose a number (0 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required