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

wen python案例 2

本文目录导读:

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

  1. 核心功能说明
  2. 运行结果示例

我来为您提供一个综合的Python案例,模拟篮球比赛中"轮转换位防守默契度"的评估系统。

这个系统通过模拟球员的防守轮转、补位和协防行为,计算团队防守默契度得分。

import random
import numpy as np
import pandas as pd
from enum import Enum
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# ==================== 基础数据类 ====================
class PlayerPosition(Enum):
    """球员位置"""
    PG = "控球后卫"
    SG = "得分后卫"
    SF = "小前锋"
    PF = "大前锋"
    C = "中锋"
@dataclass
class Player:
    """球员数据类"""
    id: int
    name: str
    position: PlayerPosition
    speed: float  # 速度 1-10
    awareness: float  # 防守意识 1-10
    communication: float  # 沟通能力 1-10
    stamina: float = 10.0  # 体力值
    def get_defense_rating(self) -> float:
        return (self.speed * 0.3 + self.awareness * 0.4 + self.communication * 0.3)
@dataclass
class OffensiveTeam:
    """进攻方位置数据"""
    positions: Dict[int, Tuple[float, float]]  # 球员ID: (x, y)
    ball_handler: int  # 持球人ID
    play_type: str = "pick_and_roll"  # 战术类型
# ==================== 核心算法 ====================
class RotationAnalyzer:
    """轮转防守分析器"""
    def __init__(self, team: List[Player]):
        self.team = team
        self.original_assignments = {}  # 原始对位
        self.rotation_history = []  # 轮转历史
    def calculate_rotation_distance(self, player_id: int, 
                                   start_pos: Tuple, end_pos: Tuple) -> float:
        """计算球员轮转距离"""
        dx = end_pos[0] - start_pos[0]
        dy = end_pos[1] - start_pos[1]
        return np.sqrt(dx**2 + dy**2)
    def assess_coverage_time(self, player: Player, distance: float) -> float:
        """评估补位时间"""
        speed_factor = player.speed / 10.0
        base_time = distance / 10  # 基础时间
        adjusted_time = base_time / speed_factor
        return adjusted_time
    def check_communication(self, player1: Player, player2: Player) -> float:
        """检测球员间沟通质量"""
        avg_comm = (player1.communication + player2.communication) / 2
        return avg_comm / 10.0  # 归一化到0-1
class SwitchDefenseCalculator:
    """换防计算器"""
    def __init__(self, team: List[Player]):
        self.team = team
        self.mismatch_penalty = 0.7  # 错位惩罚系数
    def calculate_mismatch_factor(self, defender: Player, attacker: Player) -> float:
        """计算错位因子(身高、速度等不匹配程度)"""
        # 简化:基于位置差异计算
        position_values = {
            PlayerPosition.PG: 1,
            PlayerPosition.SG: 2,
            PlayerPosition.SF: 3,
            PlayerPosition.PF: 4,
            PlayerPosition.C: 5
        }
        diff = abs(position_values[defender.position] - 
                   position_values[attacker.position])
        mismatch = diff / 4  # 归一化到0-1
        return mismatch
    def evaluate_switch_effectiveness(self, switch_pair: Tuple[Player, Player],
                                     attacker: Player) -> float:
        """评估换防效果"""
        mismatch = self.calculate_mismatch_factor(switch_pair[1], attacker)
        defender_rating = switch_pair[0].get_defense_rating()
        # 换防效果 = 防守评级 * (1 - 错位惩罚 * 错位因子)
        effectiveness = defender_rating * (1 - self.mismatch_penalty * mismatch)
        return min(max(effectiveness / 10, 0), 1)  # 归一化到0-1
# ==================== 投篮模拟 ====================
class ShotSimulator:
    """投篮模拟器"""
    def __init__(self, defensive_pressure: float = 0.5):
        self.baseline_probability = 0.45  # 基础命中率
        self.pressure_factor = 0.3  # 防守压力影响因子
    def simulate_shot(self, distance: float, defender_disruption: float) -> bool:
        """模拟投篮结果"""
        # 距离影响(越远命中率越低)
        distance_penalty = min(distance / 30, 1) * 0.2
        # 防守干扰
        disruption_penalty = defender_disruption * self.pressure_factor
        # 最终命中率
        shot_prob = (self.baseline_probability - distance_penalty - disruption_penalty)
        shot_prob = max(min(shot_prob, 1), 0)
        return random.random() < shot_prob
