大作业至乒乓球赛式模拟
from random import random
def print_intro():
print("学号后两位:21")
print("乒乓球比赛模拟器")
print("模拟两名选手之间的单局比赛(11分制)")
print("能力值为0-1之间的小数,表示赢得1分的概率")
def get_inputs():
a = float(input("选手A的能力值(0-1):"))
b = float(input("选手B的能力值(0-1):"))
n = int(input("模拟比赛的场次:"))
return a, b, n
def simulate_games(n, prob_a, prob_b):
wins_a, wins_b = 0, 0
for _ in range(n):
score_a, score_b = simulate_game(prob_a, prob_b)
if score_a > score_b:
wins_a += 1
else:
wins_b += 1
return wins_a, wins_b
def simulate_game(prob_a, prob_b):
score_a, score_b = 0, 0
serving = "A" # 初始发球方
while not is_game_over(score_a, score_b):
if serving == 'A':
if random() < prob_a:
score_a += 1
else:
score_b += 1
serving = 'B'
else:
if random() < prob_b:
score_b += 1
else:
score_a += 1
serving = 'A'
return score_a, score_b
def is_game_over(a, b):
if (a >= 11 or b >= 11) and abs(a - b) >= 2:
return True
if a >= 21 or b >= 21:
return True
return False
def print_results(wins_a, wins_b):
total = wins_a + wins_b
print("\n模拟结果:")
print(f"选手A获胜{wins_a}场,胜率{wins_a/total:.1%}")
print(f"选手B获胜{wins_b}场,胜率{wins_b/total:.1%}")
def main():
print_intro()
prob_a, prob_b, n = get_inputs()
wins_a, wins_b = simulate_games(n, prob_a, prob_b)
print_results(wins_a, wins_b)
if name == "main":
main()

浙公网安备 33010602011771号