Python Programming: An Introduction to Computer Science

(Nora) #1
144 CHAPTER9. SIMULATIONANDDESIGN

probA
probB
n

probA
probB
n winsAwinsB

winsA
winsB

simOneGame

probA
probB
scoreA
scoreB

main

printIntro getInputs simNGames printSummary

Figure9.2:Level 2 structurechartforracquetballsimulation.

else:
winsB = winsB+ 1
return winsA, winsB

9.3.5 Third-Level Design.


Everythingseemstobecomingtogethernicely. Let’s keepworkingonthegutsofthesimulation. The
nextobviouspointofattackissimOneGame. Here’s whereweactuallyhave tocodeupthelogicofthe
racquetballrules. Playerskeepdoingralliesuntilthegameis over. Thatsuggestssomekindofindefinite
loopstructure;wedon’t know how many ralliesit willtake beforeoneoftheplayersgetsto 15.Theloopjust
keepsgoinguntilthegameis over.
Alongtheway, weneedtokeeptrackofthescore(s),andwealsoneedtoknow whois currentlyserving.
Thescoreswillprobablyjustbea coupleofint-valuedaccumulators,buthowdowekeeptrackofwho’s
serving?It’s eitherplayerAorplayerB.Oneapproachis tousea stringvariablethatstoreseither"A"or
"B". It’s alsoanaccumulatorofsorts,buttoupdateitsvalue,wejustswitchit fromonevaluetotheother.
That’s enoughanalysistoputtogethera roughalgorithm.Let’s trythis:


Initialize scores to 0
Set serving to "A"
Loop while game is notover:
Simulate one serveof whichever player is serving
update the statusof the game
Return scores


It’s a start,at least.Clearlythere’s stillsomeworktobedoneonthisone.
We canquicklyfillinthefirstcouplestepsofthealgorithmtogetthefollowing.


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


Thequestionatthispointis exactlywhattheconditionwillbe.We needtokeeploopingaslongasthe
gameis notover. We shouldbeabletotellif thegameis overbylookingatthescores. We discusseda

Free download pdf