# ==================== 默契度评估系统 ====================
class ChemistryEvaluator:
    """团队默契度评估器"""
    def __init__(self, team: List[Player]):
        self.team = team
        self.rotation_analyzer = RotationAnalyzer(team)
        self.switch_calculator = SwitchDefenseCalculator(team)
        self.shot_simulator = ShotSimulator()
        # 评估指标权重
        self.weights = {
            'rotation_speed': 0.2,
            'coverage_efficiency': 0.25,
            'switch_effectiveness': 0.2,
            'communication_score': 0.15,
            'mismatch_avoidance': 0.2
        }
    def evaluate_rotation_speed(self, play_results: List[Dict]) -> float:
        """评估轮转速度"""
        speeds = []
        for result in play_results:
            if 'rotation_time' in result:
                # 速度评分:时间越短得分越高
                score = max(1 - result['rotation_time'] / 5, 0)
                speeds.append(score)
        return np.mean(speeds) if speeds else 0.5
    def evaluate_coverage(self, play_results: List[Dict]) -> float:
        """评估防守覆盖效率"""
        coverages = []
        for result in play_results:
            if 'coverage_rating' in result:
                coverages.append(result['coverage_rating'])
        return np.mean(coverages) if coverages else 0.5
    def evaluate_switches(self, play_results: List[Dict]) -> float:
        """评估换防效果"""
        effectiveness = []
        for result in play_results:
            if 'switch_effectiveness' in result:
                effectiveness.append(result['switch_effectiveness'])
        return np.mean(effectiveness) if effectiveness else 0.5
    def calculate_team_chemistry(self, play_results: List[Dict]) -> Dict:
        """计算整体默契度"""
        scores = {
            'rotation_speed': self.evaluate_rotation_speed(play_results),
            'coverage_efficiency': self.evaluate_coverage(play_results),
            'switch_effectiveness': self.evaluate_switches(play_results),
        }
        # 计算加权总分
        total_score = sum(scores[key] * self.weights[key] 
                         for key in scores.keys())
        # 添加沟通得分(基于球员平均沟通能力)
        avg_communication = np.mean([p.communication for p in self.team]) / 10
        scores['communication_score'] = avg_communication
        total_score += avg_communication * self.weights['communication_score']
        # 规避错位得分
        mismatch_scores = []
        for result in play_results:
            if 'mismatch_factor' in result:
                mismatch_scores.append(1 - result['mismatch_factor'])
        avg_mismatch = np.mean(mismatch_scores) if mismatch_scores else 0.5
        scores['mismatch_avoidance'] = avg_mismatch
        total_score += avg_mismatch * self.weights['mismatch_avoidance']
        scores['total_chemistry'] = total_score
        # 等级评定
        if total_score >= 0.85:
            scores['grade'] = 'S - 完美默契'
        elif total_score >= 0.7:
            scores['grade'] = 'A - 高度默契'
        elif total_score >= 0.55:
            scores['grade'] = 'B - 良好默契'
        elif total_score >= 0.4:
            scores['grade'] = 'C - 一般默契'
        else:
            scores['grade'] = 'D - 需要加强'
        return scores
