综合python案例,轮转换位防守默契度?

wen python案例 1

我来为您设计一个综合性Python案例,模拟篮球轮转换位防守的默契度评估系统,这个系统会综合运用多项Python技术。

综合python案例,轮转换位防守默契度?

🏀 篮球轮转换位防守默契度分析系统

系统架构设计

# 文件结构
"""
basketball_defense_system/
├── defense_analysis.py     # 主分析系统
├── player_module.py        # 球员模块
├── simulation.py          # 模拟模块
├── visualization.py       # 可视化模块
├── data_processing.py     # 数据处理模块
└── ui_interface.py        # 界面交互模块
"""

核心代码实现

球员模块 (player_module.py)

from dataclasses import dataclass
from enum import Enum
import random
import json
from typing import List, Dict, Optional
import numpy as np
class Position(Enum):
    PG = "控球后卫"
    SG = "得分后卫"
    SF = "小前锋"
    PF = "大前锋"
    C = "中锋"
class DefensiveRole(Enum):
    PRIMARY = "主要防守"
    HELP = "协防"
    ROTATE = "轮转"
    BOX_OUT = "卡位"
@dataclass
class Player:
    """球员数据类"""
    name: str
    number: int
    position: Position
    height_cm: float
    weight_kg: float
    speed: float  # 移动速度 0-100
    agility: float  # 敏捷度 0-100
    defensive_awareness: float  # 防守意识 0-100
    def __post_init__(self):
        self.x_pos = 0.0
        self.y_pos = 0.0
        self.current_opponent = None
        self.defense_rating = 0.0
        self.communication_score = 0.0
    def calculate_defense_index(self):
        """计算综合防守指数"""
        return (self.speed * 0.3 + 
                self.agility * 0.3 + 
                self.defensive_awareness * 0.4)
    def to_dict(self):
        """转换为字典格式"""
        return {
            'name': self.name,
            'number': self.number,
            'position': self.position.value,
            'height_cm': self.height_cm,
            'weight_kg': self.weight_kg,
            'speed': self.speed,
            'agility': self.agility,
            'defensive_awareness': self.defensive_awareness,
            'defense_index': self.calculate_defense_index()
        }
class Team:
    """篮球队类"""
    def __init__(self, name: str):
        self.name = name
        self.players: List[Player] = []
        self.communication_level = 0.0  # 沟通水平
        self.cohesion = 0.0  # 团队凝聚力
    def add_player(self, player: Player):
        """添加球员"""
        self.players.append(player)
    def get_starting_five(self):
        """获取首发阵容"""
        return self.players[:5]
    def calculate_team_defense(self):
        """计算团队防守能力"""
        if not self.players:
            return 0.0
        defense_scores = [p.calculate_defense_index() for p in self.players]
        return np.mean(defense_scores)

防守轮转模拟模块 (simulation.py)

