Python Programming: An Introduction to Computer Science

(Nora) #1
218 CHAPTER12. OBJECT-ORIENTEDDESIGN

if b.clicked(p):
returnb.getLabel() # function exit here.

TheotherwidgetsinourinterfacewillbeourDieViewthatwedevelopedinthelasttwo chapters.
Basically, wewillusethesameclassasbefore,butweneedtoaddjusta bitofnewfunctionality. As
discussedabove, wewanttochangethecolorofa dietoindicatewhetherit is selectedforrerolling.
YoumightwanttogobackandreviewtheDieViewclass. Remember, theclasscontructordraws
a squareandsevencirclestorepresentthepositionswherethepipsofvariousvalueswillappear. The
setValuemethodturnsontheappropriatepipstodisplaya givenvalue.To refreshyourmemorya bit,
hereis thesetValuemethodasweleftit:


def setValue(self,value):
# Turn all thepips off
for pip in self.pips:
pip.setFill(self.background)

# Turn the appropriatepips back on
for i in self.onTable[value]:
self.pips[i].setFill(self.foreground)

We needtomodifytheDieViewclassbyaddingasetColormethod. Thismethodwillbeusedto
changethecolorthatis usedfordrawingthepips.AsyoucanseeinthecodeforsetValue, thecolorof
thepipsis determinedbythevalueoftheinstancevariableforeground. Ofcourse,changingthevalueof
foregroudwillnotactuallychangetheappearanceofthedieuntilit is redrawnusingthenew color.
ThealgorithmforsetColorseemsstraightforward.We needtwo steps:


change foreground to the newcolor
redraw the currentvalue of the die


Unfortunately, thesecondsteppresentsa slightsnag. We alreadyhave codethatdrawsa value,namely
setValue. ButsetValuerequiresustosendthevalueasa parameter, andthecurrentversionof
DieViewdoesnotstorethisvalueanywhere.Oncetheproperpipshave beenturnedon,theactualvalueis
discarded.
InordertoimplementsetColor, weneedtotweaksetValuesothatit remembersthecurrentvalue.
ThensetColorcanredraw thedieusingitscurrentvalue.ThechangetosetValueis easy;wejustneed
toadda singleline.


self.value = value


Thislinestoresthevalueparameterinaninstancevariablecalledvalue.
WiththemodifiedversionofsetValue, implementingsetColoris a breeze.


def setColor(self,color):
self.foreground= color
self.setValue(self.value)

Noticehow thelastlinesimplycallssetValueto(re)draw thedie,passingalongthevaluethatwassaved
fromthelasttimesetValuewascalled.


CreatingtheInterface


Nowthatwehave ourwidgetsundercontrol,wearereadytoactuallyimplementourGUIpokerinterface.
Theconstructorwillcreateallofourwidgets,settinguptheinterfaceforlaterinteractions.


class GraphicsInterface:
def init(self):
self.win = GraphWin("DicePoker", 600, 400)
self.win.setBackground("green3")

Free download pdf