1. 程式人生 > 實用技巧 >羽毛球模擬競技

羽毛球模擬競技

 1 from random import random
 2 #第一階段
 3 def printIntro():
 4     print("模擬兩個選手A和B的羽毛球比賽")
 5     print("程式執行需要A和B的能力值(以0到1之間的小數表示)")
 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 def
simNGames(n, probA, probB): 12 winsA, winsB = 0, 0 13 for i in range(n): #將模擬n場比賽分解為n次模擬一場比賽 14 scoreA, scoreB = simOneGame(probA, probB) 15 if scoreA > scoreB: 16 winsA += 1 17 else: 18 winsB += 1 19 return winsA, winsB 20 def printSummary(winsA, winsB):
21 n = winsA + winsB 22 print("羽毛球比賽分析開始,共模擬{}場比賽".format(n)) 23 print("選手A獲勝{}場比賽,佔比{:0.1%}".format(winsA, winsA/n)) 24 0.8 25 print("選手B獲勝{}場比賽,佔比{:0.1%}".format(winsB, winsB/n)) 26 def main(): 27 printIntro() 28 probA, probB, n = getInputs() 29 winsA, winsB = simNGames(n, probA, probB)
30 printSummary(winsA, winsB) 31 #第二階段 32 def simOneGame(probA, probB): 33 scoreA, scoreB = 0, 0 34 serving = "A" 35 while not gameOver(scoreA, scoreB): 36 if serving == "A": 37 if random() < probA: 38 scoreA += 1 39 else: 40 serving="B" 41 else: 42 if random() < probB: 43 scoreB += 1 44 else: 45 serving="A" 46 return scoreA, scoreB 47 #第三階段 48 def gameOver(a,b): 49 if (a>=20 and b>=20): 50 if(abs(a-b)==2 and a<=29 and b<=29): 51 return True 52 53 else: 54 return a==30 or b==30 55 else: 56 return False 57 58 main() 59 60 print("學號為17")