1. 程式人生 > 實用技巧 >乒乓球比賽規則模擬體育分析

乒乓球比賽規則模擬體育分析

from random import random 
def printIntro():          #列印程式介紹資訊
    print("12號朱益民進行比賽分析結果:")
    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): # 進行N場比賽 winsA, winsB = 0, 0 for i in range(n): for j in range(5): #進行5局3勝的比賽 scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else
: winsB += 1 return winsA, winsB def gameOver(a,b): #正常比賽結束 return a==11 or b==11 def gameOver2(a,b): #進行搶12比賽結束 return a==12 or b==12 def simOneGame(probA, probB): #進行一場比賽 scoreA, scoreB = 0, 0 #初始化AB的得分 serving = "A" while
not gameOver(scoreA, scoreB): #用while迴圈來執行比賽 if scoreA==10 and scoreB==10: return(simtwoGame2(probA,probB)) if serving == "A": if random() < probA: ##用隨機數生成勝負 scoreA += 1 else: serving="B" else: if random() < probB: scoreB += 1 else: serving="A" return scoreA, scoreB def simtwoGame2(probA,probB): scoreA,scoreB=10,10 serving = "A" #假如先讓隊伍A發球 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" return scoreA, scoreB def printSummary(winsA, winsB): n = winsA + winsB print("競技分析開始,共模擬{}場比賽".format(n)) print("隊伍A獲勝{}場比賽,佔比{:0.1%}".format(winsA, winsA/n)) print("隊伍B獲勝{}場比賽,佔比{:0.1%}".format(winsB, winsB/n)) def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB) main()