12.3. CASESTUDY: DICEPOKER 213
from dice importDice
d = Dice()
d.values()
[6, 3, 3, 6, 5]
d.score()
(’Two Pairs’, 5)
d.roll([4])
d.values()
[6, 3, 3, 6, 4]
d.roll([4])
d.values()
[6, 3, 3, 6, 3]
d.score()
(’Full House’, 12)
We wouldwanttobesurethateachkindofhandscoresproperly.
ImplementingPokerApp
Nowwearereadytoturnourattentiontothetaskofactuallyimplementingthepokergame. We canuse
top-downdesigntofleshoutthedetailsandalsosuggestwhatmethodswillhave tobeimplementedinthe
PokerInterfaceclass.
Initially, weknowthatthePokerAppwillneedtokeeptrackofthedice,theamountofmoney, and
someuserinterface.Let’s initializethesevaluesintheconstructor.
class PokerApp:
def init(self):
self.dice = Dice()
self.money= 100
self.interface= PokerInterface()
To runtheprogram,wewillcreateaninstanceofthisclassandcallitsrunmethod. Basically, the
programwillloop,allowingtheusertocontinueplayinghandsuntilheorsheiseitheroutofmoney or
choosestoquit. Sinceit costs$10toplaya hand,wecancontinueaslongasself.money >= 10.
Determiningwhethertheuseractuallywantstoplayanotherhandmustcomefromtheuserinterface.Here
is onewaywemightcodetherunmethod:
def run(self):
while self.money>= 10 and self.interface.wantToPlay():
self.playRound()
self.interface.close()
Noticethecalltointerface.closeatthebottom.Thiswillallowustodoany necessarycleaningup
suchasprintinga finalmessagefortheuserorclosinga graphicswindow.
Mostoftheworkoftheprogramhasnow beenpushedintotheplayRoundmethod.Let’s continuethe
top-downprocessbyfocusingourattentionhere.Eachroundwillconsistofa seriesofrolls.Basedonthese
rolls,theprogramwillhave toadjusttheplayer’s score.
def playRound(self):
self.money= self.money - 10
self.interface.setMoney(self.money)
self.doRolls()
result, score= self.dice.score()
self.interface.showResult(result, score)
self.money= self.money + score
self.interface.setMoney(self.money)