综合python案例,空中对抗优势在哪队?

wen python案例 4

本文目录导读:

综合python案例,空中对抗优势在哪队?

  1. 空中对抗优势分析系统
  2. 运行效果说明

我来设计一个综合Python案例,模拟空中对抗(空战)情景,分析哪支队伍更具优势。

空中对抗优势分析系统

import random
import math
from dataclasses import dataclass
from typing import List, Dict, Tuple
import numpy as np
from enum import Enum
class FighterType(Enum):
    """战斗机类型"""
    STEALTH = "隐身战机"      # 高隐身
    AIR_SUPERIORITY = "空优战机"  # 高机动
    MULTI_ROLE = "多用途战机"   # 均衡型
    INTERCEPTOR = "截击机"    # 高速
class WeatherCondition(Enum):
    """天气条件"""
    CLEAR = "晴朗"
    CLOUDY = "多云"
    STORM = "雷暴"
    NIGHT = "夜间"
@dataclass
class Fighter:
    """战斗机类"""
    name: str
    fighter_type: FighterType
    speed: float          # 最大速度 (马赫)
    maneuverability: float # 机动性 (1-10)
    stealth: float        # 隐身性能 (1-10)
    avionics: float       # 航电系统 (1-10)
    weapons: float        # 武器系统 (1-10)
    pilot_experience: float # 飞行员经验 (1-10)
    def get_combat_power(self) -> float:
        """计算综合战斗力"""
        base_power = (
            self.speed * 0.2 +
            self.maneuverability * 0.25 +
            self.stealth * 0.2 +
            self.avionics * 0.15 +
            self.weapons * 0.15 +
            self.pilot_experience * 0.05
        )
        # 类型加成
        type_bonus = {
            FighterType.STEALTH: 1.2,
            FighterType.AIR_SUPERIORITY: 1.1,
            FighterType.MULTI_ROLE: 1.0,
            FighterType.INTERCEPTOR: 1.05
        }
        return base_power * type_bonus[self.fighter_type]
class AirForce:
    """空军编队类"""
    def __init__(self, name: str, fighters: List[Fighter]):
        self.name = name
        self.fighters = fighters
        self.formation_bonus = 0.0  # 编队加成
    def get_total_power(self) -> float:
        """计算编队总战斗力"""
        total = sum(fighter.get_combat_power() for fighter in self.fighters)
        # 编队加成 (多机协同)
        if len(self.fighters) > 1:
            self.formation_bonus = 1 + (len(self.fighters) - 1) * 0.1
        else:
            self.formation_bonus = 1.0
        return total * self.formation_bonus
    def get_fighter_types_count(self) -> Dict[str, int]:
        """统计各类型战机数量"""
        count = {}
        for fighter in self.fighters:
            type_name = fighter.fighter_type.value
            count[type_name] = count.get(type_name, 0) + 1
        return count
class CombatSimulator:
    """空战模拟器"""
    def __init__(self, weather: WeatherCondition = WeatherCondition.CLEAR):
        self.weather = weather
        self.weather_factor = self._get_weather_factor()
    def _get_weather_factor(self) -> float:
        """根据天气返回影响因子"""
        factors = {
            WeatherCondition.CLEAR: 1.0,
            WeatherCondition.CLOUDY: 0.9,
            WeatherCondition.STORM: 0.7,
            WeatherCondition.NIGHT: 0.8
        }
        return factors[self.weather]
    def simulate_battle(self, force1: AirForce, force2: AirForce) -> Dict:
        """模拟空战"""
        power1 = force1.get_total_power()
        power2 = force2.get_total_power()
        # 应用天气因素
        power1 *= self.weather_factor
        power2 *= self.weather_factor
        # 计算胜负概率 (添加随机因素)
        random_factor = random.uniform(0.9, 1.1)
        advantage_ratio = (power1 * random_factor) / power2
        # 根据比值判断胜率
        win_probability_1 = 1 / (1 + math.exp(-(advantage_ratio - 1) * 3))
        # 模拟战斗过程
        survival_rate_1 = random.uniform(0.7, 1.0) if win_probability_1 > 0.5 else random.uniform(0.3, 0.7)
        survival_rate_2 = random.uniform(0.7, 1.0) if win_probability_1 < 0.5 else random.uniform(0.3, 0.7)
        return {
            "force1_power": power1,
            "force2_power": power2,
            "win_probability_1": win_probability_1,
            "survival_rate_1": survival_rate_1,
            "survival_rate_2": survival_rate_2,
            "advantage_ratio": advantage_ratio
        }
