206 CHAPTER12. OBJECT-ORIENTEDDESIGN
playerB:
RBallGame
server:
playerA:playerA:
Player
prob:
score:
Player
prob:
score: 0
0.6
0.5
0
Figure12.1:Abstractview ofRBallGameobject.
Insideoftheloop,weneedtohave theservingplayerserve and,basedontheresult,decidewhattodo.
ThissuggeststhatPlayerobjectsshouldhave a methodthatperformsa serve.Afterall,whethertheserve
is wonornotdependsontheprobabilitythatis storedinsideofeachplayerobject.We’ll justasktheserver
if theserve is wonorlost.
if self.server.winsServe():
Basedonthisresult,weeitherawarda pointorchangetheserver. To awarda point,weneedtochangea
player’s score.Thisagainrequirestheplayerdosomething,namelyincrementthescore.Changingservers,
ontheotherhand,is doneatthegamelevel,sincethisinformationis keptintheserverinstancevariable
ofRBallGame.
Puttingit alltogether, hereis ourplaymethod:
def play(self):
while not self.isOver():
if self.server.winsServe():
self.server.incScore()
else:
self.changeServer()
Aslongasyourememberthatselfis anRBallGame, thiscodeshouldbeclear. Whilethegameis not
over, if theserverwinsa serve, awarda pointtotheserver, otherwisechangetheserver.
Ofcoursethepricewepayforthissimplealgorithmis thatwenow have two new methods(isOverand
changeServer) thatneedtobeimplementedintheRBallGameclassandtwo more(winsServerand
incScore) forthePlayerclass.
Beforeattackingthenew methodsoftheRBallGameclass,let’s gobackandfinishuptheothertop-level
methodoftheclass,namelygetScores. Thisonejustreturnsthescoresofthetwo players.Ofcourse,
werunintothesameproblemagain.It is theplayerobjectsthatactuallyknow thescores,sowewillneeda
methodthatasksa playertoreturnitsscore.
def getScore(self):
return self.playerA.getScore(), self.playerB.getScore()
ThisaddsonemoremethodtobeimplementedinthePlayerclass.Make sureyouputthatonourlistto
completelater.
To finishouttheRBallGameclass,weneedto writetheisOverandchangeServermethods.Given
whatwehave developedalreadyandourpreviousversionofthisprogram,thesemethodsarestraightforward.
I’ll leave thoseasanexerciseforyouat themoment.If you’re lookingformysolutions,skiptothecomplete
codeat theendofthissection.