06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

176 Inheritance<br />

# play until all 50 cards are matched<br />

turn = 0<br />

numHands = len(self.hands)<br />

while matches < 25:<br />

matches = matches + self.playOneTurn(turn)<br />

turn = (turn + 1) % numHands<br />

print "----------<br />

self.printHands()<br />

Game is Over"<br />

Some of the steps of the game have been separated in<strong>to</strong> methods.<br />

removeAllMatches traverses the list of hands and invokes removeMatches on<br />

each:<br />

class OldMaidGame(CardGame):<br />

...<br />

def removeAllMatches(self):<br />

count = 0<br />

for hand in self.hands:<br />

count = count + hand.removeMatches()<br />

return count<br />

As an exercise, write printHands which traverses self.hands and<br />

prints each hand.<br />

count is an accumula<strong>to</strong>r that adds up the number of matches in each hand and<br />

returns the <strong>to</strong>tal.<br />

When the <strong>to</strong>tal number of matches reaches twenty-five, fifty cards have been<br />

removed from the hands, which means that only one card is left and the game is<br />

over.<br />

The variable turn keeps track of which player’s turn it is. It starts at 0 and<br />

increases by one each time; when it reaches numHands, the modulus opera<strong>to</strong>r<br />

wraps it back around <strong>to</strong> 0.<br />

The method playOneTurn takes an argument that indicates whose turn it is. The<br />

return value is the number of matches made during this turn:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!