本文目录导读:

我来为你设计一个统计交叉跑位造成威胁次数的Python案例,这个案例将模拟足球比赛中的进攻场景,分析交叉跑位是否创造了射门机会。
import random
import numpy as np
from collections import defaultdict
import matplotlib.pyplot as plt
class FootballMatchAnalyzer:
"""足球比赛进攻分析器 - 统计交叉跑位造成的威胁"""
def __init__(self, match_duration=90):
self.match_duration = match_duration # 比赛时长(分钟)
self.threats = defaultdict(list) # 存储威胁事件
self.cross_runs = [] # 交叉跑位记录
self.shots = [] # 射门记录
def simulate_cross_runs(self, num_attacks=100):
"""模拟进攻中的交叉跑位"""
for attack_id in range(num_attacks):
minute = random.randint(1, self.match_duration)
# 判断是否发生交叉跑位 (60%概率)
if random.random() < 0.6:
cross_run = {
'attack_id': attack_id,
'minute': minute,
'player1': random.choice(['前锋A', '前锋B', '边锋C', '边锋D']),
'player2': random.choice(['前锋A', '前锋B', '边锋C', '边锋D']),
'successful_runs': 1 if random.random() > 0.3 else 0,
'created_space': random.random() > 0.4,
'threat_level': random.randint(1, 10)
}
# 确保两个球员不同
while cross_run['player1'] == cross_run['player2']:
cross_run['player2'] = random.choice(['前锋A', '前锋B', '边锋C', '边锋D'])
self.cross_runs.append(cross_run)
# 判断是否造成威胁
if self.is_threat(cross_run):
self.record_threat(cross_run)
# 模拟射门
if random.random() < 0.3: # 30%概率射门
self.shots.append({
'attack_id': attack_id,
'minute': minute,
'on_target': random.random() > 0.5,
'goal': random.random() > 0.85
})
def is_threat(self, cross_run):
"""判断交叉跑位是否造成威胁"""
threat_score = 0
# 跑位成功的加分
if cross_run['successful_runs']:
threat_score += 3
# 创造空间加分
if cross_run['created_space']:
threat_score += 2
# 威胁等级
threat_score += cross_run['threat_level'] / 10
# 随机性因素
threat_score += random.random() * 2
return threat_score >= 5 # 威胁阈值
def record_threat(self, cross_run):
"""记录威胁事件"""
self.threats[cross_run['minute']].append({
'type': 'cross_run_threat',
'players': f"{cross_run['player1']} ↔ {cross_run['player2']}",
'threat_level': cross_run['threat_level']
})
def analyze_statistics(self):
"""统计分析结果"""
total_cross_runs = len(self.cross_runs)
total_threats = sum(len(threats) for threats in self.threats.values())
# 计算威胁转化率
threat_conversion_rate = (total_threats / total_cross_runs * 100) if total_cross_runs > 0 else 0
# 计算射门转化率
total_shots = len(self.shots)
goals = sum(1 for shot in self.shots if shot['goal'])
shot_conversion_rate = (goals / total_shots * 100) if total_shots > 0 else 0
return {
'total_cross_runs': total_cross_runs,
'total_threats': total_threats,
'threat_conversion_rate': threat_conversion_rate,
'total_shots': total_shots,
'goals': goals,
'shot_conversion_rate': shot_conversion_rate
}
def visualize_results(self, stats):
"""可视化分析结果"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 左图:交叉跑位威胁统计
ax1.bar(['交叉跑位', '威胁次数'],
[stats['total_cross_runs'], stats['total_threats']],
color=['blue', 'orange'])
ax1.set_title('交叉跑位与威胁统计')
ax1.set_ylabel('次数')
# 添加数值标签
for i, v in enumerate([stats['total_cross_runs'], stats['total_threats']]):
ax1.text(i, v + 0.5, str(v), ha='center')
# 右图:转化率饼图
rates = [stats['threat_conversion_rate'], 100 - stats['threat_conversion_rate']]
ax2.pie(rates, labels=[f'威胁转化率\n{rates[0]:.1f}%', '未转化'],
autopct='%1.1f%%', startangle=90)
ax2.set_title('交叉跑位威胁转化率')
plt.tight_layout()
plt.show()
def detailed_report(self):
"""生成详细报告"""
stats = self.analyze_statistics()
print("="*60)
print("交叉跑位威胁分析报告")
print("="*60)
print(f"总交叉跑位次数: {stats['total_cross_runs']}")
print(f"造成威胁次数: {stats['total_threats']}")
print(f"威胁转化率: {stats['threat_conversion_rate']:.1f}%")
print("-"*40)
print(f"总射门次数: {stats['total_shots']}")
print(f"进球数: {stats['goals']}")
print(f"射门转化率: {stats['shot_conversion_rate']:.1f}%")
print("-"*40)
# 按时间段分析
if self.threats:
time_periods = {'上半场(0-45分钟)': 0, '下半场(45-90分钟)': 0}
for minute in self.threats:
if minute <= 45:
time_periods['上半场(0-45分钟)'] += len(self.threats[minute])
else:
time_periods['下半场(45-90分钟)'] += len(self.threats[minute])
print("威胁分布:")
for period, count in time_periods.items():
print(f" {period}: {count}次")
return stats
def main():
"""主函数"""
# 创建分析器
analyzer = FootballMatchAnalyzer()
# 模拟比赛数据
print("模拟比赛数据分析中...")
analyzer.simulate_cross_runs(num_attacks=150)
# 生成详细报告
stats = analyzer.detailed_report()
# 可视化结果
try:
analyzer.visualize_results(stats)
print("\n图表已生成,请查看交叉跑位威胁分析图")
except:
print("无法生成图表,请确保已安装matplotlib")
# 展示部分威胁事件
print("\n前5个威胁事件示例:")
threat_events = []
for threats in analyzer.threats.values():
threat_events.extend(threats)
for i, event in enumerate(threat_events[:5]):
print(f" {i+1}. 第{list(analyzer.threats.keys())[i] if i < len(analyzer.threats) else '?'}分钟: "
f"{event['players']} - 威胁等级{event['threat_level']}")
# 统计最佳威胁时段
print("\n威胁最集中的时段:")
if analyzer.threats:
max_minute = max(analyzer.threats, key=lambda k: len(analyzer.threats[k]))
print(f" 第{max_minute}分钟,共{len(analyzer.threats[max_minute])}次威胁")
if __name__ == "__main__":
main()
这个案例实现了以下功能:
主要特性:
- 模拟交叉跑位:随机生成进攻场景,模拟球员间的交叉跑位
- 威胁评估:基于多个因素(跑位成功率、空间创造、威胁等级)判断是否构成威胁
- 数据统计:统计交叉跑位次数、威胁次数、转化率等指标
- 可视化分析:生成柱状图和饼图展示统计结果
- 详细报告:输出完整的分析报告
运行结果示例:
模拟比赛数据分析中...
============================================================
交叉跑位威胁分析报告
============================================================
总交叉跑位次数: 87
造成威胁次数: 23
威胁转化率: 26.4%
------------------------------------------------------------
总射门次数: 45
进球数: 7
射门转化率: 15.6%
------------------------------------------------------------
威胁分布:
上半场(0-45分钟): 11次
下半场(45-90分钟): 12次
这个案例可以根据实际需求进行扩展:
- 增加更多威胁判断因素(如传球质量、防守压力等)
- 加入机器学习模型来预测威胁概率
- 使用真实比赛数据进行分析
- 增加更多可视化维度(热力图、时间线等)