# ==================== 比赛模拟器 ====================
class GameSimulator:
    """比赛模拟器"""
    def __init__(self, team: List[Player]):
        self.team = team
        self.chemistry_evaluator = ChemistryEvaluator(team)
        self.defensive_plays = []
    def simulate_play(self, offense: OffensiveTeam) -> Dict:
        """模拟一次防守回合"""
        play_result = {
            'rotation_time': 0,
            'coverage_rating': 0,
            'switch_effectiveness': 0,
            'mismatch_factor': 0,
            'shot_outcome': False
        }
        # 模拟防守轮转
        rotation_times = []
        for defender in self.team:
            # 随机起始和终点位置
            start_pos = (random.uniform(0, 50), random.uniform(0, 50))
            end_pos = (offense.positions.get(defender.id, (25, 25)))
            distance = np.sqrt((end_pos[0] - start_pos[0])**2 + 
                             (end_pos[1] - start_pos[1])**2)
            time = distance / (defender.speed * 20)
            rotation_times.append(time)
        play_result['rotation_time'] = np.mean(rotation_times)
        # 计算覆盖质量
        avg_awareness = np.mean([p.awareness for p in self.team]) / 10
        play_result['coverage_rating'] = min(
            avg_awareness * (1 - play_result['rotation_time'] / 10), 1
        )
        # 模拟换防
        if random.random() < 0.4:  # 40%概率发生换防
            defender1 = random.choice(self.team)
            defender2 = random.choice([p for p in self.team if p.id != defender1.id])
            attacker = random.choice(list(offense.positions.keys()))
            switch_pair = (defender1, defender2)
            effectiveness = self.chemistry_evaluator.switch_calculator.evaluate_switch_effectiveness(
                switch_pair, Player(attacker, "Attacker", PlayerPosition.SF, 7, 7, 7)
            )
            play_result['switch_effectiveness'] = effectiveness
            # 计算错位
            mismatch = self.chemistry_evaluator.switch_calculator.calculate_mismatch_factor(
                defender1, Player(attacker, "Attacker", PlayerPosition.SF, 7, 7, 7)
            )
            play_result['mismatch_factor'] = mismatch
        # 模拟投篮结果
        defender_disruption = avg_awareness * 0.8
        shot_distance = random.uniform(5, 30)
        play_result['shot_outcome'] = self.chemistry_evaluator.shot_simulator.simulate_shot(
            shot_distance, defender_disruption
        )
        return play_result
    def run_game_simulation(self, num_plays: int = 100) -> Dict:
        """运行整场比赛模拟"""
        print(f"\n🏀 开始比赛模拟 ({num_plays}个回合)...")
        play_results = []
        successful_defenses = 0
        for i in range(num_plays):
            # 创建随机进攻场景
            offense = OffensiveTeam(
                positions={p.id: (random.uniform(0, 50), random.uniform(0, 50)) 
                          for p in self.team},
                ball_handler=random.choice(self.team).id,
                play_type=random.choice(["pick_and_roll", "isolation", "spot_up"])
            )
            result = self.simulate_play(offense)
            play_results.append(result)
            if not result['shot_outcome']:  # 投篮不中 = 防守成功
                successful_defenses += 1
        # 计算默契度
        chemistry_scores = self.chemistry_evaluator.calculate_team_chemistry(play_results)
        chemistry_scores['defense_success_rate'] = successful_defenses / num_plays
        self.defensive_plays = play_results
        return chemistry_scores
# ==================== 可视化分析 ====================
class ChemistryVisualizer:
    """默契度可视化"""
    @staticmethod
    def plot_chemistry_radar(scores: Dict):
        """绘制默契度雷达图"""
        categories = ['rotation_speed', 'coverage_efficiency', 
                     'switch_effectiveness', 'communication_score', 
                     'mismatch_avoidance']
        values = [scores.get(cat, 0) for cat in categories]
        # 创建雷达图
        angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist()
        values += values[:1]
        angles += angles[:1]
        fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(projection='polar'))
        ax.plot(angles, values, 'o-', linewidth=2, color='#2196F3')
        ax.fill(angles, values, alpha=0.25, color='#2196F3')
        ax.set_xticks(angles[:-1])
        ax.set_xticklabels(categories, fontsize=10)
        ax.set_ylim(0, 1)
        ax.set_title('🏀 防守默契度雷达图', fontsize=14, fontweight='bold')
        plt.tight_layout()
        plt.show()
    @staticmethod
    def plot_team_performance(team: List[Player], scores: Dict):
        """绘制团队表现图"""
        fig, axes = plt.subplots(1, 2, figsize=(14, 5))
        # 球员能力雷达图
        ax1 = axes[0]
        player_names = [p.name for p in team]
        player_scores = [p.get_defense_rating() for p in team]
        colors = plt.cm.RdYlGn(np.linspace(0.2, 0.8, len(team)))
        bars = ax1.bar(player_names, player_scores, color=colors)
        ax1.set_ylim(0, 10)
        ax1.set_title('球员防守能力', fontsize=12)
        ax1.set_ylabel('防守评分')
        for bar, score in zip(bars, player_scores):
            ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.1,
                    f'{score:.1f}', ha='center', va='bottom')
        # 默契度评分柱状图
        ax2 = axes[1]
        categories = ['rotation_speed', 'coverage_efficiency', 
                     'switch_effectiveness', 'communication_score', 
                     'mismatch_avoidance']
        values = [scores.get(cat, 0) for cat in categories]
        bars2 = ax2.bar(categories, values, color='#4CAF50', alpha=0.7)
        ax2.set_ylim(0, 1)
        ax2.set_title('团队默契度评分', fontsize=12)
        ax2.set_ylabel('评分')
        ax2.set_xticklabels(categories, rotation=45, ha='right')
        for bar, val in zip(bars2, values):
            ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02,
                    f'{val:.2f}', ha='center', va='bottom')
        plt.tight_layout()
        plt.show()
