214 CHAPTER12. OBJECT-ORIENTEDDESIGN
Thiscodeonlyreallyhandlesthescoringaspectofa round.Anytimenew informationmustbeshowntothe
user, a suitablemethodfrominterfaceis invoked.The$10feetoplaya roundis firstdeductedandthe
interfaceis updatedwiththenew amountofmoney remaining.Theprogramthenprocessesa seriesofrolls
(doRolls), showstheusertheresult,andupdatestheamountofmoney accordingly.
Finally, wearedowntothenitty-grittydetailsofimplementingthedicerollingprocess.Initially, allof
thedicewillberolled.Thenweneeda loopthatcontinuesrollinguser-selecteddiceuntileithertheuser
choosestoquitrollingorthelimitofthreerollsis reached.Let’s usea localvariablerollstokeeptrackof
how many timesthedicehave beenrolled.Obviously, displayingthediceandgettingthethelistofdiceto
rollmustcomefrominteractionwiththeuserthroughinterface.
def doRolls(self):
self.dice.rollAll()
roll = 1
self.interface.setDice(self.dice.values())
toRoll = self.interface.chooseDice()
while roll< 3 and toRoll != []:
self.dice.roll(toRoll)
roll = roll+ 1
self.interface.setDice(self.dice.values())
if roll < 3:
toRoll = self.interface.chooseDice()
Atthispoint,wehave completedthebasicfunctionsofourinteractive poker program.Thatis,wehave a
modeloftheprocessforplayingpoker. We can’t reallytestoutthisprogramyet,however, becausewedon’t
have a userinterface.
12.3.4 A Text-BasedUI
IndesigningPokerAppwehave alsodevelopeda specificationfora genericPokerInterfaceclass.Our
interfacemustsupportthemethodsfordisplayinginformation:setMoney,setDice, andshowResult.
It mustalsohave methodsthatallowforinputfromtheuser:wantToPlay, andchooseDice. These
methodscanbeimplementedinmany differentways,producingprogramsthatlookquitedifferenteven
thoughtheunderlyingmodel,PokerApp, remainsthesame.
Usually, graphicalinterfacesaremuchmorecomplicatedtodesignandbuildthantext-basedones.If we
areina hurrytogetourapplicationrunning,wemightfirsttrybuildinga simpletext-basedinterface.We can
usethisfortestinganddebuggingofthemodelwithoutalltheextracomplicationofa full-blownGUI.
First,let’s tweakourPokerAppclassa bitsothattheuserinterfaceis suppliedasa parametertothe
constructor.
class PokerApp:
def init(self,interface):
self.dice = Dice()
self.money= 100
self.interface= interface
Thenwecaneasilycreateversionsofthepokerprogramusingdifferentinterfaces.
Now let’s considera bare-bonesinterfacetotestoutthepokerprogram.Ourtext-basedversionwillnot
presenta finishedapplication,butrather, give usa minimalistinterfacesolelytogettheprogramrunning.
Eachofthenecessarymethodscanbegivena trivialimplementation.
Hereis a completeTextInterfaceclassusingthisapproach:
file: textpoker.py
class TextInterface:
def __init__(self):
print "Welcometo video poker."