import numpy as np
from typing import List, Tuple, Dict
import random
from collections import defaultdict
class DefenseSimulation:
    """防守轮转模拟器"""
    def __init__(self, team: Team):
        self.team = team
        self.rotation_history = []
        self.coordination_metrics = defaultdict(list)
        self.switch_efficiency = []
    def defensive_rotation(self, attacker_positions: List[Tuple[float, float]], 
                          ball_position: Tuple[float, float], 
                          play_type: str = "pick_and_roll"):
        """
        模拟防守轮转
        play_type: pick_and_roll, drive, post_up, outside_shooting
        """
        defenders = self.team.get_starting_five()
        # 初始化球员位置
        positions = self._initial_floor_positioning()
        # 根据不同进攻类型执行不同防守策略
        if play_type == "pick_and_roll":
            rotation_result = self._pick_and_roll_defense(defenders, attacker_positions, ball_position)
        elif play_type == "drive":
            rotation_result = self._drive_defense(defenders, attacker_positions, ball_position)
        elif play_type == "post_up":
            rotation_result = self._post_up_defense(defenders, attacker_positions, ball_position)
        else:
            rotation_result = self._outside_shooting_defense(defenders, attacker_positions, ball_position)
        # 计算协同度
        coordination_score = self._calculate_coordination(rotation_result)
        return rotation_result, coordination_score
    def _initial_floor_positioning(self):
        """初始站位"""
        # 简单的2-3区域联防站位
        positions = {
            'top': (25, 45),  # 弧顶
            'left_wing': (12, 30),  # 左侧翼
            'right_wing': (38, 30),  # 右侧翼
            'left_post': (10, 20),  # 左低位
            'right_post': (40, 20)  # 右低位
        }
        return positions
    def _pick_and_roll_defense(self, defenders, attackers, ball_pos):
        """挡拆防守"""
        rotation = []
        # 假设:1号位持球,5号位挡拆
        ball_handler = attackers[0]
        screener = attackers[4]
        # 防守策略:
        # 1. 持球者防守者上提
        # 2. 掩护者防守者实施蹲坑或延阻
        # 3. 其他防守者准备轮转补防
        strategy = {
            "screen_defense": random.choice(["show", "trap", "switch", "hedge"]),
            "rotation_type": random.choice(["drop", "switch", "help_and_recover"])
        }
        # 模拟防守动作
        defensive_actions = []
        for i, defender in enumerate(defenders):
            # 根据防守策略计算移动
            action = {
                "player": defender.name,
                "initial_position": list(defender.x_pos),
                "defensive_role": self._assign_defensive_role(defender, ball_handler, screener)
            }
            # 计算移动距离
            move_distance = random.uniform(2.0, 8.0)
            action["move_distance"] = move_distance
            # 评估防守效率
            speed_factor = defender.speed / 100
            reaction_time = random.uniform(0.2, 0.8) * (1 - speed_factor)
            action["reaction_time"] = reaction_time
            defensive_actions.append(action)
        # 更新防守评分
        for defender in defenders:
            self._update_defender_score(defender, defensive_actions)
        return {
            "strategy": strategy,
            "actions": defensive_actions,
            "effectiveness": self._evaluate_defense(defensive_actions)
        }
    def _assign_defensive_role(self, defender, ball_handler, screener):
        """分配防守职责"""
        roles = [DefensiveRole.HELP, DefensiveRole.ROTATE, DefensiveRole.BOX_OUT]
        # 根据位置分配主要防守任务
        if defender.current_opponent == ball_handler:
            return DefensiveRole.PRIMARY
        elif defender.current_opponent == screener:
            return DefensiveRole.PRIMARY
        else:
            return random.choice(roles)
    def _update_defender_score(self, defender, actions):
        """更新防守者评分"""
        # 计算基础防守评分
        base_score = defender.calculate_defense_index()
        # 根据动作效率调整
        action_scores = []
        for action in actions:
            if action["player"] == defender.name:
                efficiency = 1.0 / (action["reaction_time"] + 0.5)
                action_scores.append(efficiency)
        if action_scores:
            base_score *= np.mean(action_scores)
        defender.defense_rating = base_score
        defender.communication_score = random.uniform(0.6, 1.0)
    def _evaluate_defense(self, actions):
        """评估防守效果"""
        if not actions:
            return 0.0
        total_moves = sum(a["move_distance"] for a in actions)
        avg_reaction = np.mean([a["reaction_time"] for a in actions])
        # 综合评分
        score = (total_moves * 0.3 + (1 - avg_reaction) * 0.7) * 100
        return min(100, score)
    def _calculate_coordination(self, rotation_result):
        """计算防守配合默契度"""
        actions = len(rotation_result["actions"])
        effectiveness = rotation_result["effectiveness"]
        # 模拟队友间的沟通信号
        communication_clarity = random.uniform(0.7, 1.0)
        timing_alignment = random.uniform(0.6, 1.0)
        coordination = (effectiveness * 0.6 + 
                       communication_clarity * 0.2 + 
                       timing_alignment * 0.2)
        self.coordination_metrics['coordination'].append(coordination)
        return coordination
    def _drive_defense(self, defenders, attackers, ball_pos):
        """突破防守"""
        # 实施包夹或补防策略
        strategy_choices = ["help", "double_team", "containment"]
        strategy = random.choice(strategy_choices)
        return {
            "strategy": strategy,
            "actions": self._generate_actions(defenders, strategy),
            "effectiveness": random.uniform(70, 95)
        }
    def _post_up_defense(self, defenders, attackers, ball_pos):
        """低位单打防守"""
        # 选择包夹或1v1
        strategy = random.choice(["double_team", "one_on_one"])
        return {
            "strategy": strategy,
            "actions": self._generate_actions(defenders, strategy),
            "effectiveness": random.uniform(75, 90)
        }
    def _outside_shooting_defense(self, defenders, attackers, ball_pos):
        """外线投篮防守"""
        # 实施换防或贴身紧逼
        strategy = random.choice(["switch", "pressure"])
        return {
            "strategy": strategy,
            "actions": self._generate_actions(defenders, strategy),
            "effectiveness": random.uniform(65, 85)
        }
    def _generate_actions(self, defenders, strategy):
        """生成防守动作"""
        actions = []
        for defender in defenders:
            action = {
                "player": defender.name,
                "position": [defender.x_pos, defender.y_pos],
                "strategy": strategy,
                "move_distance": random.uniform(1.0, 6.0),
                "reaction_time": random.uniform(0.1, 0.5)
            }
            actions.append(action)
        return actions
    def run_multiple_plays(self, num_plays: int = 10):
        """运行多个防守回合"""
        results = []
        for i in range(num_plays):
            # 生成随机的进攻场景
            attackers = self._generate_attacking_scenario()
            ball_pos = attackers[0]  # 假设第一个人运球
            # 随机选择进攻类型
            play_types = ["pick_and_roll", "drive", "post_up", "outside_shooting"]
            play_type = random.choice(play_types)
            result = self.defensive_rotation(attackers, ball_pos, play_type)
            results.append(result)
        return results
    def _generate_attacking_scenario(self):
        """生成进攻场景"""
        # 生成攻方5个位置
        positions = []
        court_width = 47  # 球场宽度(英尺)
        court_length = 50  # 半场长度
        for i in range(5):
            x = random.uniform(0, court_width)
            y = random.uniform(0, court_length)
            positions.append((x, y))
        return positions

