from random import random
#打印程序介绍信息
def printintro():
print("这个程序模拟两个选手a和b的乒乓球比赛")
print("程序运行需要a和b的能力值(以0到1之间的小数表示)")
#获得程序运行参数
def printinputs():
a = eval(input("请输入选手a的能力值(0-1): "))
b = eval(input("请输入选手b的能力值(0-1): "))
n = eval(input("模拟比赛的场次: "))
return a, b, n
# 进行n场比赛
def simngames(n, proba, probb):
winsa, winsb = 0, 0
for i in range(n):
for j in range(7): #进行7局4胜的比赛
scorea, scoreb = simonegame(proba, probb)
if scorea > scoreb:
winsa += 1
else:
winsb += 1
return winsa,winsb
#进行一场比赛
def simonegame(proba, probb):
scorea, scoreb = 0, 0 #初始化ab的得分
serving = "a"
while not gameover(scorea, scoreb): #用while循环来执行比赛
if scorea==10 and scoreb==10:
return(simonegame2(proba,probb))
if serving == "a":
if random() < proba: ##用随机数生成胜负
scorea += 1
else:
serving="b"
else:
if random() < probb:
scoreb += 1
else:
serving="a"
return scorea, scoreb
def simonegame2(proba,probb):
scorea,scoreb=10,10
serving = "a"
while not gameover2(scorea, scoreb):
if serving == "a":
if random() < proba:
scorea += 1
else:
serving="b"
else:
if random() < probb:
scoreb += 1
else:
serving="a"
return scorea, scoreb
#比赛结束
def gameover(a,b): #正常比赛结束
return a==11 or b==11
def gameover2(a,b): #进行抢12比赛结束
if abs((a-b))>=2:
return a,b
#输出数据
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()
proba, probb, n = printinputs()
winsa, winsb = simngames(n, proba, probb)
printsummary(winsa, winsb)
main()
标签:winsb,winsa,scorea,scoreb,probb,proba,体育竞技,模拟 From: https://www.cnblogs.com/lzk-95uu/p/17928007.html
# 进行n场比赛
def simngames(n, proba, probb):
winsa, winsb = 0, 0
for i in range(n):
for j in range(5): #进行5局3胜的比赛
scorea, scoreb = simonegame(proba, probb)
if scorea > scoreb:
winsa += 1
else:
winsb += 1
return winsa,winsb