class OptimalStrategyAnalyzer:
    """最优策略分析器"""
    @staticmethod
    def analyze_force_composition(fighters: List[Fighter]) -> str:
        """分析编队构成建议"""
        types_count = {}
        for fighter in fighters:
            type_name = fighter.fighter_type.value
            types_count[type_name] = types_count.get(type_name, 0) + 1
        # 计算各类型占比
        total = len(fighters)
        recommendations = []
        if types_count.get("隐身战机", 0) / total < 0.2:
            recommendations.append("建议增加隐身战机比例,提高突防能力")
        if types_count.get("空优战机", 0) / total < 0.3:
            recommendations.append("建议增加空优战机,提升制空权争夺能力")
        if types_count.get("截击机", 0) / total > 0.5:
            recommendations.append("截击机比例过高,建议增加多用途战机以应对多样化任务")
        if len(fighters) < 4:
            recommendations.append("建议增加战机数量,形成规模优势")
        return "\n".join(recommendations) if recommendations else "编队构成合理,无需调整"
def create_sample_forces():
    """创建示例空军力量"""
    # 红队:以隐身战机和空优战机为主
    red_force = AirForce("红队", [
        Fighter("歼-20A", FighterType.STEALTH, 2.5, 9.0, 9.5, 8.5, 9.0, 8.0),
        Fighter("歼-20B", FighterType.STEALTH, 2.6, 9.2, 9.5, 9.0, 9.2, 8.5),
        Fighter("歼-16", FighterType.AIR_SUPERIORITY, 2.2, 8.5, 7.0, 8.5, 8.8, 7.5),
        Fighter("歼-16D", FighterType.AIR_SUPERIORITY, 2.3, 8.8, 7.5, 9.0, 9.0, 8.0),
    ])
    # 蓝队:以多用途战机和截击机为主
    blue_force = AirForce("蓝队", [
        Fighter("F-35A", FighterType.MULTI_ROLE, 1.8, 8.0, 8.0, 9.0, 8.5, 7.5),
        Fighter("F-35B", FighterType.MULTI_ROLE, 1.8, 8.2, 8.0, 8.8, 8.2, 7.0),
        Fighter("F-22", FighterType.STEALTH, 2.0, 9.5, 9.5, 9.0, 9.0, 8.5),
        Fighter("F-15EX", FighterType.INTERCEPTOR, 2.5, 8.0, 6.5, 8.5, 8.8, 8.0),
    ])
    return red_force, blue_force
def comprehensive_analysis():
    """综合分析"""
    print("="*60)
    print("空中对抗优势分析系统")
    print("="*60)
    # 创建对抗力量
    red_force, blue_force = create_sample_forces()
    print(f"\n【对抗双方】")
    print(f"红队: {red_force.name}")
    print(f"蓝队: {blue_force.name}")
    # 展示双方编队
    for force in [red_force, blue_force]:
        print(f"\n{force.name} 编队:")
        for fighter in force.fighters:
            print(f"  - {fighter.name} ({fighter.fighter_type.value}) 战斗力: {fighter.get_combat_power():.2f}")
        print(f"  编队总战斗力: {force.get_total_power():.2f}")
        print(f"  战机类型分布: {force.get_fighter_types_count()}")
    # 分析编队构成
    analyzer = OptimalStrategyAnalyzer()
    print(f"\n【编队优化建议】")
    print(f"红队: {analyzer.analyze_force_composition(red_force.fighters)}")
    print(f"蓝队: {analyzer.analyze_force_composition(blue_force.fighters)}")
    # 多种天气下模拟
    print(f"\n【战斗模拟 - 不同天气条件】")
    results = {}
    for weather in WeatherCondition:
        simulator = CombatSimulator(weather)
        result = simulator.simulate_battle(red_force, blue_force)
        results[weather] = result
        print(f"\n{weather.value}条件:")
        print(f"  红队战斗力: {result['force1_power']:.2f}")
        print(f"  蓝队战斗力: {result['force2_power']:.2f}")
        print(f"  红队胜率: {result['win_probability_1']*100:.1f}%")
        print(f"  红队生存率: {result['survival_rate_1']*100:.1f}%")
        print(f"  蓝队生存率: {result['survival_rate_2']*100:.1f}%")
    # 综合优势分析
    print("\n" + "="*60)
    print("【综合优势分析】")
    print("="*60)
    avg_win_prob = np.mean([r['win_probability_1'] for r in results.values()])
    avg_survival_1 = np.mean([r['survival_rate_1'] for r in results.values()])
    avg_survival_2 = np.mean([r['survival_rate_2'] for r in results.values()])
    print(f"红队平均胜率: {avg_win_prob*100:.1f}%")
    print(f"红队平均生存率: {avg_survival_1*100:.1f}%")
    print(f"蓝队平均生存率: {avg_survival_2*100:.1f}%")
    if avg_win_prob > 0.5:
        print(f"\n★★★ 红队在空中对抗中占据优势 ★★★")
        print(f"优势因素分析:")
        print(f"  - 隐身战机数量更多,突防能力强")
        print(f"  - 空优战机机动性好,夺控战场主动权重")
        print(f"  - 综合战斗力更强")
    else:
        print(f"\n★★★ 蓝队在空中对抗中占据优势 ★★★")
        print(f"优势因素分析:")
        print(f"  - 具备高端隐身战机")
        print(f"  - 编队构成互补")
        print(f"  - 具备强大的截击力量")
    # 数据分析可视化(简单的ASCII图)
    print("\n" + "="*60)
    print("【战斗力对比条形图】")
    print("="*60)
    max_power = max(results[WeatherCondition.CLEAR]['force1_power'], 
                   results[WeatherCondition.CLEAR]['force2_power'])
    for force_name, power in [
        ("红队", results[WeatherCondition.CLEAR]['force1_power']),
        ("蓝队", results[WeatherCondition.CLEAR]['force2_power'])
    ]:
        bar_length = int((power / max_power) * 30)
        print(f"{force_name}: {'█' * bar_length} {power:.2f}")
    return results
