204 CHAPTER12. OBJECT-ORIENTEDDESIGN
class SimStats:
def init(self):
self.winsA= 0
self.winsB= 0
self.shutsA= 0
self.shutsB= 0
Now let’s take a lookat theupdatemethod.It takesa gameasa normalparameterandmustupdatethe
fourcountsaccordingly. Theheadingofthemethodwilllooklike this:
def update(self,aGame):
Buthow exactlydoweknow whatto do?We needto know thefinalscoreofthegame,but thisinformation
residesinsideofaGame. Remember, wearenotallowedtodirectlyaccesstheinstancevariablesofaGame.
We don’t evenknow yetwhatthoseinstancevariableswillbe.
Ouranalysissuggeststheneedfora newmethodintheRBallGameclass. We needtoextendthe
interfacesothataGamehasa wayofreportingthefinalscore.Let’s callthenew methodgetScoresand
have it returnthescoreforplayerA andthescoreforplayerB.
Now thealgorithmforupdateis straightforward.
def update(self,aGame):
a, b = aGame.getScores()
if a > b: # A won the game
self.winsA= self.winsA + 1
if b == 0:
self.shutsA= self.shutsA + 1
else: # B won the game
self.winsB= self.winsB + 1
if a == 0:
self.shutsB= self.shutsB + 1
We cancompletetheSimStatsclassbywritinga methodtoprintouttheresults.OurprintReport
methodwillgeneratea tablethatshowsthewins,winpercentage,shutoutsandshutoutpercentageforeach
player. Hereis a sampleoutput:
Summary of 500 games:
wins (% total) shutouts (% wins)
Player A: 411 82.2% 60 14.6%
Player B: 89 17.8% 7 7.9%
It is easytoprintouttheheadingsforthistable,buttheformattingofthelinestakesa littlemorecare.
We wanttogetthecolumnslinedupnicely, andwemustavoiddivisionbyzeroincalculatingtheshutout
percentagefora playerwhodidn’t getany wins.Let’s writethebasicmethodbut procrastinatea bitandpush
off thedetailsofformattingthelineintoanothermethod,printLine. TheprintLinemethodwillneed
theplayerlabel(AorB),numberofwinsandshutouts,andthetotalnumberofgames(forcalculationof
percentages).
def printReport(self):
# Print a nicelyformatted report
n = self.winsA+ self.winsB
print "Summaryof", n , "games:"
print
print " wins (% total) shutouts (% wins) "
print "--------------------------------------------"
self.printLine("A",self.winsA, self.shutsA, n)
self.printLine("B",self.winsB, self.shutsB, n)