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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

16.3 Dealing cards 171<br />

16.3 Dealing cards<br />

NowthatwehaveaHand class, we want <strong>to</strong> deal cards from the Deck in<strong>to</strong> hands.<br />

It is not immediately obvious whether this method should go in the Hand class<br />

or in the Deck class, but since it operates on a single deck and (possibly) several<br />

hands, it is more natural <strong>to</strong> put it in Deck.<br />

deal should be fairly general, since different games will have different requirements.<br />

We may want <strong>to</strong> deal out the entire deck at once or add one card <strong>to</strong> each<br />

hand.<br />

deal takes three parameters: the deck, a list (or tuple) of hands, and the <strong>to</strong>tal<br />

number of cards <strong>to</strong> deal. If there are not enough cards in the deck, the method<br />

deals out all of the cards and s<strong>to</strong>ps:<br />

class Deck :<br />

...<br />

def deal(self, hands, nCards=999):<br />

nHands = len(hands)<br />

for i in range(nCards):<br />

if self.isEmpty(): break # break if out of cards<br />

card = self.popCard() # take the <strong>to</strong>p card<br />

hand = hands[i % nHands] # whose turn is next?<br />

hand.addCard(card)<br />

# add the card <strong>to</strong> the hand<br />

The last parameter, nCards, is optional; the default is a large number, which<br />

effectively means that all of the cards in the deck will get dealt.<br />

The loop variable i goes from 0 <strong>to</strong> nCards-1. Each time through the loop, a card<br />

is removed from the deck using the list method pop, which removes and returns<br />

the last item in the list.<br />

The modulus opera<strong>to</strong>r (%) allows us <strong>to</strong> deal cards in a round robin (one card at<br />

a time <strong>to</strong> each hand). When i is equal <strong>to</strong> the number of hands in the list, the<br />

expression i % nHands wraps around <strong>to</strong> the beginning of the list (index 0).<br />

16.4 Printing a Hand<br />

To print the contents of a hand, we can take advantage of the printDeck and<br />

str methods inherited from Deck. For example:

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

Saved successfully!

Ooh no, something went wrong!