12.5. EXERCISES 223
We couldhave usedinheritancetobuildourpokerprogram.WhenwefirstwrotetheDieViewclass,
it didnotprovidea wayofchangingtheappearanceofthedie.We solvedthisproblembymodifyingthe
originalclassdefinition.Analternative wouldhave beentoleave theoriginalclassunchangedandcreate
a newsubclassColorDieView. AColorDieViewis justlike aDieViewexceptthatit containsan
additionalmethodthatallowsustochangeitscolor. Hereis how it wouldlookinPython:
class ColorDieView(DieView):
def setValue(self,value):
self.value= value
DieView.setValue(self,value)
def setColor(self,color):
self.foreground= color
self.setValue(self.value)
Thefirstlineofthisdefinitionsaysthatwearedefininga newclassColorDieViewthatisbased
on(i.e.,a subclassof)DieView. Insidethenewclass,wedefinetwo methods. Thesecondmethod,
setColor, addsthenew operation.Ofcourse,inordertomakesetColorwork,wealsoneedtomodify
thesetValueoperationslightly.
ThesetValuemethodinColorDieViewredefinesoroverridesthedefinitionofsetValuethatwas
providedin theDieViewclass.ThesetValuemethodin thenew classfirststoresthevalueandthenrelies
onthesetValuemethodofthesuperclassDieViewtoactuallydraw thepips.Noticeespeciallyhow the
callto themethodfromthesuperclassis made.Thenormalapproachself.setValue(value)wouldre-
ferto thesetValuemethodoftheColorDieViewclass,sinceselfis aninstanceofColorDieView.
InordertocalltheoriginalsetValuemethodfromthesuperclass,it is necessarytoputtheclassname
wheretheobjectwouldnormallygo.
DieView.setValue(self,value)
Theactualobjecttowhichthemethodis appliedis thensentasthefirstparameter.
12.5 Exercises
- Inyourownwords,describetheprocessofOOD.
- Inyourownwords,defineencapsulation,polymorphismandinheritance.
- AddbellsandwhistlestothePokerDicegame.
- Redoany ofthedesignproblemsfromChapter9 usingOOtechniques.
- Findtherulestoaninterestingdicegameandwriteaninteractive programtoplayit.Someexamples
areCraps,Yacht,GreedandSkunk. - Writea programthatdealsfourbridgehands,countshowmany pointsthey have andgivesopening
bids. - Finda simplecardgamethatyoulike andimplementaninteractive programtoplaythatgame.Some
possibilitiesareWar, Blackjack,varioussolitairegames,andCrazyEights. - Writeaninteractive programfora boardgame.SomeexamplesareOthello(Reversi),ConnectFour,
Battleship,Sorry!,andParcheesi.