import random
def play_one_game(prob_a, prob_b):
"""
模拟一局乒乓球比赛,先得11分且领先2分者胜。
prob_a: 选手A每球得分概率
prob_b: 选手B每球得分概率 (通常 prob_b = 1 - prob_a)
返回获胜方 'A' 或 'B'
"""
score_a = 0
score_b = 0
while True:
# 模拟每一球
if random.random() < prob_a:
score_a += 1
else:
score_b += 1
# 判断是否结束
if (score_a >= 11 or score_b >= 11) and abs(score_a - score_b) >= 2:
break
return 'A' if score_a > score_b else 'B'
def play_one_match(prob_a, prob_b, best_of=7):
"""
模拟一场比赛(多局),采用七局四胜制(默认)。
best_of: 总局数,7为七局四胜,5为五局三胜。
返回获胜方 'A' 或 'B'
"""
wins_a = 0
wins_b = 0
target = best_of // 2 + 1 # 四胜或三胜
while wins_a < target and wins_b < target:
winner = play_one_game(prob_a, prob_b)
if winner == 'A':
wins_a += 1
else:
wins_b += 1
return 'A' if wins_a > wins_b else 'B'
def simulate_matches(prob_a, prob_b, num_matches, best_of=7):
"""
模拟多场比赛,统计胜率
"""
wins_a = 0
for _ in range(num_matches):
if play_one_match(prob_a, prob_b, best_of) == 'A':
wins_a += 1
return wins_a / num_matches
def main():
print("===== 乒乓球比赛模拟 (单打七局四胜制) =====")
# 输入选手能力值(每球得分概率)
try:
prob_a = float(input("请输入选手A的每球得分概率 (0~1): "))
prob_b = float(input("请输入选手B的每球得分概率 (0~1): "))
except ValueError:
print("输入无效,使用默认概率 A=0.5, B=0.5")
prob_a, prob_b = 0.5, 0.5
可选比赛类型
print("\n选择比赛类型:")
print("1. 单打(七局四胜)")
print("2. 双打或团体(五局三胜)")
choice = input("请输入选择 (1 或 2): ").strip()
if choice == '2':
best_of = 5
match_type = "五局三胜"
else:
best_of = 7
match_type = "七局四胜"
num_matches = int(input("请输入模拟的场次数量 (例如 1000): "))
win_rate = simulate_matches(prob_a, prob_b, num_matches, best_of)
print(f"\n在 {num_matches} 场 {match_type} 比赛中,选手A的胜率: {win_rate:.2%}")
print(f"选手B的胜率: {1 - win_rate:.2%}")
在右下角生成数字 0142(控制台最后一行输出)
print("\n0142")
if name == "main":
main()