from random import random
print('学号尾数为9')


#描述比赛的函数
def printIntro():
print("这个程序模拟两个选手A和B的羽毛球竞技比赛")
print("程序运行需要A和B的能力值(以0到1之间的小数表示)")

#用来输入数据的函数 两位选手的能力值 比赛场次 模拟次数
def getInputs():
probA=eval(input("请输入选手A的能力值(0-1):"))
probB=eval(input("请输入选手B的能力值(0-1):"))
n=eval(input("请输入比赛的场次:"))
m=eval(input("请输入模拟次数:"))
return probA,probB,n,m

#比赛结束条件
def gameOver(a,b):
#若有一方先达到二十分,且分差不是2,都未到达30分,则结束。否则未结束
if a>=20 or b>=20:
if(abs(a-b)==2 and a<=29 and b<=29):
return True
else:
print('s')
return a==30 or b==30
else:
return False


#模拟比赛场次,并跟踪记录每个球员赢了多少场比赛
def simNGames(n,probA,probB):
winsA=0
winsB=0
scoreA_is=[]
scoreB_is=[]
for i in range(n):
scoreA,scoreB=simOneGame(probA,probB)
scoreA_is.append(scoreA)
scoreB_is.append(scoreB)
if scoreA>scoreB:
winsA+=1
else:
winsB+=1
return winsA,winsB,scoreA_is,scoreB_is


#模拟一场比赛,需要知道每个球员的概率,返回了两个球员的最终得分
def simOneGame(probA,probB):
scoreA,scoreB=0,0
serving='A'
while not gameOver(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):
if a>=20 and b>=20:
if abs(a-b)==2 and a<=29 and b<=29:
return True
elif a==30 or b==30:
return True
else:
return False
elif (a==21 and b<20) or (b==21 and a<20):
return True
else:
return False


#输出比赛结果
def printSummary(winsA,winsB,m,scoreA_is,scoreB_is):
n=winsA+winsB
print("模型模拟次数为{}".format(m))
print("竞技分析开始,共模拟{}场比赛".format(n))
print("A选手各场次的得分为:")
print(scoreA_is)
print("B选手各场次的得分为:")
print(scoreB_is)
print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA,winsA/n))
print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB,winsB/n))
def main():
printIntro()
probA,probB,n,m=getInputs()
for i in range(m):
winsA,winsB,scoreA_is,scoreB_is=simNGames(n,probA,probB)
printSummary(winsA,winsB,m,scoreA_is,scoreB_is)
main()