Python Programming: An Introduction to Computer Science

(Nora) #1
9.3.TOP-DOWNDESIGN 145

numberofpossibilitiesforthisconditioninthepreviouschapter, someofwhichwerefairlycomplex.Let’s
hidethedetailsinanotherfunction,gameOver, thatlooksatthescoresandreturnstrue(1)if thegameis
over, andfalse(0)if it is not.Thatgetsusontotherestoftheloopfornow.
Figure9.3showsthestructurechartwithournew function.ThecodeforsimOneGamenow lookslike
this:


def simOneGame(probA, probB):
scoreA = 0
scoreB = 0
serving = "A"
while not gameOver(scoreA,scoreB):


probA
probB
n

probA
probB
n winsAwinsB

winsA
winsB

simOneGame

probA
probB
scoreA
scoreB

main

scoreA
scoreB true|false

printIntro getInputs simNGames printSummary

gameOver

Figure9.3:Level 3 structurechartforracquetballsimulation.

Insidetheloop,weneedtodoa singleserve. Remember, wearegoingtocomparea randomnumbertoa
probabilityinorderto determineif theserver winsthepoint(random() < prob). Thecorrectprobability
touseis determinedbythevalueofserving. We willneeda decisionbasedonthisvalue.If A is serving,
thenweneedtouseA’s probability, and,basedontheresultoftheserve, updateeitherA’s scoreorchange
theservicetoB.Hereis thecode:


if serving == "A":
if random() < probA: # A wins the serve
scoreA = scoreA+ 1
else: # A loses the serve
serving = "B"


Ofcourse,if A is notserving,weneedtodothesamething,onlyforB.We justneedtoattacha mirror
imageelseclause.


if serving == "A":
if random() < probA: # A wins the serve
scoreA = scoreA+ 1

Free download pdf