"""
二战中国战场 - 战争兵棋推演
需要安装: pip install pygame
"""

import pygame
import random
import math
from enum import Enum
from typing import List, Tuple
import sys

# 初始化Pygame
pygame.init()

# 常量定义
SCREEN_WIDTH = 1400
SCREEN_HEIGHT = 900
FPS = 60
TILE_SIZE = 64

# 颜色定义
class Colors:
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    YELLOW = (255, 255, 0)
    GRAY = (128, 128, 128)
    DARK_GRAY = (64, 64, 64)
    BROWN = (139, 69, 19)
    DARK_GREEN = (0, 100, 0)
    LIGHT_GREEN = (144, 238, 144)
    GOLD = (255, 215, 0)
    ORANGE = (255, 165, 0)
    CYAN = (0, 255, 255)

# 单位类型
class UnitType(Enum):
    INFANTRY = "步兵"
    CAVALRY = "骑兵"
    ARTILLERY = "炮兵"
    TANK = "坦克"
    ENGINEER = "工兵"
    MEDIC = "医疗兵"
    COMMANDER = "指挥官"

# 阵营
class Faction(Enum):
    CHINA = "中国"
    JAPAN = "日本"

# 武器类
class Weapon:
    def __init__(self, name, weapon_type, attack, defense, range_val, price, description):
        self.name = name
        self.weapon_type = weapon_type
        self.attack = attack
        self.defense = defense
        self.range = range_val
        self.price = price
        self.description = description

# 武器库
class WeaponShop:
    @staticmethod
    def get_weapons():
        return [
            Weapon("中正式步枪", "步枪", 6, 1, 3, 50, "中国制式步枪"),
            Weapon("汉阳造步枪", "步枪", 5, 1, 3, 40, "老式步枪"),
            Weapon("捷克式轻机枪", "轻机枪", 8, 2, 4, 120, "主力轻机枪"),
            Weapon("马克沁重机枪", "重机枪", 10, 3, 4, 180, "水冷式重机枪"),
            Weapon("毛瑟手枪", "手枪", 4, 0, 1, 30, "盒子炮"),
            Weapon("60mm迫击炮", "迫击炮", 12, 1, 5, 200, "轻型迫击炮"),
            Weapon("75mm山炮", "野战炮", 15, 2, 6, 350, "山炮"),
            Weapon("105mm榴弹炮", "重型火炮", 20, 3, 8, 500, "重型榴弹炮"),
            Weapon("M3冲锋枪", "冲锋枪", 7, 1, 2, 180, "美援冲锋枪"),
            Weapon("巴祖卡火箭筒", "反坦克武器", 18, 2, 5, 300, "美援火箭筒"),
            Weapon("掷弹筒", "曲射武器", 9, 1, 4, 150, "曲射火力"),
            Weapon("反坦克步枪", "反坦克武器", 14, 1, 4, 250, "反装甲"),
        ]

# 游戏地图
class GameMap:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.tiles = []
        for y in range(height):
            row = []
            for x in range(width):
                row.append("平原")
            self.tiles.append(row)
        self.generate()
    
    def generate(self):
        for y in range(self.height):
            for x in range(self.width):
                r = random.random()
                if r < 0.10:
                    self.tiles[y][x] = "森林"
                elif r < 0.15:
                    self.tiles[y][x] = "山地"
                elif r < 0.18:
                    self.tiles[y][x] = "城市"
                elif r < 0.22:
                    self.tiles[y][x] = "河流"
                elif r < 0.28:
                    self.tiles[y][x] = "道路"

