12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

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.

Chapter 18InheritanceIn this chapter we will develop classes to represent playing cards, decks of cards, and poker hands.If you don’t play poker, you can read about it at wikipedia.org/wiki/Poker, but you don’t haveto; I’lltellyou what you need toknow forthe exercises.IfyouarenotfamiliarwithAnglo-Americanplayingcards,youcanreadaboutthematwikipedia.org/wiki/Playing_cards.18.1 CardobjectsThere are fifty-two cards in a deck, each of which belongs to one of four suits and one of thirteenranks. The suits are Spades, Hearts, Diamonds, and Clubs (in descending order in bridge). Theranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. Depending on the game that you areplaying, an Ace may be higher thanKing or lower than2.Ifwewanttodefineanewobjecttorepresentaplayingcard,itisobviouswhattheattributesshouldbe: rank and suit. It is not as obvious what type the attributes should be. One possibility is touse strings containing words like'Spade' for suits and'Queen' for ranks. One problem with thisimplementationisthatitwouldnotbeeasytocomparecardstoseewhichhadahigherrankorsuit.An alternative is to use integers to encode the ranks and suits. In this context, “encode” means thatwe are going to define a mapping between numbers and suits, or between numbers and ranks. Thiskind of encoding isnot meant tobe asecret (that would be “encryption”).For example, thistable shows the suitsand thecorresponding integer codes:Spades ↦→ 3Hearts ↦→ 2Diamonds ↦→ 1Clubs ↦→ 0This code makes it easy to compare cards; because higher suits map to higher numbers, we cancompare suitsby comparing theircodes.The mapping for ranks is fairly obvious; each of the numerical ranks maps to the correspondinginteger, and forface cards:

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

Saved successfully!

Ooh no, something went wrong!