220 CHAPTER12. OBJECT-ORIENTEDDESIGN
self.money.setText("$%d" % (amt))
def showResult(self,msg, score):
if score > 0:
text = "%s!You win $%d" % (msg, score)
else:
text = "Yourolled %s" % (msg)
self.msg.setText(text)
Ina similarspirit,theoutputmethodsetDicemustmake a calltothesetValuemethodofthe
approriateDieViewobjectsindice. We candothiswithaforloop.
def setDice(self,values):
for i in range(5):
self.dice[i].setValue(values[i])
Take a goodlookat thelineintheloopbody. It setstheithdietoshow theithvalue.
Asyoucansee,oncetheinterfacehasbeenconstructed,makingit functionalisnotoverlydifficult.
Ouroutputmethodsarecompletedwithjusta fewlinesofcode.Theinputmethodsareonlyslightlymore
complicated.
ThewantToPlaymethodwillwaitfortheusertoclickeither“RollDice”or“Quit.” We canuseour
choosehelpermethodtodothis.
def wantToPlay(self):
ans = self.choose(["Roll Dice", "Quit"])
self.msg.setText("")
return ans == "RollDice"
Afterwaitingfortheusertoclickanappropriatebutton,thismethodthenclearsoutany message,suchas
thepreviousresults,bysettingthemsgtexttotheemptystring.Themethodthenreturnsa Booleanvalueby
examiningthelabelreturnedbychoose.
ThatbringsustothechooseDicemethod.Herewemustimplementa moreextensive userinteraction.
ThechooseDicemethodreturnsa listoftheindexesofthedicethattheuserwishestoroll.
InourGUI,theuserwillchoosedicebyclickingoncorrespondingbuttons.We needtomaintaina listof
whichdicehave beenchosen.Eachtimea diebuttonis clicked,thatdieis eitherchosen(itsindex is appended
tothelist)orunchosen(itsindex isremovedfromthelist). Inaddition,thecolorofthecorresponding
DieViewreflectsthestatusofthedie.Theinteractionendswhentheuserclickseithertherollbuttonorthe
scorebutton.If therollbuttonis clicked,themethodreturnsthelistofcurrentlychosenindexes.If thescore
buttonis clicked,thefunctionreturnsanemptylisttosignalthattheplayeris donerolling.
Hereis onewaytoimplementthechoosingofdice.Thecommentsinthiscodeexplainthealgorithm:
def chooseDice(self):
# choices is a listof the indexes of the selected dice
choices = [] # No dice chosen yet
while 1:
# wait foruser to click a valid button
b = self.choose(["Die 1", "Die 2", "Die 3", "Die 4", "Die5",
"Roll Dice", "Score"])
if b[0] == "D": # User clicked a die button
i = eval(b[4])- 1 # Translate label to die index
if i in choices: # Currently selected, unselectit
choices.remove(i)
self.dice[i].setColor("black")
else: # Currently unselected,select it
choices.append(i)