Python Programming: An Introduction to Computer Science

(Nora) #1
12.2. CASESTUDY: RACQUETBALLSIMULATION 205

To finishouttheclass,weimplementtheprintLinemethod. Thismethodwillmake heavyuseof
stringformatting.A goodstartis todefinea templatefortheinformationthatwillappearineachline.


def printLine(self,label, wins, shuts, n):
template = "Player%s: %4d %5.1f%% %11d %s"
if wins == 0: # Avoid division by zero!
shutStr = "-----"
else:
shutStr = "%4.1f%%"% (float(shuts)/wins*100)
print template% (label, wins, float(wins)/n*100, shuts,shutStr)

Noticehow theshutoutpercentageis handled.Themaintemplateincludesit asa string,andtheifstatement
takescareofformattingthispiecetopreventdivisionbyzero.


12.2.3 ImplementingRBallGame


Now thatwehave wrappeduptheSimStatsclass,weneedtoturnourattentiontoRBallGame. Summa-
rizingwhatwehave decidedsofar, thisclassneedsa constructorthatacceptstwo probabilitiesasparameters,
aplaymethodthatplaysthegame,andagetScoresmethodthatreportsthescores.
Whatwilla racquetballgameneedtoknow? To actuallyplaythegame,wehave torememberthe
probabilityforeachplayer, thescoreforeachplayer, andwhichplayeris serving.If youthinkaboutthis
carefully, youwillseethatprobabilityandscorearepropertiesrelatedtoparticularplayers, whiletheserver
is a propertyofthegamebetweenthetwo players.Thatsuggeststhatwemightsimplyconsiderthata game
needstoknow whotheplayersareandwhichis serving.Theplayersthemselvescanbeobjectsthatknow
theirprobabilityandscore. ThinkingabouttheRBallGameclassthiswayleadsustodesignsomenew
objects.
If theplayersareobjects,thenwewillneedanotherclasstodefinetheirbehavior. Let’s namethatclass
Player. APlayerobjectwillkeeptrackofitsprobabilityandcurrentscore.WhenaPlayeris first
createdtheprobabilitywillbesuppliedasa parameter, butthescorewilljuststartoutat0.We’ll fleshout
thedesignofPlayerclassmethodsasweworkonRBallGame.
We arenow in a positionto definetheconstructorforRBallGame. Thegamewillneedinstancevariables
forthetwo playersandanothervariabletokeeptrackofwhichplayeris serving.


class RBallGame:
def init(self,probA, probB):
self.playerA= Player(probA)
self.playerB= Player(probB)
self.server= self.PlayerA # Player A always serves first


Sometimesit helpstodrawa picturetoseetherelationshipsamongtheobjectsthatwearecreating.
SupposewecreateaninstanceofRBallGamelike this:


theGame = RBallGame(.6,.5)


Figure12.1showsanabstractpictureoftheobjectscreatedbythisstatementandtheirinter-relationships.
OK,nowthatwecancreateanRBallGame, weneedtofigureouthowtoplayit.Goingbacktothe
dicussionofracquetballfromChapter9, weneedanalgorithmthatcontinuesto serve ralliesandeitheraward
pointsorchangetheserver asappropriateuntilthegameis over. We cantranslatethisloosealgorithmalmost
directlyintoourobject-basedcode.
First,weneeda loopthatcontinuesaslongasthegameis notover. Obviously, thedecisionofwhether
thegamehasendedornotcanonlybemadebylookingatthegameobjectitself. Let’s justassumethat
anappropriateisOvermethodcanbewritten.Thebeginningofourplaymethodcanmake useofthis
(yet-to-be-written)method.


def play(self):
while not self.isOver():

Free download pdf