12.3. CASESTUDY: DICEPOKER 211
constructorCreatetheinitialcollection.
rollAllAssignrandomvaluestoeachofthefive dice.
rollAssigna randomvaluetosomesubsetofthedice,whilemaintainingthecurrentvalueofothers.
valuesReturnthecurrentvaluesofthefive dice.
scoreReturnthescoreforthedice.
We canalsothinkoftheentireprogramasanobject.Let’s calltheclassPokerApp. APokerApp
objectwillkeeptrackofthecurrentamountofmoney, thedice,thenumberofrolls,etc.It willimplementa
runmethodthatweusetogetthingsstartedandalsosomehelpermethodsthatareusedtoimplementrun.
We won’t know exactlywhatmethodsareneededuntilwedesignthemainalgorithm.
Upto thispoint,I have concentratedontheactualgamethatweareimplementing.Anothercomponentto
thisprogramwillbetheuserinterface.Onegoodwaytobreakdownthecomplexityofa moresophisticated
programis toseparatetheuserinterfacefromthemaingutsoftheprogram.Thisis oftencalledthemodel-
viewapproach.Ourprogramimplementssomemodel(inthiscase,it modelsa poker game),andtheinterface
is a view ofthecurrentstateofthemodel.
Onewayofseparatingouttheinterfaceis toencapsulatethedecisionsabouttheinterfaceina separate
interfaceobject.Anadvantageofthisapproachis thatwecanchangethelookandfeeloftheprogramsimply
bysubstitutinga differentinterfaceobject.Forexample,wemighthave a text-basedversionofa progamand
a graphicalversion.
Let’s assumethatourprogramwillmake useofaninterfaceobject,callit aPokerInterface. It’s
notclearyetexactlywhatbehaviorswewillneedfromthisclass,butaswerefinethePokerAppclass,we
willneedtogetinformationfromtheuserandalsodisplayinformation.Thesewillcorrespondtomethods
implementedbythePokerInterfaceclass.
12.3.3 ImplementingtheModel.
Sofar, wehave a prettygoodpictureofwhattheDiceclasswilldoanda startingpointforimplementing
thePokerAppclass.We couldproceedbyworkingoneitheroftheseclasses.We won’t reallybeabletotry
outthePokerAppclassuntilwehave dice,solet’s startwiththelower-levelDiceclass.
ImplementingDice
TheDiceclassimplementsa collectionofdice,whicharejustchangingnumbers.Theobviousrepresenta-
tionis tousea listoffive ints.Ourconstructorneedstocreatea listandassignsomeinitialvalues.
class Dice:
def init(self):
self.dice = [0]*5
self.rollAll()
Thiscodefirstcreatesa listoffive zeroes.Theseneedtobesettosomerandomvalues.Sincewearegoing
toimplementarollAllfunctionanyway, callingit heresavesduplicatingthatcode.
We needmethodstorollselecteddiceandalsotorollallofthedice.Sincethelatteris a specialcaseof
theformer, let’s turnourattentiontotherollfunction,whichrollsa subset.We canspecifywhichdiceto
rollbypassinga listofindexes.Forexample,roll([0,3,4])wouldrollthediceinpositions0,3 and 4
ofthedicelist.We justneeda loopthatgoesthroughtheparameterandgeneratesa new randomvaluefor
eachposition.
def roll(self,which):
for pos in which:
self.dice[pos]= randrange(1,7)
Next,wecanuserolltoimplementrollAllasfollows: