import random
import sys

def print_intro():
    """打印程序介绍信息"""
    print("""
    ====================================
    排球比赛模拟程序(学号后两位:04)
    ====================================
    程序功能:
    1. 模拟排球比赛过程,遵循正式比赛规则
    2. 前4局25分制,需赢2分以上
    3. 决胜局15分制,需赢2分以上
    4. 5局3胜制
    5. 计算两队获胜概率
    ====================================
    """)

def get_input():
    """获取用户输入"""
    while True:
        try:
            probA = float(input("请输入队伍A的能力值(0-1): "))
            probB = float(input("请输入队伍B的能力值(0-1): "))
            n = int(input("请输入模拟比赛次数: "))
            if 0 <= probA <= 1 and 0 <= probB <= 1 and n > 0:
                return probA, probB, n
            else:
                print("输入无效,请重新输入。")
        except ValueError:
            print("请输入有效的数字。")

def sim_one_game(probA, probB, is_final=False):
    """模拟一局比赛"""
    scoreA, scoreB = 0, 0
    serving = 'A'  # 发球方
    target = 15 if is_final else 25
    
    while not game_over(scoreA, scoreB, is_final):
        if random.random() < probA if serving == 'A' else probB:
            # 发球方得分
            if serving == 'A':
                scoreA += 1
            else:
                scoreB += 1
        else:
            # 接球方得分,交换发球权
            if serving == 'A':
                serving = 'B'
            else:
                serving = 'A'
            
            if serving == 'A':
                scoreA += 1
            else:
                scoreB += 1
    
    return scoreA, scoreB

def game_over(scoreA, scoreB, is_final):
    """判断一局比赛是否结束"""
    target = 15 if is_final else 25
    if is_final:
        return (scoreA >= target or scoreB >= target) and abs(scoreA - scoreB) >= 2
    else:
        return (scoreA >= target or scoreB >= target) and abs(scoreA - scoreB) >= 2

def sim_one_match(probA, probB):
    """模拟一场完整的比赛(5局3胜)"""
    winsA, winsB = 0, 0
    
    for i in range(5):
        is_final = (i == 4)  # 第5局是决胜局
        scoreA, scoreB = sim_one_game(probA, probB, is_final)
        
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
        
        # 如果一方已经赢得3局,比赛结束
        if winsA == 3 or winsB == 3:
            break
    
    return winsA, winsB

def sim_n_matches(probA, probB, n):
    """模拟n场比赛"""
    winsA, winsB = 0, 0
    
    for _ in range(n):
        matchA, matchB = sim_one_match(probA, probB)
        if matchA > matchB:
            winsA += 1
        else:
            winsB += 1
    
    return winsA, winsB

def print_summary(winsA, winsB):
    """打印比赛结果摘要"""
    n = winsA + winsB
    print("\n模拟比赛结果分析:")
    print("="*40)
    print(f"总比赛场次: {n}")
    print(f"队伍A获胜场次: {winsA} 胜率: {winsA/n:.1%}")
    print(f"队伍B获胜场次: {winsB} 胜率: {winsB/n:.1%}")
    print("="*40)

def main():
    """主程序"""
    print_intro()
    probA, probB, n = get_input()
    winsA, winsB = sim_n_matches(probA, probB, n)
    print_summary(winsA, winsB)

if __name__ == '__main__':
    main()

 

posted on 2025-06-23 11:43  1235yyq  阅读(10)  评论(0)    收藏  举报