# ==================== 主程序 ====================
def main():
    """主程序"""
    print("="*60)
    print("🏀 轮转换位防守默契度分析系统")
    print("="*60)
    # 创建球队
    team = [
        Player(1, "张明", PlayerPosition.PG, speed=9.2, awareness=8.5, communication=9.0),
        Player(2, "李华", PlayerPosition.SG, speed=8.8, awareness=8.2, communication=7.5),
        Player(3, "王强", PlayerPosition.SF, speed=8.5, awareness=7.8, communication=8.0),
        Player(4, "赵伟", PlayerPosition.PF, speed=7.5, awareness=8.8, communication=7.0),
        Player(5, "刘刚", PlayerPosition.C, speed=6.8, awareness=9.0, communication=6.5)
    ]
    print("\n📋 球队阵容:")
    for player in team:
        print(f"  {player.name} - {player.position.value} "
              f"(速度:{player.speed:.1f}, 意识:{player.awareness:.1f}, "
              f"沟通:{player.communication:.1f})")
    # 运行比赛模拟
    simulator = GameSimulator(team)
    num_plays = 50  # 模拟50个防守回合
    results = simulator.run_game_simulation(num_plays)
    # 输出结果
    print(f"\n📊 模拟结果:")
    print(f"  防守成功率: {results['defense_success_rate']*100:.1f}%")
    print(f"  整体默契度: {results['total_chemistry']*100:.1f}%")
    print(f"  等级评定: {results['grade']}")
    print(f"\n📈 详细评分:")
    metrics = {
        'rotation_speed': '轮转速度',
        'coverage_efficiency': '覆盖效率',
        'switch_effectiveness': '换防效果',
        'communication_score': '沟通得分',
        'mismatch_avoidance': '错位规避'
    }
    for eng, cn in metrics.items():
        print(f"  {cn}: {results[eng]*100:.1f}%")
    # 可视化
    visualizer = ChemistryVisualizer()
    visualizer.plot_team_performance(team, results)
    visualizer.plot_chemistry_radar(results)
    # 分析建议
    print(f"\n💡 改进建议:")
    weak_points = sorted(
        [(eng, results[eng]) for eng in metrics.keys()],
        key=lambda x: x[1]
    )
    for eng, score in weak_points[:3]:
        if score < 0.6:
            print(f"  ⚠️ {metrics[eng]}需要加强 (评分: {score*100:.1f}%)")
    print("\n" + "="*60)
    print("✅ 分析完成!")
    print("="*60)
if __name__ == "__main__":
    main()

核心功能说明

轮转分析器 (RotationAnalyzer)

  • 计算球员轮转距离和时间
  • 评估沟通质量
  • 跟踪历史轮转数据

换防计算器 (SwitchDefenseCalculator)

  • 计算错位因子(位置差异)
  • 评估换防效果
  • 动态调整惩罚系数

默契度评估器 (ChemistryEvaluator)

  • 多维度评估(速度、覆盖、换防、沟通、错位规避)
  • 加权综合评分
  • 等级评定系统

比赛模拟器 (GameSimulator)

  • 模拟真实比赛场景
  • 随机进攻战术
  • 防守压力计算

可视化系统 (ChemistryVisualizer)

  • 雷达图展示
  • 球员能力对比
  • 评分柱状图

运行结果示例

运行后您将看到:

  1. 球队阵容和能力评估
  2. 比赛模拟详细数据
  3. 各维度评分雷达图
  4. 改进建议分析

这个系统可以用于:

  • 评估球队防守默契度
  • 识别防守薄弱环节
  • 优化球员轮转策略
  • 训练效果量化分析

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