本文目录导读:

我来给你设计一个实时展示场上优势的Python案例,这个案例将模拟一个竞技场数据分析,实时计算双方的优势指标。
完整案例:实时优势分析系统
import random
import time
import pandas as pd
import numpy as np
from collections import deque
from datetime import datetime
class RealTimeAdvantageAnalyzer:
"""实时优势分析器 - 模拟竞技场数据分析"""
def __init__(self, window_size=20):
# 存储历史数据
self.window_size = window_size
self.team_a_data = deque(maxlen=window_size)
self.team_b_data = deque(maxlen=window_size)
# 当前状态
self.current_score_a = 0
self.current_score_b = 0
self.current_possession = 'A' # 球权归属
self.current_phase = '进攻' # 当前阶段
# 历史优势记录
self.advantage_history = []
def generate_events(self):
"""生成模拟比赛事件"""
events_pool = [
('得分', 2, '投篮命中'),
('得分', 3, '三分命中'),
('篮板', 1, '防守篮板'),
('抢断', 1, '抢断成功'),
('助攻', 1, '助攻成功'),
('失误', -1, '失误'),
('犯规', -0.5, '犯规'),
('盖帽', 1, '盖帽成功'),
('罚球', 1, '罚球命中'),
('进攻篮板', 1, '进攻篮板'),
('快攻', 1, '快攻得分'),
('暂停', 0.5, '战术暂停'),
('换人', 0.3, '阵容调整'),
('失误', -0.8, '传球失误'),
('远投', 2, '超远三分')
]
# 随机选择事件
event_type, value, desc = random.choice(events_pool)
# 随机选择事件归属队伍
team = 'A' if random.random() < 0.5 + self.calculate_team_bonus() else 'B'
# 更新球权
if random.random() < 0.3:
self.current_possession = team
# 更新阶段
phases = ['进攻', '防守', '转换', '阵地战']
self.current_phase = random.choice(phases)
return {
'timestamp': datetime.now().strftime('%H:%M:%S'),
'team': team,
'event_type': event_type,
'value': value,
'desc': desc,
'possession': self.current_possession,
'phase': self.current_phase
}
def calculate_team_bonus(self):
"""计算队伍优势加成"""
if len(self.team_a_data) > 0 and len(self.team_b_data) > 0:
avg_a = np.mean(self.team_a_data)
avg_b = np.mean(self.team_b_data)
return (avg_a - avg_b) / 100 # 简单的优势加成
return 0
def process_event(self, event):
"""处理事件并更新数据"""
team = event['team']
value = event['value']
if team == 'A':
self.team_a_data.append(value)
if event['event_type'] == '得分':
self.current_score_a += abs(value)
else:
self.team_b_data.append(value)
if event['event_type'] == '得分':
self.current_score_b += abs(value)
def calculate_metrics(self):
"""计算综合优势指标"""
metrics = {
'team_a_score': self.current_score_a,
'team_b_score': self.current_score_b,
'team_a_avg': np.mean(self.team_a_data) if self.team_a_data else 0,
'team_b_avg': np.mean(self.team_b_data) if self.team_b_data else 0,
'team_a_momentum': self.calculate_momentum('A'),
'team_b_momentum': self.calculate_momentum('B'),
'possession_control': self.current_possession,
'current_phase': self.current_phase
}
# 计算总优势
metrics['total_advantage'] = (
metrics['team_a_avg'] - metrics['team_b_avg'] +
metrics['team_a_momentum'] - metrics['team_b_momentum'] +
(self.current_score_a - self.current_score_b) * 0.1
)
return metrics
def calculate_momentum(self, team):
"""计算队伍势头"""
if team == 'A':
data = list(self.team_a_data)
else:
data = list(self.team_b_data)
if len(data) >= 3:
# 计算最近3个事件的势头
recent = data[-3:]
return np.mean(recent) * 0.5
return 0
def determine_winner(self, metrics):
"""判断当前优势方"""
advantage = metrics['total_advantage']
if advantage > 1.5:
return 'A队大优势', 'advantage'
elif advantage > 0.5:
return 'A队小优势', 'slight'
elif advantage < -1.5:
return 'B队大优势', 'disadvantage'
elif advantage < -0.5:
return 'B队小优势', 'slight_disadvantage'
else:
return '势均力敌', 'balanced'
def format_display(self, metrics, result):
"""格式化显示数据"""
status, level = result
# 创建进度条
def create_progress_bar(value, max_value=10):
"""创建可视化进度条"""
if value > 0:
progress = min(int(value / max_value * 20), 20)
return '█' * progress + '░' * (20 - progress)
else:
value_abs = abs(value)
progress = min(int(value_abs / max_value * 20), 20)
return '░' * 20 + ' ← B队' + '█' * min(progress, 20)
display = f"""
╔══════════════════════════════════════════════════════════════════╗
║ 实时优势分析监控系统 ║
╠══════════════════════════════════════════════════════════════════╣
║ 时间: {metrics['timestamp'] if 'timestamp' in metrics else '--:--:--'} ║
║ ║
║ 比分: A队 {metrics['team_a_score']} : {metrics['team_b_score']} B队 ║
║ 球权: {metrics['possession_control']}队 阶段: {metrics['current_phase']} ║
║ ║
║ ┌──────────────────────────────────────────────────────────┐ ║
║ │ 优势分布: │ ║
║ │ 【A队】 ████████████████░░░░ (评分: {metrics['team_a_avg']:.1f}) │ ║
║ │ 【B队】 ██████████░░░░░░░░░░ (评分: {metrics['team_b_avg']:.1f}) │ ║
║ └──────────────────────────────────────────────────────────┘ ║
║ ║
║ 综合优势: {metrics['total_advantage']:.2f} ║
║ 当前局面: 【{status}】 ║
║ 优势柱状图: ║
║ A队 ← {create_progress_bar(metrics['total_advantage'])} → B队 ║
║ ║
║ 势头分析: ║
║ A队势头: {metrics['team_a_momentum']:.2f} B队势头: {metrics['team_b_momentum']:.2f} ║
╠══════════════════════════════════════════════════════════════════╣
║ 最近事件: ║
"""
return display
def run_simulation(self, duration=30):
"""运行实时模拟"""
print("🚀 实时优势分析系统启动...")
print("=" * 60)
start_time = time.time()
while time.time() - start_time < duration:
# 生成并处理事件
event = self.generate_events()
self.process_event(event)
# 计算指标
metrics = self.calculate_metrics()
metrics['timestamp'] = event['timestamp']
# 判断优势方
result = self.determine_winner(metrics)
# 格式化并显示
display = self.format_display(metrics, result)
# 添加最近事件
display += f"║ {event['timestamp']} - {event['event_type']} {event['value']:+.1f} {event['desc']}({event['team']}队) ║\n"
display += "║" + " " * 58 + "║\n"
display += "╚" + "═" * 60 + "╝"
# 清屏并显示
print('\033[2J\033[H') # 清屏并回到顶部
print(display)
# 记录历史
self.advantage_history.append({
'time': event['timestamp'],
'advantage': metrics['total_advantage'],
'result': result[0]
})
# 暂停一下
time.sleep(1)
self.print_summary()
def print_summary(self):
"""打印模拟总结"""
print("\n" + "=" * 60)
print("📊 模拟结束,数据总结:")
print(f"总事件数: {len(self.team_a_data) + len(self.team_b_data)}")
print(f"A队平均评分: {np.mean(self.team_a_data):.2f}")
print(f"B队平均评分: {np.mean(self.team_b_data):.2f}")
print(f"最终比分: {self.current_score_a} : {self.current_score_b}")
# 分析优势变化
if self.advantage_history:
advantages = [h['advantage'] for h in self.advantage_history]
print(f"最大优势: {max(advantages):.2f}")
print(f"最小优势: {min(advantages):.2f}")
print(f"平均优势: {np.mean(advantages):.2f}")
# 绘制简单趋势图
print("\n优势变化趋势:")
trend = ""
for adv in advantages:
if adv > 0:
trend += "📈" if adv > np.mean(advantages) else "📊"
else:
trend += "📉" if adv < np.mean(advantages) else "📊"
print(trend)
# 使用示例
if __name__ == "__main__":
analyzer = RealTimeAdvantageAnalyzer()
analyzer.run_simulation(duration=30) # 运行30秒模拟
可视化版本(带图表)
如果你想要更美观的图表展示,这里是增强版:
import matplotlib.pyplot as plt
from IPython.display import clear_output
import seaborn as sns
def enhanced_visualization(analyzer):
"""增强版可视化图表"""
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# 获取数据
timestamps = [h['time'] for h in analyzer.advantage_history]
advantages = [h['advantage'] for h in analyzer.advantage_history]
# 1. 优势趋势图
axes[0, 0].plot(timestamps, advantages, 'b-', label='优势值')
axes[0, 0].axhline(y=0, color='red', linestyle='--', alpha=0.3)
axes[0, 0].fill_between(timestamps, 0, advantages,
where=[a > 0 for a in advantages],
alpha=0.3, color='green')
axes[0, 0].fill_between(timestamps, 0, advantages,
where=[a < 0 for a in advantages],
alpha=0.3, color='red')
axes[0, 0].set_title('优势变化趋势')
axes[0, 0].set_ylabel('优势值')
axes[0, 0].legend()
# 2. 队伍表现对比
team_data = ['A', 'B']
team_scores = [sum(analyzer.team_a_data), sum(analyzer.team_b_data)]
axes[0, 1].bar(team_data, team_scores, color=['blue', 'orange'])
axes[0, 1].set_title('队伍累计表现')
axes[0, 1].set_ylabel('累计得分')
# 3. 事件分布
if analyzer.advantage_history:
results = [h['result'] for h in analyzer.advantage_history]
from collections import Counter
result_counts = Counter(results)
axes[1, 0].pie(result_counts.values(), labels=result_counts.keys(),
autopct='%1.1f%%')
axes[1, 0].set_title('优势阶段分布')
# 4. 实时统计
if analyzer.advantage_history:
axes[1, 1].hist(advantages, bins=15, alpha=0.7, color='purple')
axes[1, 1].set_title('优势值分布')
axes[1, 1].set_xlabel('优势值')
axes[1, 1].set_ylabel('频次')
plt.tight_layout()
plt.show()
# 使用示例
analyzer = RealTimeAdvantageAnalyzer()
analyzer.run_simulation(duration=30)
enhanced_visualization(analyzer)
代码特点
- 实时性: 每秒更新一次数据,实时显示当前状态
- 多维度分析: 包括比分、球权、阶段、势头等多个维度
- 优势算法: 综合多个因素计算总优势
- 可视化: 提供命令行显示和matplotlib图表两种方式
- 灵活性: 可调整窗口大小、事件类型、权重等参数
这个系统可以应用于体育比赛分析、游戏竞技、市场分析等场景,实时展示双方占优情况,你可以根据具体需求修改事件类型、权重计算方式等参数。