模拟比赛

import random
import matplotlib.pyplot as plt
from collections import defaultdict

乒乓球比赛模拟器

class TableTennisSimulator:
def init(self, player_a, player_b, a_win_prob=0.5):
"""
初始化比赛参数
:param player_a: 选手A名称
:param player_b: 选手B名称
:param a_win_prob: A赢得1分的概率(0-1)
"""
self.players = (player_a, player_b)
self.prob = a_win_prob
self.stats = defaultdict(int) # 统计比赛数据

def play_point(self):
    """模拟1分的争夺"""
    return random.random() < self.prob

def play_game(self):
    """模拟1局比赛(11分制,10平后需赢2分)"""
    score_a, score_b = 0, 0
    while not self.is_game_over(score_a, score_b):
        if self.play_point():
            score_a += 1
        else:
            score_b += 1
    return score_a, score_b

@staticmethod
def is_game_over(a, b):
    """判断一局是否结束"""
    if max(a, b) >= 11 and abs(a - b) >= 2:
        return True
    return False

def play_match(self, best_of=7):
    """
    模拟一场比赛(默认七局四胜)
    :param best_of: 总局数(7=四胜制,5=三胜制)
    """
    wins_a, wins_b = 0, 0
    max_games = best_of // 2 + 1
    
    while wins_a < max_games and wins_b < max_games:
        game_a, game_b = self.play_game()
        if game_a > game_b:
            wins_a += 1
        else:
            wins_b += 1
        self.stats['total_games'] += 1
    
    winner = self.players[0] if wins_a > wins_b else self.players[1]
    self.stats['matches_played'] += 1
    self.stats[winner] += 1
    return winner, wins_a, wins_b

def simulate_season(self, n_matches=100, best_of=7):
    """模拟多场比赛并统计结果"""
    results = []
    for _ in range(n_matches):
        results.append(self.play_match(best_of))
    return results

def plot_results(self, results):
    """可视化比赛结果"""
    winners = [r[0] for r in results]
    win_counts = {self.players[0]: winners.count(self.players[0]),
                  self.players[1]: winners.count(self.players[1])}
    
    plt.figure(figsize=(10, 5))
    plt.bar(win_counts.keys(), win_counts.values(), color=['red', 'blue'])
    plt.title(f"乒乓球比赛胜负统计 (共{len(results)}场)")
    plt.ylabel("获胜场次")
    for i, v in enumerate(win_counts.values()):
        plt.text(i, v + 0.5, str(v), ha='center')
    plt.show()

示例使用

if name == "main":
# 创建模拟器 (马龙 vs 樊振东,假设马龙单分胜率55%)
simulator = TableTennisSimulator("小明", "小刚", 0.55)

print("模拟单场七局四胜比赛:")
winner, score_a, score_b = simulator.play_match(best_of=7)
print(f"比赛结果: {winner} 获胜 (比分: {score_a}-{score_b})")

print("\n模拟100场七局四胜赛季:")
results = simulator.simulate_season(n_matches=100, best_of=7)
simulator.plot_results(results)

print("\n模拟双打五局三胜比赛:")
winner, score_a, score_b = simulator.play_match(best_of=5)
print(f"比赛结果: {winner} 获胜 (比分: {score_a}-{score_b})")
posted @ 2025-06-23 14:31  邓雁戈  阅读(13)  评论(0)    收藏  举报