# 单位类
class Unit:
    def __init__(self, unit_type, faction, x, y):
        self.unit_type = unit_type
        self.faction = faction
        self.x = x
        self.y = y
        self.max_health = 100
        self.health = 100
        self.attack = 10
        self.defense = 5
        self.movement = 4
        self.range = 2
        self.level = 1
        self.experience = 0
        self.equipped_weapon = None
        self.moved = False
        self.attacked = False
        self.selected = False
        self.ai_highlight = False
        self.setup_stats()
    
    def setup_stats(self):
        stats = {
            UnitType.INFANTRY: (100, 8, 5, 4, 2),
            UnitType.CAVALRY: (90, 10, 3, 7, 1),
            UnitType.ARTILLERY: (80, 15, 2, 3, 6),
            UnitType.TANK: (150, 18, 8, 5, 3),
            UnitType.ENGINEER: (90, 6, 5, 4, 2),
            UnitType.MEDIC: (80, 3, 3, 4, 1),
            UnitType.COMMANDER: (120, 12, 7, 5, 3),
        }
        if self.unit_type in stats:
            h, a, d, m, r = stats[self.unit_type]
            self.max_health = h
            self.health = h
            self.attack = a
            self.defense = d
            self.movement = m
            self.range = r
    
    def attack_target(self, target):
        if self.attacked:
            return 0
        dist = abs(self.x - target.x) + abs(self.y - target.y)
        if dist > self.range:
            return 0
        
        base = self.attack
        if self.equipped_weapon:
            base += self.equipped_weapon.attack
        
        damage = base * (1 - target.defense * 0.04)
        damage *= random.uniform(0.8, 1.2)
        
        if random.random() < 0.1:
            damage *= 1.5
        
        damage = max(1, int(damage))
        target.health -= damage
        if target.health <= 0:
            target.health = 0
        
        self.attacked = True
        self.experience += 10
        if self.experience >= self.level * 100:
            self.level_up()
        
        return damage
    
    def level_up(self):
        self.level += 1
        self.experience = 0
        self.max_health += 20
        self.health = self.max_health
        self.attack += 2
        self.defense += 1
    
    def reset_turn(self):
        self.moved = False
        self.attacked = False
    
    def is_alive(self):
        return self.health > 0

