模拟乒乓球竞技比赛分析
模拟体育竞技分析:
采用乒乓球比赛规则(学号为23)
点击查看代码
import random
import sys
from PyInstaller import __main__ as pyi
def print_intro():
"""打印程序介绍信息"""
print("""
====================================
乒乓球比赛模拟器(学号23)
====================================
功能:
1. 模拟乒乓球单打比赛(七局四胜制)
2. 计算两个选手/球队的获胜概率
3. 支持自定义比赛次数
====================================
""")
def simulate_game(player_a, player_b):
"""模拟一局比赛"""
score_a = 0
score_b = 0
while not game_over(score_a, score_b):
if random.random() < player_a / (player_a + player_b):
score_a += 1
else:
score_b += 1
return score_a > score_b
def game_over(score_a, score_b):
"""判断一局比赛是否结束"""
if max(score_a, score_b) >= 11 and abs(score_a - score_b) >= 2:
return True
return False
def simulate_match(player_a, player_b, best_of=7):
"""模拟一场比赛(多局)"""
wins_a = 0
wins_b = 0
needed_wins = (best_of // 2) + 1
while wins_a < needed_wins and wins_b < needed_wins:
if simulate_game(player_a, player_b):
wins_a += 1
else:
wins_b += 1
return wins_a > wins_b
def main():
print_intro()
try:
# 输入选手能力和模拟次数
ability_a = float(input("请输入选手A的能力值(0-1): "))
ability_b = float(input("请输入选手B的能力值(0-1): "))
simulations = int(input("请输入模拟次数: "))
if not (0 <= ability_a <= 1 and 0 <= ability_b <= 1):
raise ValueError("能力值必须在0到1之间")
if simulations <= 0:
raise ValueError("模拟次数必须大于0")
# 模拟比赛
wins_a = 0
for _ in range(simulations):
if simulate_match(ability_a, ability_b):
wins_a += 1
wins_b = simulations - wins_a
# 输出结果
print("\n模拟结果:")
print(f"选手A获胜次数: {wins_a} ({wins_a/simulations*100:.1f}%)")
print(f"选手B获胜次数: {wins_b} ({wins_b/simulations*100:.1f}%)")
except ValueError as e:
print(f"输入错误: {e}")
sys.exit(1)
def package():
"""使用PyInstaller打包程序"""
pyi.run([
'--name=乒乓球比赛模拟器',
'--onefile',
'--windowed',
'pingpong_simulator.py'
])
if __name__ == "__main__":
main()
# 如果要打包程序,取消下面的注释
# package()
采用乒乓球规则,同时采用循环赛或者晋级赛形式,模拟分析4个队及以上体育竞技,并输出排名。
点击查看代码
import random
from collections import defaultdict
def print_intro():
print("""
====================================
乒乓球团体比赛模拟系统(学号23)
====================================
功能:
1. 支持4个及以上队伍比赛
2. 可选择循环赛或淘汰赛赛制
3. 输出完整比赛排名
====================================
""")
class Team:
def __init__(self, name, ability):
self.name = name
self.ability = ability
self.wins = 0
self.points = 0
def __repr__(self):
return f"{self.name}(能力值:{self.ability})"
def simulate_game(team1, team2):
"""模拟一局比赛"""
score1 = score2 = 0
while not game_over(score1, score2):
if random.random() < team1.ability / (team1.ability + team2.ability):
score1 += 1
else:
score2 += 1
return score1 > score2
def game_over(score1, score2):
"""乒乓球比赛规则"""
if max(score1, score2) >= 11 and abs(score1 - score2) >= 2:
return True
return False
def simulate_match(team1, team2, best_of=5):
"""模拟一场团体比赛(五局三胜制)"""
wins1 = wins2 = 0
needed_wins = (best_of // 2) + 1
while wins1 < needed_wins and wins2 < needed_wins:
if simulate_game(team1, team2):
wins1 += 1
else:
wins2 += 1
# 更新队伍积分(胜者得2分,败者得1分)
if wins1 > wins2:
team1.points += 2
team2.points += 1
return team1
else:
team2.points += 2
team1.points += 1
return team2
def round_robin(tournament):
"""循环赛制"""
print("\n=== 循环赛开始 ===")
teams = tournament.teams
n = len(teams)
for i in range(n):
for j in range(i+1, n):
winner = simulate_match(teams[i], teams[j])
winner.wins += 1
print(f"{teams[i].name} vs {teams[j].name} → 胜者: {winner.name}")
def knockout(tournament):
"""淘汰赛制"""
print("\n=== 淘汰赛开始 ===")
teams = tournament.teams.copy()
round_num = 1
while len(teams) > 1:
print(f"\n第{round_num}轮淘汰赛:")
winners = []
for i in range(0, len(teams), 2):
if i+1 < len(teams):
team1, team2 = teams[i], teams[i+1]
winner = simulate_match(team1, team2)
winners.append(winner)
print(f"{team1.name} vs {team2.name} → 胜者: {winner.name}")
else:
# 轮空队伍直接晋级
winners.append(teams[i])
print(f"{teams[i].name} 轮空自动晋级")
teams = winners
round_num += 1
return teams[0]
class Tournament:
def __init__(self, teams):
self.teams = [Team(name, ability) for name, ability in teams.items()]
def print_ranking(self):
"""根据积分和胜场数排序"""
sorted_teams = sorted(self.teams, key=lambda x: (-x.points, -x.wins, -x.ability))
print("\n=== 最终排名 ===")
print("排名\t队伍\t\t积分\t胜场\t能力值")
for i, team in enumerate(sorted_teams, 1):
print(f"{i}\t{team.name:10}\t{team.points}\t{team.wins}\t{team.ability:.2f}")
def main():
print_intro()
# 示例队伍数据(可修改)
teams = {
"中国队": 0.9,
"日本队": 0.8,
"德国队": 0.7,
"韩国队": 0.75,
"瑞典队": 0.65,
"法国队": 0.6
}
tournament = Tournament(teams)
print("参赛队伍:")
for team in tournament.teams:
print(f"- {team}")
choice = input("\n请选择赛制 (1-循环赛 2-淘汰赛): ")
if choice == "1":
round_robin(tournament)
elif choice == "2":
champion = knockout(tournament)
print(f"\n冠军是: {champion.name}!")
else:
print("无效选择,默认使用循环赛")
round_robin(tournament)
tournament.print_ranking()
if __name__ == "__main__":
main()
循环赛
打包