b.采用排球比賽規則(學號尾號為4,5,6同學必做及格題)。賽制規定: 前4局比賽采用25分制,每個隊只有贏得至少25分,並同時超過對方2分時 ,才勝1局。 正式比賽采用5局3勝制,決勝局的比賽采用15分制,一隊先得8分后,兩隊交換場區,按原位置順序繼續比賽到結束。 在決勝局(第五局)之比賽,先獲15分並領先對方2分為勝。


# -*- 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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM