1.自顶向下模块化设计
2.自底向上实现
2.1printIntro() #输出程序的初步信息
def printIntro():
print("这个程序模拟两个选手的竞赛")
print("需要输入两个运动员的能力值")
2.2getInputs(): #获得选手的能力与比赛场次
def getInputs():
a=eval(input("请输入选手A的能力值0-1"))
b=eval(input("请输入选手B的能力值0-1"))
n=eval(input("模拟比赛场次"))
return a,b,n
2.3simNGames(n,proA,proB): #N场游戏结果
def simNGames(n,proA,proB):
winsA,winsB=0,0;
for i in range(n):
scoreA,scoreB=simOneGame(proA,proB)
if scoreA>scoreB:
winsA+=1
else:
winsB+=1
return winsA,winsB
2.4printSummary(winsA,winsB): #输出胜负情况
def printSummary(winsA,winsB):
n=winsA+winsB
print("模拟比赛的场次为{}场".format(n))
print("选手A获胜{}场,占比{:0.1%}".format(winsA,winsA/n))
print("选手B获胜{}场,占比{:0.1%}".format(winsB,winsB/n))
最终实现:
import random
def printIntro():
print("这个程序模拟两个选手的竞赛")
print("需要输入两个运动员的能力值")
def getInputs():
a=eval(input("请输入选手A的能力值0-1\n"))
b=eval(input("请输入选手B的能力值0-1\n"))
n=eval(input("模拟比赛场次"))
return a,b,n
def gameOver(scoreA,scoreB):
return scoreA==15 or scoreB==15
def simOneGame(proA,proB):
scoreA,scoreB=0,0
serving="A"
while not gameOver(scoreA,scoreB):
if serving=="A":
if random.random()<proA:
scoreA+=1
else:
serving="B"
else:
if random.random()<proB:
scoreB+=1
else:
serving="A"
return scoreA,scoreB
def simNGames(n,proA,proB):
winsA,winsB=0,0;
for i in range(n):
scoreA,scoreB=simOneGame(proA,proB)
if scoreA>scoreB:
winsA+=1
else:
winsB+=1
return winsA,winsB
def printSummary(winsA,winsB):
n=winsA+winsB
print("模拟比赛的场次为{}场".format(n))
print("选手A获胜{}场,占比{:0.1%}".format(winsA,winsA/n))
print("选手B获胜{}场,占比{:0.1%}".format(winsB,winsB/n))
def main():
printIntro()
proA,proB,n=getInputs()
winsA,winsB=simNGames(n,proA,proB)
printSummary(winsA,winsB)
main()