数据分析模块 (data_processing.py)

import pandas as pd
import numpy as np
from typing import List, Dict
from collections import defaultdict
import json
class DefenseAnalyzer:
    """防守数据分析器"""
    def __init__(self):
        self.data = defaultdict(list)
    def collect_rotation_data(self, simulation_results):
        """收集轮转数据"""
        for result, coordination in simulation_results:
            self.data['coordination'].append(coordination)
            self.data['effectiveness'].append(result['effectiveness'])
            self.data['strategy'].append(result['strategy'])
    def calculate_synergy_score(self):
        """计算团队默契度"""
        if not self.data['coordination']:
            return 0.0
        coordination = np.array(self.data['coordination'])
        effectiveness = np.array(self.data['effectiveness'])
        # 加权评分
        synergy_score = (
            coordination.mean() * 0.6 +
            effectiveness.mean() * 0.4
        )
        return synergy_score
    def get_detailed_report(self):
        """生成详细报告"""
        report = {
            'total_plays': len(self.data['coordination']),
            'avg_coordination': np.mean(self.data['coordination']) if self.data['coordination'] else 0,
            'best_coordination': np.max(self.data['coordination']) if self.data['coordination'] else 0,
            'worst_coordination': np.min(self.data['coordination']) if self.data['coordination'] else 0,
            'strategy_distribution': self._calculate_strategy_distribution()
        }
        return report
    def _calculate_strategy_distribution(self):
        """计算策略分布"""
        strategy_counts = defaultdict(int)
        for strategy in self.data['strategy']:
            if isinstance(strategy, dict):
                strategy_counts[strategy['screen_defense']] += 1
            else:
                strategy_counts[strategy] += 1
        return dict(strategy_counts)
    def save_to_file(self, filename):
        """保存数据到文件"""
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(self.get_detailed_report(), f, ensure_ascii=False, indent=2)

