12.2. CASESTUDY: RACQUETBALLSIMULATION 207
12.2.4 ImplementingPlayer
IndevelopingtheRBallGameclass,wediscoveredtheneedforaPlayerclassthatencapsulatesthe
serviceprobabilityandcurrentscorefora player. ThePlayerclassneedsa suitableconstructorandmethods
forwinsServe,incScoreandgetScore.
If youaregettingthehangofthisobject-orientedapproach,youshouldhave notroublecomingupwith
a constructor. We justneedtoinitializetheinstancevariables.Theplayer’s probabilitywillbepassedasa
parameter, andthescorestartsat 0.
def __init__(self,prob):
# Create a playerwith this probability
self.prob = prob
self.score= 0
TheothermethodsforourPlayerclassareevensimpler. To seeif a playerwinsa serve, wecompare
theprobabilitytoa randomnumberbetween0 and1.
def winsServe(self):
return random()<= self.prob
To give a playera point,wesimplyaddonetothescore.
def incScore(self):
self.score= self.score + 1
Thefinalmethodjustreturnsthevalueofthescore.
def getScore(self):
return self.score
Initially, youmaythinkthatit’s sillytocreatea classwitha bunchofone-ortwo-linemethods.Actually,
it’s quitecommonfora well-modularized,objected-orientedprogramtohave lotsoftrivialmethods. The
pointofdesignistobreaka problemdownintosimplerpieces. Ifthosepiecesaresosimplethattheir
implementationis obvious,thatgivesusconfidencethatwemusthave gottenit right.
12.2.5 TheCompleteProgram.
Thatprettymuchwrapsupourobject-orientedversionoftheracquetballsimulation.Thecompleteprogram
follows.Youshouldreadthroughit andmake sureyouunderstandexactlywhateachclassdoesandhow it
doesit.If youhave questionsaboutany parts,gobacktothediscussionabove tofigureit out.
objrball.py -- Simulationof a racquet game.
Illustratesdesign with objects.
from random importrandom
class Player:
A Player keepstrack of service probability and score
def __init__(self,prob):
# Create a playerwith this probability
self.prob = prob
self.score= 0
def winsServe(self):
# RETURNS a Booleanthat is true with probability self.prob
return random()<= self.prob