def advanced_sensitivity_analysis():
    """高级敏感性分析"""
    print("\n" + "="*60)
    print("【敏感性分析 - 单机变化影响】")
    print("="*60)
    red_force, blue_force = create_sample_forces()
    simulator = CombatSimulator(WeatherCondition.CLEAR)
    # 测试单类型战机的影响
    base_result = simulator.simulate_battle(red_force, blue_force)
    base_win_prob = base_result['win_probability_1']
    original_fighters = red_force.fighters.copy()
    # 模拟更换红队第一架战机
    test_fighters = [
        Fighter("替换机型A", FighterType.STEALTH, 2.8, 9.5, 9.8, 9.5, 9.5, 9.0),  # 加强版
        Fighter("替换机型B", FighterType.AIR_SUPERIORITY, 2.4, 8.8, 7.5, 8.8, 9.0, 8.0),  # 普通版
        Fighter("替换机型C", FighterType.MULTI_ROLE, 2.0, 8.5, 8.5, 8.5, 8.5, 8.0),  # 均衡版
    ]
    for test_fighter in test_fighters:
        test_force = AirForce("测试编队", [test_fighter] + red_force.fighters[1:])
        result = simulator.simulate_battle(test_force, blue_force)
        change = (result['win_probability_1'] - base_win_prob) * 100
        print(f"\n更换{test_fighter.name}后:")
        print(f"  胜率变化: {change:+.1f}%")
        print(f"  当前胜率: {result['win_probability_1']*100:.1f}%")
    print("\n" + "="*60)
    print("分析完成!")
    print("="*60)
if __name__ == "__main__":
    # 主程序入口
    try:
        # 基础综合分析
        results = comprehensive_analysis()
        # 高级敏感性分析
        advanced_sensitivity_analysis()
        print("\n程序执行完毕!")
    except Exception as e:
        print(f"程序执行出错: {str(e)}")
        raise

运行效果说明

这个综合案例包含了:

核心功能模块

  • 战斗机建模:不同类型战斗机(隐身、空优、多用途、截击)
  • 编队管理:多机型混编和编队加成
  • 战斗模拟:考虑天气、随机因素的综合模拟
  • 策略分析:编队优化和敏感性分析

分析维度

  • 综合战斗力对比
  • 不同天气条件下的表现
  • 编队构成合理性分析
  • 单机更换的影响评估

输出结果

  • 详细的战斗参数对比
  • 直观的条形图展示
  • 策略建议

通过这个案例,可以清晰判断哪方在空中对抗中更具优势,并分析具体原因,根据示例数据,红队(配备大量隐身战机和空优战机)通常会在对抗中占据优势。

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