羽毛球比赛规则:
1、21分制,一场3局比赛,3局2胜
2、每球得分制
3、每回合中,取胜的一方加1分
4、当双方均为20分时,领先对方2分的一方赢得该局比赛
5、当双方均为29分时,先取得30分的一方赢得该局比赛
from random import random def printIntro(): print("29号羽毛球比赛(3局2胜)分析") print("这个程序模拟两个选手A和B的某种竞技比赛") print("程序运行需要A和B的能力值(以0到1之间的小数表示)") def getInputs(): a = eval(input("请输入选手A的能力值(0-1): ")) b = eval(input("请输入选手B的能力值(0-1): ")) n = eval(input("模拟比赛的场次: ")) return a, b, n def simNGames(n, probA, probB): sumA, sumB = 0, 0 for i in range(n): winsA, winsB = 0, 0 for j in range(3): scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 if winsA==2: break elif winsB==2: break if winsA==2: sumA+=1 elif winsB==2: sumB+=1 return sumA, sumB def gameOver1(a,b): return a==21 or b==21 def gameOver2(a,b): return abs(a-b)==2 or (a==b==29) def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" while not gameOver1(scoreA, scoreB): if scoreA==20 and scoreB==20:#双方都为20分 scoreA,scoreB=simOneGame1(probA,probB,serving) return scoreA,scoreB elif serving == "A": if random() < probA: scoreA += 1 else: serving="B" else: if random() < probB: scoreB += 1 else: serving="A" return scoreA, scoreB def simOneGame1(probA,probB,serving): scoreA,scoreB = 20,20 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" if scoreA==29 and scoreB==29:#双方均为29分 if serving == "A": if random() < probA: scoreA += 1 else: serving="B" else: if random() < probB: scoreB += 1 else: serving="A" return scoreA, scoreB def printSummary(sumA, sumB): n = sumA + sumB print("竞技分析开始,共模拟{}场比赛".format(n)) print("选手A获胜{}场比赛,占比{:0.1%}".format(sumA, sumA/n)) print("选手B获胜{}场比赛,占比{:0.1%}".format(sumB, sumB/n)) def main(): printIntro() probA, probB, n = getInputs() sumA, sumB = simNGames(n, probA, probB) printSummary(sumA, sumB) main()
原文:https://www.cnblogs.com/jiana/p/12860014.html