# AI系统
class AISystem:
    def __init__(self, game):
        self.game = game
        self.last_moved_index = -1
    
    def execute_turn(self):
        print("AI开始执行回合")  # 调试输出
        
        # 获取日军和中国单位
        jp_units = []
        for u in self.game.units:
            if u.faction == Faction.JAPAN and u.is_alive():
                jp_units.append(u)
        
        cn_units = []
        for u in self.game.units:
            if u.faction == Faction.CHINA and u.is_alive():
                cn_units.append(u)
        
        print(f"日军单位数: {len(jp_units)}, 中国单位数: {len(cn_units)}")  # 调试
        
        if not cn_units or not jp_units:
            print("没有可行动的单位")  # 调试
            self.game.ai_turn_finished()
            return
        
        # 清除所有AI高亮
        for u in jp_units:
            u.ai_highlight = False
        
        # 选择本回合行动的单位
        selected = self.select_unit(jp_units, cn_units)
        print(f"选择的单位: {selected}")  # 调试
        
        if selected:
            selected.ai_highlight = True
            print(f"执行行动前 - 位置: ({selected.x}, {selected.y}), 移动力: {selected.movement}")  # 调试
            self.perform_action(selected, cn_units)
            print(f"执行行动后 - 位置: ({selected.x}, {selected.y})")  # 调试
        else:
            print("没有选择到单位")  # 调试
            self.game.ai_turn_finished()
    
    def select_unit(self, jp_units, cn_units):
        scores = []
        for i, unit in enumerate(jp_units):
            score = 0
            
            # 找到最近的敌人
            nearest = min(cn_units, key=lambda e: abs(e.x - unit.x) + abs(e.y - unit.y))
            dist = abs(nearest.x - unit.x) + abs(nearest.y - unit.y)
            
            print(f"单位{i}: {unit.unit_type.value} 位置({unit.x},{unit.y}) 最近敌人在({nearest.x},{nearest.y}) 距离{dist}")  # 调试
            
            # 距离评分
            if dist <= unit.range:
                score += 50  # 可以直接攻击
            elif dist <= unit.movement + unit.range:
                score += 30  # 移动后可攻击
            else:
                score += 10  # 需要移动
            
            # 优先攻击残血敌人
            if nearest.health < nearest.max_health * 0.3:
                score += 20
            
            # 单位状态
            score += unit.health / unit.max_health * 10
            
            # 单位类型加成
            if unit.unit_type == UnitType.TANK:
                score += 15
            elif unit.unit_type == UnitType.COMMANDER:
                score += 10
            elif unit.unit_type == UnitType.ARTILLERY:
                score += 8
            
            # 随机因素
            score += random.uniform(-3, 3)
            
            scores.append((score, unit, i))
            print(f"  得分: {score:.1f}")  # 调试
        
        # 按分数排序
        scores.sort(key=lambda x: x[0], reverse=True)
        
        # 选择分数最高的单位（避免连续选择同一个）
        for score, unit, i in scores:
            if i != self.last_moved_index or len(jp_units) == 1:
                self.last_moved_index = i
                print(f"选择单位{i}: {unit.unit_type.value} 得分{score:.1f}")  # 调试
                return unit
        
        # 如果都被选过，选第一个
        if scores:
            self.last_moved_index = scores[0][2]
            print(f"所有单位都被选过，选择第一个: {scores[0][1].unit_type.value}")  # 调试
            return scores[0][1]
        
        return None
    
    def perform_action(self, unit, cn_units):
        # 找到最近的敌人
        nearest = min(cn_units, key=lambda e: abs(e.x - unit.x) + abs(e.y - unit.y))
        dist = abs(nearest.x - unit.x) + abs(nearest.y - unit.y)
        
        print(f"行动决策 - 距离: {dist}, 攻击范围: {unit.range}, 移动力: {unit.movement}")  # 调试
        
        if dist <= unit.range:
            # 情况1: 可以直接攻击
            print("策略: 直接攻击")  # 调试
            dmg = unit.attack_target(nearest)
            msg = f"[日军] {unit.unit_type.value}攻击{nearest.unit_type.value}，造成{dmg}伤害"
            self.game.combat_log.append(msg)
            self.game.message = msg
            
            if not nearest.is_alive():
                self.game.combat_log.append(f"[日军] 消灭中国{nearest.unit_type.value}！")
                self.game.units.remove(nearest)
                self.game.message += " 消灭！"
            
            # 重要：攻击完成后也要结束回合
            self.game.ai_turn_finished()
            
        elif dist <= unit.movement + unit.range:
            # 情况2: 移动后可以攻击
            print("策略: 移动后攻击")  # 调试
            dx = nearest.x - unit.x
            dy = nearest.y - unit.y
            
            # 计算移动方向
            move_x = unit.x
            move_y = unit.y
            
            if dx != 0:
                move_x = unit.x + (1 if dx > 0 else -1)
            if dy != 0:
                move_y = unit.y + (1 if dy > 0 else -1)
            
            print(f"尝试移动到: ({move_x}, {move_y})")  # 调试
            
            # 检查移动是否合法
            if 0 <= move_x < self.game.map.width and 0 <= move_y < self.game.map.height:
                # 检查是否被占据
                occupied = False
                for u in self.game.units:
                    if u.x == move_x and u.y == move_y and u != unit and u.is_alive():
                        occupied = True
                        print(f"位置被{u.unit_type.value}占据")  # 调试
                        break
                
                if not occupied:
                    # 执行移动
                    old_x, old_y = unit.x, unit.y
                    unit.x = move_x
                    unit.y = move_y
                    unit.moved = True
                    
                    direction = ""
                    if move_x > old_x: direction = "→"
                    elif move_x < old_x: direction = "←"
                    if move_y > old_y: direction += "↓"
                    elif move_y < old_y: direction += "↑"
                    
                    self.game.message = f"[日军] {unit.unit_type.value}移动{direction}至({move_x},{move_y})"
                    print(f"移动成功: {direction}")  # 调试
                    
                    # 检查移动后是否可以攻击
                    new_dist = abs(nearest.x - move_x) + abs(nearest.y - move_y)
                    if new_dist <= unit.range and not unit.attacked:
                        print("移动后攻击")  # 调试
                        dmg = unit.attack_target(nearest)
                        self.game.combat_log.append(f"[日军] {unit.unit_type.value}移动后攻击，{dmg}伤害")
                        self.game.message += f"，攻击造成{dmg}伤害"
                        
                        if not nearest.is_alive():
                            self.game.combat_log.append(f"[日军] 消灭中国{nearest.unit_type.value}！")
                            self.game.units.remove(nearest)
                            self.game.message += " 消灭！"
                else:
                    # 位置被占据，尝试其他方向
                    print("位置被占据，尝试原地攻击")  # 调试
                    self.game.message = f"[日军] {unit.unit_type.value}无法移动"
                    
                    # 尝试攻击范围内的其他目标
                    targets = []
                    for e in cn_units:
                        if abs(e.x - unit.x) + abs(e.y - unit.y) <= unit.range:
                            targets.append(e)
                    
                    if targets and not unit.attacked:
                        target = min(targets, key=lambda e: e.health)
                        dmg = unit.attack_target(target)
                        self.game.combat_log.append(f"[日军] {unit.unit_type.value}攻击{target.unit_type.value}，{dmg}伤害")
                        self.game.message += f"，攻击造成{dmg}伤害"
                        
                        if not target.is_alive():
                            self.game.combat_log.append(f"[日军] 消灭中国{target.unit_type.value}！")
                            self.game.units.remove(target)
                            self.game.message += " 消灭！"
            else:
                print("移动超出地图范围")  # 调试
                self.game.message = f"[日军] {unit.unit_type.value}无法移动"
            
            # 重要：移动完成后结束回合
            self.game.ai_turn_finished()
            
        else:
            # 情况3: 距离太远，只能移动
            print("策略: 向敌人移动")  # 调试
            dx = nearest.x - unit.x
            dy = nearest.y - unit.y
            
            # 尝试多个移动方向
            possible_moves = []
            
            for step_x in [-1, 0, 1]:
                for step_y in [-1, 0, 1]:
                    if step_x == 0 and step_y == 0:
                        continue
                    if abs(step_x) + abs(step_y) > 1:  # 只能走直线
                        continue
                    
                    new_x = unit.x + step_x
                    new_y = unit.y + step_y
                    
                    if 0 <= new_x < self.game.map.width and 0 <= new_y < self.game.map.height:
                        # 检查是否被占据
                        occupied = False
                        for u in self.game.units:
                            if u.x == new_x and u.y == new_y and u != unit and u.is_alive():
                                occupied = True
                                break
                        
                        if not occupied:
                            # 计算这个位置的价值
                            new_dist = abs(nearest.x - new_x) + abs(nearest.y - new_y)
                            score = -new_dist  # 距离越近越好
                            
                            # 优先选择主要方向
                            if (dx > 0 and step_x > 0) or (dx < 0 and step_x < 0):
                                score += 5
                            if (dy > 0 and step_y > 0) or (dy < 0 and step_y < 0):
                                score += 5
                            
                            possible_moves.append((score, new_x, new_y))
            
            print(f"可能的移动: {len(possible_moves)}个")  # 调试
            
            if possible_moves:
                # 选择最佳移动
                possible_moves.sort(key=lambda m: m[0], reverse=True)
                best = possible_moves[0]
                
                old_x, old_y = unit.x, unit.y
                unit.x = best[1]
                unit.y = best[2]
                unit.moved = True
                
                direction = ""
                if best[1] > old_x: direction = "→"
                elif best[1] < old_x: direction = "←"
                if best[2] > old_y: direction += "↓"
                elif best[2] < old_y: direction += "↑"
                
                self.game.message = f"[日军] {unit.unit_type.value}移动{direction}至({best[1]},{best[2]})"
                print(f"移动成功: {direction} 到 ({best[1]}, {best[2]})")  # 调试
            else:
                self.game.message = f"[日军] {unit.unit_type.value}原地待命"
                print("无法移动")  # 调试
            
            # 重要：移动完成后结束回合
            self.game.ai_turn_finished()

