乒乓球模拟体育竞赛

发布时间 2023-12-25 22:14:31作者: banbu--

代码

 1 import random
 2 def printIntro():
 3     print("这个程序模拟量个选手A和B的某种竞技比赛")
 4     print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
 5  
 6 def getInputs():
 7     a = eval(input("请输入选手A的能力值(0-1): "))
 8     b = eval(input("请输入选手B的能力值(0-1): "))
 9     n = eval(input("模拟比赛的场次: "))
10     return a, b, n
11  
12 def printSummary(winsA, winsB):
13     n = winsA + winsB
14     print("竞技分析开始, 共模拟{}场比赛".format(n))
15     print("选手A获胜{}场比赛, 占比{:0.1%}".format(winsA, winsA/n))
16     print("选手B获胜{}场比赛, 占比{:0.1%}".format(winsB, winsB/n))
17  
18 def gameOver(a, b):
19     return a == 15 or b == 15
20     
21 def simOneGame(probA, probB):
22     scoreA, scoreB = 0, 0
23     serving = "A"
24     while not gameOver(scoreA, scoreB):
25         if serving == "A":
26             if random.random() < probA:
27                 scoreA += 1
28             else:
29                 serving = "B"
30         else:
31             if random.random() < probB:
32                 scoreB += 1
33             else:
34                 serving = "A"
35     return scoreA, scoreB
36  
37 def simNGames(n ,probA, probB):
38     winsA, winsB = 0, 0
39     for i in range(n):
40         scoreA, scoreB = simOneGame(probA, probB)
41         if scoreA > scoreB:
42             winsA += 1
43         else:
44             winsB += 1
45     return winsA, winsB
46  
47 def main():
48     print("22信计2班,学号后两位:12")
49     printIntro()
50     probA, probB, n = getInputs()
51     winsA, winsB = simNGames(n, probA, probB)
52     printSummary(winsA, winsB)
53 main()

 

运行结果