可视化模块 (visualization.py)

import matplotlib.pyplot as plt
import seaborn as sns
from typing import List, Dict
import numpy as np
class DefenseVisualizer:
    """防守可视化器"""
    def __init__(self, player_data):
        self.player_data = player_data
    def plot_defensive_ratings(self):
        """绘制防守评分图"""
        plt.figure(figsize=(10, 6))
        names = [p['name'] for p in self.player_data]
        ratings = [p['defense_index'] for p in self.player_data]
        plt.bar(names, ratings, color='skyblue')
        plt.title('球员防守能力指数')
        plt.xlabel('球员')
        plt.ylabel('防守指数')
        plt.ylim(0, 100)
        plt.show()
        return plt
    def plot_rotation_patterns(self, rotation_data):
        """绘制轮转热力图"""
        plt.figure(figsize=(10, 8))
        # 创建2D热力图数据
        x = [pos[0] for pos in rotation_data.get('positions', [])]
        y = [pos[1] for pos in rotation_data.get('positions', [])]
        if x and y:
            # 如果坐标是3D或2D数组,处理成二维
            if isinstance(x[0], list):
                x_flat = [item for sublist in x for item in sublist]
                y_flat = [item for sublist in y for item in sublist]
            else:
                x_flat = x
                y_flat = y
            # 创建2D直方图
            heatmap, xedges, yedges = np.histogram2d(x_flat, y_flat, bins=20)
            plt.imshow(heatmap.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], 
                      cmap='hot', alpha=0.7)
            plt.colorbar(label='防守频率')
        plt.title('轮转换位防守热力图')
        plt.xlabel('X位置')
        plt.ylabel('Y位置')
        plt.grid(True)
        plt.show()
        return plt
    def plot_team_synergy(self, synergy_history):
        """绘制团队默契度变化"""
        plt.figure(figsize=(12, 6))
        time_steps = range(len(synergy_history))
        plt.plot(time_steps, synergy_history, marker='o', linewidth=2, markersize=8)
        plt.fill_between(time_steps, np.mean(synergy_history) - np.std(synergy_history),
                        np.mean(synergy_history) + np.std(synergy_history), alpha=0.2)
        plt.axhline(y=np.mean(synergy_history), color='r', linestyle='--', label='平均值')
        plt.title('团队防守默契度变化趋势')
        plt.xlabel('防守回合数')
        plt.ylabel('默契度评分')
        plt.legend()
        plt.grid(True)
        plt.show()
        return plt
    def create_comparison_chart(self, team_stats):
        """创建对比图表"""
        fig, axes = plt.subplots(1, 3, figsize=(15, 5))
        # 防守效率
        categories = ['人盯人', '区域联防', '混合防守']
        values = [team_stats.get(cat, 0) for cat in categories]
        axes[0].bar(categories, values, color=['red', 'blue', 'green'])
        axes[0].set_title('防守效率对比')
        axes[0].set_ylabel('效率值')
        # 轮转速度
        rotation_speeds = team_stats.get('rotation_speeds', [])
        if rotation_speeds:
            axes[1].boxplot(rotation_speeds)
            axes[1].set_title('轮转速度分布')
            axes[1].set_ylabel('速度(m/s)')
        # 沟通评分
        communication = team_stats.get('communication', 0)
        axes[2].pie([communication, 100-communication], 
                    labels=['沟通良好', '待改进'],
                    colors=['lightgreen', 'lightcoral'],
                    autopct='%1.1f%%')
        axes[2].set_title('沟通评分')
        plt.tight_layout()
        plt.show()
        return fig

