146 CHAPTER9. SIMULATIONANDDESIGN
else: # A loses serve
serving = "B"
else:
if random() < probB: # B wins the serve
scoreB = scoreB+ 1
else: # B loses the serve
serving = "A"
Thatprettymuchcompletesthefunction.It gota bitcomplicated,butseemstoreflecttherulesofthe
simulationasthey werelaidout.Puttingthefunctiontogether, hereis theresult.
def simOneGame(probA, probB):
scoreA = 0
scoreB = 0
serving = "A"
while gameNotOver(scoreA,scoreB):
if serving== "A":
if random()< probA:
scoreA = scoreA+ 1
else:
serving = "B"
else:
if random()< probB:
scoreB = scoreB+ 1
else:
serving = "A"
return scoreA,scoreB
9.3.6 FinishingUp
Whew!We have justonemoretroublesomefunctionleft,gameOver. Hereis whatweknow aboutit sofar.
def gameOver(a,b):
a and b representscores for a racquetball game
RETURNS trueif the game is over, false otherwise.
Accordingtotherulesforoursimulation,a gameis overwheneitherplayerreachesa totalof15.We can
checkthiswitha simpleBooleancondition.
def gameOver(a,b):
a and b representscores for a racquetball game
RETURNS trueif the game is over, false otherwise.
return a==15 or b==15
Noticehow thisfunctiondirectlycomputesandreturnstheBooleanresultallinonestep.
We’ve doneit!ExceptforprintSummary, theprogramis complete.Let’s fillinthemissingdetails
andcallit a wrap.Hereis thecompleteprogramfromstarttofinish:
rball.py
from random importrandom
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n,probA, probB)
printSummary(winsA,winsB)