import random # 打印程序的介绍性信息 def printIntro(): print("本程序将模拟乒乓球比赛的过程,并计算两个球员(或球队)的获胜概率。") print("学号:31") print("姓名:赖章智") # 获取用户输入 def getInputs(): probA = float(input("请输入球员A(或球队A)的能力值(0到1之间的数): ")) probB = float(input("请输入球员B(或球队B)的能力值(0到1之间的数): ")) n = int(input("请输入模拟比赛的次数: ")) return probA, probB, n # 模拟一场比赛 def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" while scoreA < 11 and scoreB < 11: if serving == "A": if random.random() < probA: scoreA += 1 serving = "B" else: serving = "B" else: if random.random() < probB: scoreB += 1 serving = "A" else: serving = "A" # 检查是否有一方达到10分,如果是,则需要再多得两分才能获胜 if scoreA == 10 or scoreB == 10: while (scoreA == 10 and scoreB < 12) or (scoreB == 10 and scoreA < 12): if serving == "A": if random.random() < probA: scoreA += 1 break else: serving = "B" else: if random.random() < probB: scoreB += 1 break else: serving = "A" return scoreA > scoreB # 模拟多场比赛并计算获胜概率 def simNGames(probA, probB, n): winsA = sum(simOneGame(probA, probB) for _ in range(n)) winsB = n - winsA probWinA = winsA / n probWinB = winsB / n return probWinA, probWinB
体育竞技模拟
最新推荐文章于 2024-09-16 14:49:33 发布