# 主游戏类
class WarGame:
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("二战中国战场 - 兵棋推演")
        self.clock = pygame.time.Clock()
        self.running = True
        
        # 字体
        try:
            self.font = pygame.font.SysFont("simhei", 24)
            self.small_font = pygame.font.SysFont("simhei", 18)
            self.title_font = pygame.font.SysFont("simhei", 30)
        except:
            self.font = pygame.font.Font(None, 24)
            self.small_font = pygame.font.Font(None, 18)
            self.title_font = pygame.font.Font(None, 30)
        
        # 游戏状态
        self.current_turn = 1
        self.selected_unit = None
        self.message = ""
        self.combat_log = []
        self.is_ai_turn = False
        self.gold = 1000
        self.income = 100
        
        # 地图和单位
        self.map = GameMap(18, 10)
        self.units = []
        self.weapons = WeaponShop.get_weapons()
        self.ai = AISystem(self)
        
        # 面板
        self.panel_width = 320
        self.map_width = SCREEN_WIDTH - self.panel_width
        
        self.init_game()
    
    def init_game(self):
        # 中国军队
        cn = [
            (UnitType.COMMANDER, 2, 5),
            (UnitType.INFANTRY, 3, 4),
            (UnitType.INFANTRY, 4, 5),
            (UnitType.INFANTRY, 3, 6),
            (UnitType.CAVALRY, 5, 4),
            (UnitType.ARTILLERY, 1, 5),
            (UnitType.MEDIC, 4, 6),
            (UnitType.ENGINEER, 5, 6),
        ]
        for t, x, y in cn:
            self.units.append(Unit(t, Faction.CHINA, x, y))
        
        # 日军
        jp = [
            (UnitType.COMMANDER, 15, 3),
            (UnitType.INFANTRY, 16, 2),
            (UnitType.INFANTRY, 14, 4),
            (UnitType.INFANTRY, 16, 4),
            (UnitType.ARTILLERY, 17, 3),
            (UnitType.TANK, 15, 5),
            (UnitType.ENGINEER, 14, 2),
            (UnitType.INFANTRY, 13, 3),
        ]
        for t, x, y in jp:
            self.units.append(Unit(t, Faction.JAPAN, x, y))
        
        self.message = "游戏开始！第1回合 - 中国军队行动 (左键选择 右键移动/攻击 空格结束)"
    
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if not self.is_ai_turn:
                    x, y = event.pos
                    if x < self.map_width:
                        tx = x // TILE_SIZE
                        ty = y // TILE_SIZE
                        if event.button == 1:
                            self.select_unit(tx, ty)
                        elif event.button == 3:
                            self.move_or_attack(tx, ty)
                    else:
                        self.handle_panel_click(x, y)
            
            elif event.type == pygame.KEYDOWN:
                if not self.is_ai_turn:
                    if event.key == pygame.K_SPACE:
                        self.end_player_turn()
                    elif event.key == pygame.K_r and self.selected_unit:
                        self.selected_unit.reset_turn()
                        self.message = "单位已重置"
                    elif event.key == pygame.K_ESCAPE:
                        self.selected_unit = None
                        for u in self.units:
                            u.selected = False
                        self.message = "已取消选择"
                    elif event.key == pygame.K_TAB:
                        self.cycle_selection()
    
    def cycle_selection(self):
        cn_units = [u for u in self.units if u.faction == Faction.CHINA and u.is_alive()]
        if not cn_units:
            return
        
        for u in self.units:
            u.selected = False
        
        if self.selected_unit and self.selected_unit in cn_units:
            idx = cn_units.index(self.selected_unit)
            nxt = (idx + 1) % len(cn_units)
        else:
            nxt = 0
        
        self.selected_unit = cn_units[nxt]
        self.selected_unit.selected = True
        self.message = f"选择{self.selected_unit.unit_type.value}"
    
    def select_unit(self, x, y):
        for u in self.units:
            u.selected = False
        
        for u in self.units:
            if u.x == x and u.y == y and u.faction == Faction.CHINA and u.is_alive():
                self.selected_unit = u
                u.selected = True
                w = f"，武器：{u.equipped_weapon.name}" if u.equipped_weapon else ""
                self.message = f"选择{u.unit_type.value} Lv.{u.level}{w}"
                return
        
        for u in self.units:
            if u.x == x and u.y == y and u.faction == Faction.JAPAN and u.is_alive():
                self.message = f"日军{u.unit_type.value} 生命{u.health}/{u.max_health}"
                self.selected_unit = None
                return
        
        self.selected_unit = None
    
    def move_or_attack(self, x, y):
        if not self.selected_unit or self.selected_unit.moved:
            return
        
        # 检查是否有敌人
        for u in self.units:
            if u.x == x and u.y == y and u.faction != self.selected_unit.faction:
                self.attack(self.selected_unit, u)
                return
        
        # 检查是否有友军
        for u in self.units:
            if u.x == x and u.y == y and u != self.selected_unit:
                self.message = "位置已被占据"
                return
        
        # 移动
        dist = abs(x - self.selected_unit.x) + abs(y - self.selected_unit.y)
        if dist <= self.selected_unit.movement:
            self.selected_unit.x = x
            self.selected_unit.y = y
            self.selected_unit.moved = True
            self.message = f"移动到({x},{y})"
        else:
            self.message = f"距离不足({dist}/{self.selected_unit.movement})"
    
    def attack(self, attacker, target):
        if attacker.attacked:
            self.message = "本回合已攻击"
            return
        
        dist = abs(attacker.x - target.x) + abs(attacker.y - target.y)
        if dist > attacker.range:
            self.message = f"目标超出射程({dist}/{attacker.range})"
            return
        
        dmg = attacker.attack_target(target)
        self.combat_log.append(f"[中国] {attacker.unit_type.value}攻击{target.unit_type.value}，{dmg}伤害")
        self.message = f"攻击造成{dmg}伤害"
        
        if not target.is_alive():
            self.combat_log.append(f"[中国] 消灭日军{target.unit_type.value}！")
            self.units.remove(target)
            self.gold += 50
            self.message += " 消灭敌军！+50金"
    
    def handle_panel_click(self, x, y):
        # 结束回合按钮
        if 820 < y < 860:
            self.end_player_turn()
            return
        
        # 武器商店
        if 350 < y < 650:
            idx = (y - 350) // 25
            if 0 <= idx < len(self.weapons):
                self.buy_weapon(idx)
    
    def buy_weapon(self, idx):
        if not self.selected_unit:
            self.message = "请先选择单位"
            return
        
        w = self.weapons[idx]
        if self.gold >= w.price:
            self.gold -= w.price
            self.selected_unit.equipped_weapon = w
            self.message = f"购买{w.name}成功"
        else:
            self.message = f"金币不足({w.price})"
    
    def end_player_turn(self):
        print("玩家回合结束，开始AI回合")  # 调试
        self.gold += self.income
        self.selected_unit = None
        for u in self.units:
            u.selected = False
        
        self.is_ai_turn = True
        self.message = "日军行动中..."
        
        # 立即执行AI行动
        self.ai.execute_turn()
    
    def ai_turn_finished(self):
        print("AI回合结束")  # 调试
        self.is_ai_turn = False
        self.current_turn += 1
        
        # 重置中国单位
        for u in self.units:
            if u.faction == Faction.CHINA:
                u.reset_turn()
            if u.faction == Faction.JAPAN:
                u.ai_highlight = False
        
        # 检查胜利条件
        cn = any(u.faction == Faction.CHINA and u.is_alive() for u in self.units)
        jp = any(u.faction == Faction.JAPAN and u.is_alive() for u in self.units)
        
        if not cn:
            self.message = "战败！日军胜利！"
            self.is_ai_turn = True
        elif not jp:
            self.message = "胜利！中国军队获胜！"
            self.is_ai_turn = True
        else:
            self.message = f"第{self.current_turn}回合 - 中国军队行动"
    
    def draw(self):
        self.screen.fill(Colors.BLACK)
        self.draw_map()
        self.draw_units()
        self.draw_panel()
        self.draw_message()
        pygame.display.flip()
    
    def draw_map(self):
        colors = {
            "平原": Colors.LIGHT_GREEN,
            "森林": Colors.DARK_GREEN,
            "山地": Colors.GRAY,
            "河流": Colors.BLUE,
            "城市": Colors.BROWN,
            "道路": Colors.YELLOW,
        }
        
        for y in range(self.map.height):
            for x in range(self.map.width):
                terrain = self.map.tiles[y][x]
                color = colors.get(terrain, Colors.LIGHT_GREEN)
                rect = pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                pygame.draw.rect(self.screen, color, rect)
                pygame.draw.rect(self.screen, Colors.BLACK, rect, 1)
                
                # 地形标签
                if terrain != "平原":
                    label = terrain[0]
                    text = self.small_font.render(label, True, Colors.WHITE)
                    cx = x * TILE_SIZE + TILE_SIZE // 2 - 8
                    cy = y * TILE_SIZE + TILE_SIZE // 2 - 8
                    self.screen.blit(text, (cx, cy))
    
    def draw_units(self):
        for unit in self.units:
            if not unit.is_alive():
                continue
            
            cx = unit.x * TILE_SIZE + TILE_SIZE // 2
            cy = unit.y * TILE_SIZE + TILE_SIZE // 2
            r = TILE_SIZE // 3
            
            # 颜色
            color = Colors.RED if unit.faction == Faction.CHINA else Colors.BLUE
            
            # AI高亮
            if unit.ai_highlight:
                pygame.draw.circle(self.screen, Colors.GOLD, (cx, cy), r + 6, 4)
                # 闪烁效果
                pulse = int(abs(math.sin(pygame.time.get_ticks() * 0.005)) * 3)
                pygame.draw.circle(self.screen, Colors.YELLOW, (cx, cy), r + 6 + pulse, 1)
            
            # 选中
            if unit.selected:
                pygame.draw.circle(self.screen, Colors.GOLD, (cx, cy), r + 4, 3)
            
            # 单位圆
            pygame.draw.circle(self.screen, color, (cx, cy), r)
            pygame.draw.circle(self.screen, Colors.BLACK, (cx, cy), r, 1)
            
            # 生命条
            hp = unit.health / unit.max_health
            bw = TILE_SIZE - 10
            bh = 4
            bx = cx - bw // 2
            by = cy - r - 10
            pygame.draw.rect(self.screen, Colors.DARK_GRAY, (bx-1, by-1, bw+2, bh+2))
            pygame.draw.rect(self.screen, Colors.RED, (bx, by, bw, bh))
            if hp > 0:
                hc = Colors.GREEN if hp > 0.5 else Colors.ORANGE
                pygame.draw.rect(self.screen, hc, (bx, by, int(bw * hp), bh))
            
            # 标签
            label = unit.unit_type.value[:2]
            text = self.small_font.render(label, True, Colors.WHITE)
            tr = text.get_rect(center=(cx, cy))
            self.screen.blit(text, tr)
            
            # AI标记
            if unit.faction == Faction.JAPAN:
                ai_text = self.small_font.render("AI", True, Colors.YELLOW)
                self.screen.blit(ai_text, (cx - 10, cy - r - 22))
    
    def draw_panel(self):
        px = self.map_width
        pygame.draw.rect(self.screen, Colors.DARK_GRAY, (px, 0, self.panel_width, SCREEN_HEIGHT))
        pygame.draw.line(self.screen, Colors.GOLD, (px, 0), (px, SCREEN_HEIGHT), 2)
        
        y = 10
        title = self.title_font.render("兵棋推演", True, Colors.GOLD)
        self.screen.blit(title, (px + 10, y))
        y += 40
        
        sub = self.small_font.render("玩家 vs AI (1子/回合)", True, Colors.CYAN)
        self.screen.blit(sub, (px + 10, y))
        y += 30
        
        info = [
            f"回合: {self.current_turn}",
            f"金币: {self.gold}",
            f"收入: {self.income}/回合",
        ]
        if self.is_ai_turn:
            info.append("状态: AI行动中")
        
        for line in info:
            t = self.font.render(line, True, Colors.WHITE)
            self.screen.blit(t, (px + 15, y))
            y += 28
        
        y += 5
        pygame.draw.line(self.screen, Colors.GRAY, (px + 10, y), (px + self.panel_width - 20, y), 1)
        y += 15
        
        # 选中单位
        if self.selected_unit:
            u = self.selected_unit
            t = self.font.render("【选中单位】", True, Colors.GOLD)
            self.screen.blit(t, (px + 10, y))
            y += 28
            
            lines = [
                f"兵种: {u.unit_type.value}",
                f"生命: {u.health}/{u.max_health}",
                f"攻击: {u.attack}",
                f"防御: {u.defense}",
                f"移动: {u.movement}",
                f"射程: {u.range}",
                f"等级: {u.level}",
            ]
            if u.equipped_weapon:
                lines.append(f"武器: {u.equipped_weapon.name}")
            
            for line in lines:
                t = self.small_font.render(line, True, Colors.YELLOW)
                self.screen.blit(t, (px + 20, y))
                y += 22
            
            y += 5
            pygame.draw.line(self.screen, Colors.GRAY, (px + 10, y), (px + self.panel_width - 20, y), 1)
            y += 10
        
        # 武器商店
        t = self.font.render("━━ 武器商店 ━━", True, Colors.GOLD)
        self.screen.blit(t, (px + 10, y))
        y += 30
        
        for w in self.weapons[:12]:
            c = Colors.CYAN if self.gold >= w.price else Colors.GRAY
            t = self.small_font.render(w.name, True, c)
            self.screen.blit(t, (px + 15, y))
            
            pt = self.small_font.render(f"{w.price}金", True, Colors.GOLD)
            self.screen.blit(pt, (px + self.panel_width - 60, y))
            y += 24
        
        y += 5
        pygame.draw.line(self.screen, Colors.GRAY, (px + 10, y), (px + self.panel_width - 20, y), 1)
        y += 10
        
        # 战斗日志
        t = self.font.render("━━ 战斗日志 ━━", True, Colors.GOLD)
        self.screen.blit(t, (px + 10, y))
        y += 30
        
        for log in self.combat_log[-5:]:
            c = Colors.ORANGE if "[日军]" in log else Colors.WHITE
            t = self.small_font.render(log[:25], True, c)
            self.screen.blit(t, (px + 15, y))
            y += 20
        
        # 结束按钮
        by = SCREEN_HEIGHT - 50
        btn = pygame.Rect(px + 10, by, self.panel_width - 40, 35)
        bc = Colors.DARK_GRAY if self.is_ai_turn else Colors.RED
        pygame.draw.rect(self.screen, bc, btn)
        pygame.draw.rect(self.screen, Colors.GOLD, btn, 2)
        
        bt = "AI行动中..." if self.is_ai_turn else "结束回合 (空格)"
        t = self.font.render(bt, True, Colors.WHITE)
        tr = t.get_rect(center=btn.center)
        self.screen.blit(t, tr)
    
    def draw_message(self):
        if self.message:
            rect = pygame.Rect(0, SCREEN_HEIGHT - 35, self.map_width, 35)
            pygame.draw.rect(self.screen, Colors.DARK_GRAY, rect)
            pygame.draw.line(self.screen, Colors.GOLD, (0, SCREEN_HEIGHT - 35), (self.map_width, SCREEN_HEIGHT - 35), 1)
            t = self.small_font.render(self.message, True, Colors.YELLOW)
            self.screen.blit(t, (10, SCREEN_HEIGHT - 28))
    
    def run(self):
        while self.running:
            self.handle_events()
            self.draw()
            self.clock.tick(FPS)
        pygame.quit()
        sys.exit()

# 运行
if __name__ == "__main__":
    print("游戏启动...")
    print("操作说明：")
    print("  左键点击 - 选择单位")
    print("  右键点击 - 移动/攻击")
    print("  空格键 - 结束回合")
    print("  TAB键 - 切换单位")
    print("  R键 - 重置单位")
    print("  ESC键 - 取消选择")
    game = WarGame()
    game.run()