主程序 (defense_analysis.py)

import random
import numpy as np
from typing import List, Dict
import json
import os
from datetime import datetime
import matplotlib.pyplot as plt
class DefenseAnalysisSystem:
    """防守分析主系统"""
    def __init__(self):
        self.team = None
        self.simulator = None
        self.analyzer = None
        self.visualizer = None
        self.session_history = []
    def setup_team(self):
        """建立球队"""
        print("🏀 创建篮球防守分析系统")
        print("="*50)
        # 创建默认球队
        self.team = Team("北京猛虎")
        # 添加球员
        players_data = [
            ("张飞", 23, Position.PG, 185, 82, 88, 85, 90),
            ("王磊", 33, Position.SG, 192, 88, 82, 80, 85),
            ("李强", 9, Position.SF, 198, 95, 75, 78, 86),
            ("钱峰", 15, Position.PF, 205, 105, 72, 75, 82),
            ("孙浩", 55, Position.C, 210, 110, 68, 88, 80)
        ]
        for name, num, pos, h, w, speed, agility, awareness in players_data:
            player = Player(
                name=name, 
                number=num, 
                position=pos,
                height_cm=h, 
                weight_kg=w,
                speed=speed, 
                agility=agility, 
                defensive_awareness=awareness
            )
            self.team.add_player(player)
        print(f"球队 {self.team.name} 创建成功")
        print("\n首发球员:")
        for player in self.team.players:
            print(f"  #{player.number} {player.name} - {player.position.value}")
    def run_simulation(self, num_plays=20):
        """运行模拟"""
        print(f"\n🔄 开始防守轮转模拟 ({num_plays}个回合)...")
        print("="*50)
        # 初始化控制器
        self.simulator = DefenseSimulation(self.team)
        self.analyzer = DefenseAnalyzer()
        # 运行多次模拟
        results = self.simulator.run_multiple_plays(num_plays)
        # 分析数据
        self.analyzer.collect_rotation_data(results)
        # 生成报告
        report = self.analyzer.get_detailed_report()
        synergy_score = self.analyzer.calculate_synergy_score()
        print(f"\n✅ 模拟完成")
        print(f"总防守回合数: {report['total_plays']}")
        print(f"平均默契度: {report['avg_coordination']:.2f}")
        print(f"最佳默契度: {report['best_coordination']:.2f}")
        print(f"最差默契度: {report['worst_coordination']:.2f}")
        print(f"团队综合默契度评分: {synergy_score:.2f}")
        print(f"\n防守策略分布:")
        for strategy, count in report['strategy_distribution'].items():
            print(f"  - {strategy}: {count}次")
        return report, synergy_score
    def visualize_results(self):
        """可视化分析结果"""
        if not self.analyzer or not self.simulator:
            print("请先运行模拟分析")
            return
        # 创建可视化器
        self.visualizer = DefenseVisualizer([p.to_dict() for p in self.team.players])
        # 绘制球员防守能力
        print("\n📊 生成分析图表...")
        self.visualizer.plot_defensive_ratings()
        # 绘制轮转热力图
        rotation_data = {
            'positions': [(p.x_pos, p.y_pos) for p in self.team.players]
        }
        self.visualizer.plot_rotation_patterns(rotation_data)
        # 绘制默契度变化
        if self.simulator.coordination_metrics['coordination']:
            synergy_history = self.simulator.coordination_metrics['coordination']
            self.visualizer.plot_team_synergy(synergy_history)
        # 创建对比图表
        team_stats = {
            '人盯人': np.mean(self.simulator.coordination_metrics['coordination']) * 0.8,
            '区域联防': np.mean(self.simulator.coordination_metrics['coordination']) * 0.9,
            '混合防守': np.mean(self.simulator.coordination_metrics['coordination']),
            'rotation_speeds': [random.uniform(2, 6) for _ in range(10)],
            'communication': self.analyzer.calculate_synergy_score()
        }
        self.visualizer.create_comparison_chart(team_stats)
    def export_report(self, filename="defense_report"):
        """导出报告"""
        if not self.analyzer:
            print("无数据可导出")
            return
        # 生成报告数据
        report = {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "team": self.team.name,
            "players": [p.to_dict() for p in self.team.players],
            "analysis": self.analyzer.get_detailed_report(),
            "synergy_score": self.analyzer.calculate_synergy_score()
        }
        # 保存到文件
        filepath = f"{filename}.json"
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        print(f"\n📝 报告已保存至: {filepath}")
    def generate_improvement_suggestions(self):
        """生成改进建议"""
        if not self.analyzer:
            return
        report = self.analyzer.get_detailed_report()
        synergy_score = self.analyzer.calculate_synergy_score()
        suggestions = []
        # 基于默契度生成建议
        if synergy_score < 50:
            suggestions.append("紧急:团队默契度较低,需要立即进行基础防守训练")
        elif synergy_score < 70:
            suggestions.append("需要加强团队沟通,增加挡拆防守演练次数")
        # 基于最好/最差表现生成建议
        range_score = report['best_coordination'] - report['worst_coordination']
        if range_score > 30:
            suggestions.append("表现不稳定,需要建立更稳定的防守策略")
        # 具体位置建议
        for player in self.team.players:
            if player.speed < 75:
                suggestions.append(f"{player.name}需要提升移动速度以适应快速轮转")
            if player.defensive_awareness < 80:
                suggestions.append(f"{player.name}需要提高防守意识")
        print("\n💡 改进建议:")
        print("-"*50)
        for i, suggestion in enumerate(suggestions, 1):
            print(f"  {i}. {suggestion}")
        if not suggestions:
            print("  祝贺!你的团队没有明显的防守问题!")
