12.2. CASESTUDY: RACQUETBALLSIMULATION 203
12.2.1 CandidateObjectsandMethods
Ourfirsttaskis tofinda setofobjectsthatcouldbeusefulinsolvingthisproblem.We needtosimulatea
seriesofracquetballgamesbetweentwo playersandrecordsomestatisticsabouttheseriesofgames.This
shortdescriptionalreadysuggestsonewayofdividinguptheworkintheprogram.We needtodotwo basic
things:simulatea gameandkeeptrackofsomestatistics.
Let’s tacklesimulationofthegamefirst.We canuseanobjecttorepresenta singlegameofracquetball.
Agamewillhave tokeeptrackofinformationabouttwo players. Whenwecreatea newgame,wewill
specifytheskilllevelsoftheplayers.Thissuggestsa class,let’s callitRBallGame, witha constructorthat
requiresparametersfortheprobabilitiesofthetwo players.
Whatdoesourprogramneedtodowitha game?Obviously, it needstoplayit.Let’s give ourclassa
playmethodthatsimulatesthegameuntilit is over. We couldcreateandplaya racquetballgamewithtwo
linesofcode.
theGame = RBallGame(probA,probB)
theGame.play()
To playlotsofgames,wejustneedtoputa looparoundthiscode.That’s allwereallyneedinRBallGame
towritethemainprogram.Let’s turnourattentiontocollectingstatisticsaboutthegames.
Obviously, wewillhave to keeptrackofat leastfourcountsin orderto printa summaryofoursimulations:
winsforA,winsforB,shutoutsforA,andshutoutsforB.We willalsoprintoutthenumberofgames
simulated,butthiscanbecalculatedbyaddingthewinsforAandB.Herewehave fourrelatedpiecesof
information.Ratherthantreatingthemindependently, let’s groupthemintoa singleobject.Thisobjectwill
beaninstanceofa classcalledSimStats.
ASimStatsobjectwillkeeptrackofalltheinformationabouta seriesofgames. We have already
analyzedthefourcrucialpiecesofinformation.Now wehave todecidewhatoperationswillbeuseful.For
starters,weneeda constructorthatinitializesallofthecountsto0.
We alsoneeda wayofupdatingthecountsaseachnewgameissimulated. Let’s give ourobjectan
updatemethod. Theupdateofthestatisticswillbebasedontheoutcomeofa game. We willhave to
sendsomeinformationtothestatisticsobjectsothattheupdatecanbedoneappropriately. Aneasyapproach
wouldbetojustsendtheentiregameandletupdateextractwhateverinformationit needs.
Finally, whenallofthegameshave beensimulated,weneedtoprintouta reportoftheresults.This
suggestsaprintReportmethodthatprintsouta nicereportoftheaccumulatedstatistics.
We have now doneenoughdesignthatwecanactuallywritethemainfunctionforourprogram.Mostof
thedetailshave beenpushedoff intothedefinitionofourtwo classes.
def main():
printIntro()
probA, probB, n = getInputs()
Play the games
stats = SimStats()
for i in range(n):
theGame = RBallGame(probA,probB) # create a new game
theGame.play() # play it
stats.update(theGame) # get info about completedgame
Print the results
stats.printReport()
I have alsouseda couplehelperfunctionstoprintanintroductionandgettheinputs.Youshouldhave no
troublewritingthesefunctions.
Nowwehave tofleshoutthedetailsofourtwo classes.TheSimStatsclasslooksprettyeasy—let’s
tacklethatonefirst.
12.2.2 ImplementingSimStats.
TheconstructorforSimStatsjustneedstoinitializethefourcountsto0.Hereis anobviousapproach: