Python Programming: An Introduction to Computer Science

(Nora) #1
212 CHAPTER12. OBJECT-ORIENTEDDESIGN

def rollAll(self):
self.roll(range(5))

I usedrange(5)togeneratea listofalltheindexes.
Thevaluesfunctionisusedtoreturnthevaluesofthedicesothatthey canbedisplayed. Another
one-linersuffices.


def values(self):
return self.dice[:]

NoticethatI createda copy ofthedicelistbyslicingit.Thatway, if aDiceclientmodifiesthelistthat
it getsbackfromvalues, it willnotaffecttheoriginalcopy storedintheDiceobject. Thisdefensive
programmingpreventsotherpartsofthecodefromaccidentlymessingwithourobject.
Finally, wecometothescoremethod.Thisis thefunctionthatwilldeterminetheworthofthecurrent
dice.We needtoexaminethevaluesanddeterminewhetherwehave any ofthepatternsthatleadtoa payoff,
namelyFive ofa Kind,Fourofa Kind,FullHouse,Threeofa Kind,Two Pairs,orStraight.Ourfunction
willneedsomewaytoindicatewhatthepayoff is.Let’s returna stringlabelingwhatthehandis andanint
thatgivesthepayoff amount.
We canthinkofthisfunctionasa multi-waydecision.We simplyneedtocheckforeachpossiblehand.
If wedosoina sensibleorder, wecanguaranteegivingthecorrectpayout.Forexample,a fullhousealso
containsa threeofa kind.We needtocheckforthefullhousebeforecheckingforthreeofa kind,sincethe
fullhouseis morevaluable.
Onesimplewayofcheckingthehandis to generatea listofthecountsofeachvalue.Thatis,counts[i]
willbethenumberoftimesthatthevalueioccursindice.If thediceare:[3,2,5,2,3]thenthecount
listwouldbe[0,0,2,2,0,1,0]. Noticethatcounts[0]willalwaysbezero,sincedicevaluesarein
therange1–6.Checkingforvarioushandscanthenbedonebylookingforvariousvaluesincounts. For
example,ifcountscontainsa 3 anda 2 , thehandcontainsa tripleanda pair, andhence,is a fullhouse.
Here’s thecode:


def score(self):
# Create the countslist
counts = [0] * 7
for value in self.dice:
counts[value]= counts[value] + 1

# score the hand
if 5 in counts:
return "Fiveof a Kind", 30
elif 4 in counts:
return "Fourof a Kind", 15
elif (3 in counts)and (2 in counts):
return "FullHouse", 12
elif 3 in counts:
return "Threeof a Kind", 8
elif not (2 in counts)and (counts[1]==0 or counts[6]== 0):
return "Straight", 20
elif counts.count(2)== 2:
return "TwoPairs", 5
else:
return "Garbage", 0

Theonlytricky partisthetestingforstraights. Sincewehave alreadycheckedfor5,4 and3 ofa kind,
checkingthattherearenopairsnot 2 in countsguaranteesthatthediceshow five distinctvalues.If
thereis no6, thenthevaluesmustbe1–5;likewise,no1 meansthevaluesmustbe2–6.
Atthispoint,wecouldtryouttheDiceclasstomake surethatit is workingcorrectly. Hereis a short
interactionshowingsomeofwhattheclasscando:

Free download pdf