# 主程序入口
def main():
    # 创建系统
    system = DefenseAnalysisSystem()
    # 1. 建立球队
    system.setup_team()
    # 2. 运行模拟
    report, synergy = system.run_simulation(num_plays=25)
    # 3. 生成改进建议
    system.generate_improvement_suggestions()
    # 4. 可视化分析
    system.visualize_results()
    # 5. 导出报告
    system.export_report()
    print("\n🎉 分析完成!")
if __name__ == "__main__":
    main()

运行结果示例

🏀 创建篮球防守分析系统
==================================================
球队 北京猛虎 创建成功
首发球员:
  #23 张飞 - 控球后卫
  #33 王磊 - 得分后卫
  #9 李强 - 小前锋
  #15 钱峰 - 大前锋
  #55 孙浩 - 中锋
🔄 开始防守轮转模拟 (25个回合)...
==================================================
✅ 模拟完成
总防守回合数: 25
平均默契度: 78.34
最佳默契度: 92.15
最差默契度: 55.67
团队综合默契度评分: 74.66
防守策略分布:
  - show: 6次
  - switch: 8次
  - hedge: 5次
  - drop: 6次
💡 改进建议:
--------------------------------------------------
  1. 需要加强团队沟通,增加挡拆防守演练次数
  2. 钱峰需要提升移动速度以适应快速轮转
📊 生成分析图表...
📝 报告已保存至: defense_report.json

技术特点总结

这个综合案例涵盖了多项Python技术:

  • 面向对象编程:使用类、继承、封装
  • 数据处理:NumPy数值计算
  • 数据可视化:Matplotlib绘制图表
  • 设计模式:策略模式处理不同防守类型
  • 类型提示:使用typing模块
  • 异常处理:完善的错误处理
  • 模块化设计:高内聚低耦合

这个系统可以用于篮球战术分析、训练效果评估等多种场景。

抱歉,评论功能暂时关闭!