# -*- encoding:utf-8 -*- ''' 模擬排球競技 @author: bpf ''' # 比賽規則: # 1. 采用5局3勝制 # 2. 前四局采用25分制,每個隊只有在贏得至少25分,且同時超過對方2分時才勝一局 # 3. 決勝局(第五局)采用15分制,先獲得15分,且同時超過對方2分為勝 from random import random def printInfo(): ''' 打印程序的功能信息 ''' print("\t\t這個程序模擬2個隊伍A和B的排球競技比賽!") print("\t 程序運行需要隊伍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 NGames(n, probA, probB): ''' 模擬n場比賽 ''' winA, winB = 0, 0 for _ in range(n): scoreA, scoreB = OneGame(probA, probB) if scoreA > scoreB: winA += 1 else: winB += 1 return winA, winB def OneGame(probA, probB): ''' 模擬一場比賽,包括五局 ''' scoreA, scoreB, N = 0, 0, 0 serving = 'A' while not GameOver(N, scoreA, scoreB): if serving == 'A': if random() > probA: scoreB += 1 serving = 'B' else: scoreA += 1 if serving == 'B': if random() > probB: scoreA += 1 serving = 'A' else: scoreB += 1 N += 1 return scoreA, scoreB def GameOver(N, a, b): ''' 定義贏得一局的條件 N: 當前局次(第五局為決勝局) ''' if N <= 4: return (a>=25 and b>=25 and abs(a-b)>=2) else: return (a>=15 and b>=15 and abs(a-b)>=2) def printResult(n, winA, winB): print("競技分析開始,共模擬{}場比賽".format(n)) print("隊伍A獲勝{}場比賽,占比{:0.1%}".format(winA,winA/n)) print("隊伍B獲勝{}場比賽,占比{:0.1%}".format(winB,winB/n)) if __name__ == "__main__": printInfo() probA, probB, n = getInputs() winA, winB = NGames(n, probA, probB) printResult(n, winA, winB)