Python Programming: An Introduction to Computer Science

(Nora) #1
12.3. CASESTUDY: DICEPOKER 217

Figure12.2:GUIinterfaceforvideodicepoker.

Unlike thebuttonsin thecalculatorprogram,thebuttonsofourpoker interfacewillnotbeactive allofthe
time.Forexample,thedicebuttonswillonlybeactive whentheuseris actuallyintheprocessofchoosing
dice.Whenuserinputis required,thevalidbuttonsforthatinteractionwillbesetactive andtheotherswillbe
inactive. To implementthisbehavior, wecanadda helpermethodcalledchooseto thePokerInterface
class.
Thechoosemethodtakesa listofbuttonlabelsasa parameter, activatesthem,andthenwaitsforthe
usertoclickoneofthem.Thereturnvalueofthefunctionis thelabelofthebuttonthatwasclicked.We can
callthechoosemethodwheneverweneedinputfromtheuser. Forexample,if wearewaitingfortheuser
tochooseeitherthe“RollDice”or“Quit”button,wewouldusea sequenceofcodelike this:


choice = self.choose(["Roll Dice", "Quit"])
if choice == "RollDice":
...


Assumingthebuttonsarestoredinaninstancevariablecalledbuttons, hereis onepossibleimplemen-
tationofchoose:


def choose(self,choices):
buttons = self.buttons

# activatechoice buttons, deactivate others
for b in buttons:
if b.getLabel()in choices:
b.activate()
else:
b.deactivate()

# get mouseclicks until an active button is clicked
while 1:
p = self.win.getMouse()
for b in buttons:
Free download pdf