import tkinter as tk
from tkinter import ttk, messagebox
import random
from dataclasses import dataclass
from typing import Optional, Tuple
from enum import Enum

class UnitType(Enum):
    INFANTRY = "步兵"
    ARMOR = "坦克"
    ARTILLERY = "火炮"
    AIR = "空军"
    SNIPER = "狙击手"
    MEDIC = "医疗兵"

@dataclass
class Unit:
    name: str
    type: UnitType
    attack: int
    defense: int
    health: int
    max_health: int
    range: int
    movement: int
    max_movement: int
    special_ability: str
    icon: str
    icon_color: str
    has_acted: bool = False
    x: int = 0
    y: int = 0
    stealth: bool = False
    armor_piercing: bool = False
    air_strike: bool = False

class BattleSystem:
    @staticmethod
    def calculate_damage(attacker: Unit, defender: Unit, terrain_bonus: float = 1.0, is_sniper_shot: bool = False):
        base_damage = max(1, attacker.attack - defender.defense)
        
        if is_sniper_shot:
            base_damage = attacker.attack * 2
            if random.random() < 0.3:
                base_damage = int(base_damage * 1.5)
                return base_damage, True
        
        random_factor = random.uniform(0.8, 1.2)
        damage = base_damage * random_factor * terrain_bonus
        
        if attacker.type == UnitType.ARMOR and attacker.armor_piercing:
            if defender.type == UnitType.ARMOR:
                damage *= 1.5
        
        if attacker.type == UnitType.AIR and attacker.air_strike:
            damage *= 1.3
            if defender.type == UnitType.ARTILLERY:
                damage *= 1.5
            
        return int(damage), False
    
    @staticmethod
    def fight(attacker: Unit, defender: Unit, terrain_bonus: float = 1.0, is_special: bool = False):
        is_critical = False
        if attacker.type == UnitType.SNIPER and is_special:
            damage, is_critical = BattleSystem.calculate_damage(attacker, defender, terrain_bonus, True)
            defender.health -= damage
            crit_text = " ⚡暴击！" if is_critical else ""
            result = f"{attacker.name} 🔫 狙击 {defender.name}，造成 {damage} 点伤害！{crit_text}"
        elif attacker.type == UnitType.MEDIC and is_special:
            heal_amount = 25
            old_health = defender.health
            defender.health = min(defender.max_health, defender.health + heal_amount)
            actual_heal = defender.health - old_health
            result = f"{attacker.name} 💊 治疗了 {defender.name} {actual_heal} 生命值！"
            return result, False
        else:
            damage, _ = BattleSystem.calculate_damage(attacker, defender, terrain_bonus, False)
            defender.health -= damage
            result = f"{attacker.name} 对 {defender.name} 造成 {damage} 点伤害！"
        
        result += f" {defender.name} 剩余生命: {defender.health}/{defender.max_health}"
        
        if defender.health <= 0:
            result += f" {defender.name} 已被摧毁！"
            return result, True
        return result, False

class AIPlayer:
    def __init__(self, game):
        self.game = game
        
    def is_in_range(self, unit: Unit, target: Unit) -> bool:
        return abs(unit.x - target.x) + abs(unit.y - target.y) <= unit.range
    
    def make_decision(self):
        available_units = [u for u in self.game.ai_units if not u.has_acted]
        
        if not available_units or self.game.ai_has_acted:
            return False
        
        enemies = self.game.player_units
        if not enemies:
            return False
            
        for unit in available_units:
            # 医疗兵治疗
            if unit.type == UnitType.MEDIC:
                for ally in self.game.ai_units:
                    if ally != unit and ally.health < ally.max_health and self.is_in_range(unit, ally):
                        self.game.use_special_ability(unit, ally)
                        unit.has_acted = True
                        self.game.ai_has_acted = True
                        return True
            
            # 狙击手狙击
            if unit.type == UnitType.SNIPER:
                for enemy in enemies:
                    if self.is_in_range(unit, enemy):
                        self.game.use_special_ability(unit, enemy)
                        unit.has_acted = True
                        self.game.ai_has_acted = True
                        return True
            
            # 普通攻击
            for enemy in enemies:
                if self.is_in_range(unit, enemy):
                    self.game.attack_unit(unit, enemy)
                    unit.has_acted = True
                    self.game.ai_has_acted = True
                    return True
            
            # 移动
            closest = min(enemies, key=lambda e: abs(unit.x - e.x) + abs(unit.y - e.y))
            dx = 1 if closest.x > unit.x else -1 if closest.x < unit.x else 0
            dy = 1 if closest.y > unit.y else -1 if closest.y < unit.y else 0
            
            if dx != 0:
                new_x, new_y = unit.x + dx, unit.y
            else:
                new_x, new_y = unit.x, unit.y + dy
            
            if self.game.is_valid_move(unit, new_x, new_y):
                self.game.move_unit(unit, new_x, new_y)
                unit.has_acted = True
                self.game.ai_has_acted = True
                return True
        
        return False

class WarGame:
    def __init__(self):
        self.map_size = 8
        self.player_units = []
        self.ai_units = []
        self.current_turn = "player"
        self.selected_unit = None
        self.ai_player = AIPlayer(self)
        self.log_callback = None
        self.player_has_acted = False
        self.ai_has_acted = False
        self.setup_units()
        
    def setup_units(self):
        self.player_units = [
            Unit("精英步兵", UnitType.INFANTRY, 18, 12, 35, 35, 2, 3, 3, "无", "🗡️", "#FFD700"),
            Unit("重型坦克", UnitType.ARMOR, 35, 30, 80, 80, 3, 4, 4, "穿甲弹", "🔰", "#FFA500", armor_piercing=True),
            Unit("自行火炮", UnitType.ARTILLERY, 35, 10, 30, 30, 5, 2, 2, "无", "💣", "#FF6347"),
            Unit("攻击机", UnitType.AIR, 30, 20, 55, 55, 4, 5, 5, "空袭", "🛩️", "#87CEEB", air_strike=True),
            Unit("狙击手", UnitType.SNIPER, 40, 8, 25, 25, 6, 2, 2, "狙击", "🎯", "#32CD32", stealth=True),
            Unit("医疗兵", UnitType.MEDIC, 5, 15, 30, 30, 2, 3, 3, "治疗", "💊", "#FF69B4")
        ]
        
        self.ai_units = [
            Unit("铁血步兵", UnitType.INFANTRY, 20, 14, 40, 40, 2, 3, 3, "无", "⚔️", "#FF4444"),
            Unit("主战坦克", UnitType.ARMOR, 38, 32, 85, 85, 3, 4, 4, "穿甲弹", "🏆", "#FF4444", armor_piercing=True),
            Unit("火箭炮", UnitType.ARTILLERY, 38, 12, 35, 35, 5, 2, 2, "无", "🔥", "#FF4444"),
            Unit("武装直升机", UnitType.AIR, 32, 22, 60, 60, 4, 5, 5, "空袭", "🚁", "#FF4444", air_strike=True),
            Unit("王牌狙击手", UnitType.SNIPER, 45, 10, 30, 30, 6, 2, 2, "狙击", "🎯", "#FF4444", stealth=True),
            Unit("战地医生", UnitType.MEDIC, 8, 18, 35, 35, 2, 3, 3, "治疗", "🏥", "#FF4444")
        ]
        
        for i, unit in enumerate(self.player_units):
            unit.x = i
            unit.y = 0
        for i, unit in enumerate(self.ai_units):
            unit.x = self.map_size - 1 - i
            unit.y = self.map_size - 1
            
    def get_unit_at(self, x: int, y: int):
        for unit in self.player_units:
            if unit.x == x and unit.y == y:
                return unit, "player"
        for unit in self.ai_units:
            if unit.x == x and unit.y == y:
                return unit, "ai"
        return None, None
    
    def is_valid_move(self, unit: Unit, new_x: int, new_y: int) -> bool:
        if new_x < 0 or new_x >= self.map_size or new_y < 0 or new_y >= self.map_size:
            return False
        if abs(new_x - unit.x) + abs(new_y - unit.y) > unit.movement:
            return False
        target_unit, side = self.get_unit_at(new_x, new_y)
        if target_unit:
            return (unit in self.player_units and side == "ai") or (unit in self.ai_units and side == "player")
        return True
    
    def move_unit(self, unit: Unit, new_x: int, new_y: int) -> bool:
        if not self.is_valid_move(unit, new_x, new_y):
            return False
        target_unit, side = self.get_unit_at(new_x, new_y)
        if target_unit:
            return self.attack_unit(unit, target_unit)
        unit.x = new_x
        unit.y = new_y
        return True
    
    def use_special_ability(self, attacker: Unit, target: Unit) -> bool:
        # 检查距离
        distance = abs(attacker.x - target.x) + abs(attacker.y - target.y)
        if distance > attacker.range:
            if self.log_callback:
                self.log_callback(f"距离太远！需要{attacker.range}格，实际{distance}格")
            return False
        
        # 医疗兵治疗
        if attacker.type == UnitType.MEDIC:
            # 只能治疗友军
            if (attacker in self.player_units and target in self.player_units) or \
               (attacker in self.ai_units and target in self.ai_units):
                result, _ = BattleSystem.fight(attacker, target, 1.0, True)
                if self.log_callback:
                    self.log_callback(result)
                return True
            else:
                if self.log_callback:
                    self.log_callback("医疗兵只能治疗友军单位！")
                return False
        
        # 狙击手狙击
        elif attacker.type == UnitType.SNIPER:
            # 只能攻击敌军
            if (attacker in self.player_units and target in self.ai_units) or \
               (attacker in self.ai_units and target in self.player_units):
                result, is_dead = BattleSystem.fight(attacker, target, 1.0, True)
                if self.log_callback:
                    self.log_callback(result)
                if is_dead:
                    if target in self.player_units:
                        self.player_units.remove(target)
                    else:
                        self.ai_units.remove(target)
                return True
            else:
                if self.log_callback:
                    self.log_callback("狙击手只能攻击敌军单位！")
                return False
        
        return False
            
    def attack_unit(self, attacker: Unit, defender: Unit) -> bool:
        if abs(attacker.x - defender.x) + abs(attacker.y - defender.y) > attacker.range:
            return False
        result, is_dead = BattleSystem.fight(attacker, defender, 1.0, False)
        if self.log_callback:
            self.log_callback(result)
        if is_dead:
            if defender in self.player_units:
                self.player_units.remove(defender)
            else:
                self.ai_units.remove(defender)
        return True
    
    def reset_action_flags(self):
        for unit in self.player_units + self.ai_units:
            unit.has_acted = False
            
    def next_turn(self):
        self.current_turn = "ai" if self.current_turn == "player" else "player"
        self.player_has_acted = False
        self.ai_has_acted = False
        self.reset_action_flags()
        self.selected_unit = None
        
    def check_winner(self) -> Optional[str]:
        if len(self.player_units) == 0:
            return "AI"
        elif len(self.ai_units) == 0:
            return "Player"
        return None

class WarGameGUI:
    def __init__(self):
        self.game = WarGame()
        self.game.log_callback = self.add_log_message
        self.root = tk.Tk()
        self.root.title("战争兵棋推演 - 医疗兵/狙击手已修复")
        self.root.geometry("1200x750")
        self.root.configure(bg="#2c3e50")
        
        self.create_widgets()
        self.update_map()
        self.update_status()
        
    def create_widgets(self):
        title_frame = tk.Frame(self.root, bg="#2c3e50", height=60)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="⚔️ 战争兵棋推演 - 医疗兵/狙击手已修复 ⚔️", 
                font=("Arial", 18, "bold"), fg="#ecf0f1", bg="#2c3e50").pack(pady=10)
        
        main_frame = tk.Frame(self.root, bg="#2c3e50")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 规则面板
        rules_frame = tk.Frame(main_frame, bg="#34495e", relief=tk.RAISED, bd=2)
        rules_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5)
        tk.Label(rules_frame, text="📖 游戏规则", font=("Arial", 14, "bold"), fg="#f39c12", bg="#34495e").pack(pady=10)
        
        rules_text = """【核心规则】
每回合只能移动一个单位！

【特殊能力使用】
💊 医疗兵: 选中后点击友军单位治疗
🎯 狙击手: 选中后点击敌军单位狙击
🔰 坦克: 穿甲弹(对坦克+50%)
🛩️ 飞机: 空袭(伤害+30%)

【移动步数】
步兵:3 坦克:4 火炮:2
空军:5 狙击手:2 医疗兵:3

【操作说明】
1. 点击己方单位选中
2. 医疗兵：点击友军治疗
3. 狙击手：点击敌军狙击
4. 其他单位：点击格子移动/攻击"""
        
        text_widget = tk.Text(rules_frame, width=30, height=30, font=("Consolas", 10),
                             bg="#2c3e50", fg="#ecf0f1", wrap=tk.WORD)
        text_widget.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
        text_widget.insert(1.0, rules_text)
        text_widget.config(state=tk.DISABLED)
        
        # 地图面板
        map_frame = tk.Frame(main_frame, bg="#2c3e50")
        map_frame.pack(side=tk.LEFT, expand=True, fill=tk.BOTH, padx=10)
        self.canvas = tk.Canvas(map_frame, width=600, height=600, bg="#ecf0f1", relief=tk.SUNKEN, bd=3)
        self.canvas.pack(expand=True)
        self.canvas.bind("<Button-1>", self.on_map_click)
        
        # 信息面板
        info_frame = tk.Frame(main_frame, bg="#34495e", relief=tk.RAISED, bd=2, width=280)
        info_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=5)
        info_frame.pack_propagate(False)
        
        self.turn_label = tk.Label(info_frame, text="", font=("Arial", 16, "bold"), fg="#f39c12", bg="#34495e")
        self.turn_label.pack(pady=15)
        self.action_label = tk.Label(info_frame, text="", font=("Arial", 12, "bold"), fg="#e74c3c", bg="#34495e")
        self.action_label.pack(pady=5)
        
        # 使用说明
        tk.Label(info_frame, text="💡 使用说明:", font=("Arial", 10, "bold"), fg="#f39c12", bg="#34495e").pack(pady=5)
        tk.Label(info_frame, text="💊 医疗兵 → 点击友军治疗", font=("Arial", 9), fg="#27ae60", bg="#34495e").pack()
        tk.Label(info_frame, text="🎯 狙击手 → 点击敌军狙击", font=("Arial", 9), fg="#e74c3c", bg="#34495e").pack()
        tk.Label(info_frame, text="🔰 坦克 → 自动穿甲效果", font=("Arial", 9), fg="#3498db", bg="#34495e").pack()
        tk.Label(info_frame, text="🛩️ 飞机 → 自动空袭效果", font=("Arial", 9), fg="#1abc9c", bg="#34495e").pack()
        
        tk.Frame(info_frame, height=2, bg="#7f8c8d").pack(fill=tk.X, padx=10, pady=10)
        
        self.unit_info_label = tk.Label(info_frame, text="点击单位查看详细信息", font=("Arial", 10), 
                                       bg="#34495e", fg="#ecf0f1", wraplength=260, justify=tk.LEFT)
        self.unit_info_label.pack(pady=10, padx=10)
        
        tk.Frame(info_frame, height=2, bg="#7f8c8d").pack(fill=tk.X, padx=10, pady=10)
        
        log_frame = tk.LabelFrame(info_frame, text="📝 战斗日志", bg="#34495e", fg="#ecf0f1")
        log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        self.log_text = tk.Text(log_frame, height=12, width=30, font=("Arial", 9), bg="#2c3e50", fg="#ecf0f1", wrap=tk.WORD)
        scrollbar = tk.Scrollbar(log_frame, command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=scrollbar.set)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        button_frame = tk.Frame(info_frame, bg="#34495e")
        button_frame.pack(fill=tk.X, pady=15, padx=10)
        self.end_turn_btn = tk.Button(button_frame, text="结束回合", command=self.end_turn,
                                     font=("Arial", 11, "bold"), bg="#3498db", fg="white")
        self.end_turn_btn.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        tk.Button(button_frame, text="重置游戏", command=self.reset_game,
                 font=("Arial", 11, "bold"), bg="#e74c3c", fg="white").pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        self.stats_label = tk.Label(info_frame, text="", font=("Arial", 11, "bold"), bg="#34495e", fg="#ecf0f1")
        self.stats_label.pack(pady=10)
        
    def draw_health_bar(self, x, y, size, current_hp, max_hp):
        bar_width = size - 10
        bar_height = 6
        bar_x = x + 5
        bar_y = y + size - 12
        self.canvas.create_rectangle(bar_x, bar_y, bar_x + bar_width, bar_y + bar_height, fill="#c0392b", outline="")
        health_percent = current_hp / max_hp
        self.canvas.create_rectangle(bar_x, bar_y, bar_x + bar_width * health_percent, bar_y + bar_height, fill="#27ae60", outline="")
        self.canvas.create_rectangle(bar_x, bar_y, bar_x + bar_width, bar_y + bar_height, outline="#2c3e50", width=1)
        
    def update_map(self):
        self.canvas.delete("all")
        cell_size = 600 // self.game.map_size
        
        for i in range(self.game.map_size + 1):
            self.canvas.create_line(i * cell_size, 0, i * cell_size, 600, fill="#bdc3c7", width=2)
            self.canvas.create_line(0, i * cell_size, 600, i * cell_size, fill="#bdc3c7", width=2)
        
        for y in range(self.game.map_size):
            for x in range(self.game.map_size):
                color = "#f8f9fa" if (x + y) % 2 == 0 else "#e9ecef"
                self.canvas.create_rectangle(x * cell_size, y * cell_size, (x+1) * cell_size, (y+1) * cell_size, fill=color, outline="")
        
        # 玩家单位
        for unit in self.game.player_units:
            x, y = unit.x * cell_size, unit.y * cell_size
            if self.game.selected_unit == unit:
                bg_color = "#f1c40f"
            elif unit.has_acted:
                bg_color = "#7f8c8d"
            else:
                bg_color = "#3498db"
            self.canvas.create_oval(x+5, y+5, x+cell_size-5, y+cell_size-5, fill=bg_color, outline="#2c3e50", width=3)
            self.canvas.create_text(x+cell_size//2, y+cell_size//2-5, text=unit.icon, font=("Segoe UI Emoji", 28))
            self.canvas.create_text(x+cell_size//2, y+cell_size//2+18, text=f"{unit.health}", font=("Arial", 11, "bold"), fill="white")
            self.draw_health_bar(x, y, cell_size, unit.health, unit.max_health)
            if unit.has_acted:
                self.canvas.create_text(x+cell_size-12, y+8, text="✓", font=("Arial", 16, "bold"), fill="#27ae60")
            self.canvas.create_text(x+cell_size//2, y+cell_size-5, text=unit.type.value, font=("Arial", 8), fill="#2c3e50")
        
        # AI单位
        for unit in self.game.ai_units:
            x, y = unit.x * cell_size, unit.y * cell_size
            if self.game.selected_unit == unit:
                bg_color = "#f1c40f"
            elif unit.has_acted:
                bg_color = "#95a5a6"
            else:
                bg_color = "#e74c3c"
            self.canvas.create_oval(x+5, y+5, x+cell_size-5, y+cell_size-5, fill=bg_color, outline="#2c3e50", width=3)
            self.canvas.create_text(x+cell_size//2, y+cell_size//2-5, text=unit.icon, font=("Segoe UI Emoji", 28))
            self.canvas.create_text(x+cell_size//2, y+cell_size//2+18, text=f"{unit.health}", font=("Arial", 11, "bold"), fill="white")
            self.draw_health_bar(x, y, cell_size, unit.health, unit.max_health)
            if unit.has_acted:
                self.canvas.create_text(x+cell_size-12, y+8, text="✓", font=("Arial", 16, "bold"), fill="#27ae60")
            self.canvas.create_text(x+cell_size//2, y+cell_size-5, text=unit.type.value, font=("Arial", 8), fill="#2c3e50")
        
        # 可移动范围
        if self.game.selected_unit and not self.game.selected_unit.has_acted:
            unit = self.game.selected_unit
            for dx in range(-unit.movement, unit.movement+1):
                for dy in range(-unit.movement, unit.movement+1):
                    if abs(dx)+abs(dy) <= unit.movement:
                        nx, ny = unit.x+dx, unit.y+dy
                        if 0 <= nx < self.game.map_size and 0 <= ny < self.game.map_size:
                            target, side = self.game.get_unit_at(nx, ny)
                            if not target or ((unit in self.game.player_units and side == "ai") or (unit in self.game.ai_units and side == "player")):
                                x1, y1 = nx*cell_size, ny*cell_size
                                self.canvas.create_rectangle(x1, y1, x1+cell_size, y1+cell_size, fill="#2ecc71", stipple="gray50", outline="")
                                self.canvas.create_rectangle(x1, y1, x1+cell_size, y1+cell_size, outline="#27ae60", width=2, dash=(5,5))
        
    def add_log_message(self, message: str):
        from datetime import datetime
        self.log_text.insert(tk.END, f"[{datetime.now().strftime('%H:%M:%S')}] {message}\n")
        self.log_text.see(tk.END)
        
    def update_status(self):
        if self.game.current_turn == "player":
            if not self.game.player_has_acted:
                self.turn_label.config(text="🎮 玩家回合")
                self.action_label.config(text="⚠️ 选择一个未行动的单位")
                self.end_turn_btn.config(state="normal", bg="#3498db")
            else:
                self.turn_label.config(text="🎮 玩家回合")
                self.action_label.config(text="✅ 已行动，点击结束回合")
                self.end_turn_btn.config(state="normal", bg="#3498db")
        else:
            if not self.game.ai_has_acted:
                self.turn_label.config(text="🤖 AI回合")
                self.action_label.config(text="🤖 AI正在思考...")
                self.end_turn_btn.config(state="disabled", bg="#95a5a6")
            else:
                self.turn_label.config(text="🤖 AI回合")
                self.action_label.config(text="✅ AI已行动")
                self.end_turn_btn.config(state="normal", bg="#3498db")
        self.stats_label.config(text=f"👤 玩家: {len(self.game.player_units)}   🤖 AI: {len(self.game.ai_units)}")
        
    def on_map_click(self, event):
        if self.game.current_turn != "player":
            self.add_log_message("请等待AI完成回合！")
            return
        if self.game.player_has_acted:
            self.add_log_message("本回合已经行动过了！点击'结束回合'继续")
            return
            
        cell_size = 600 // self.game.map_size
        x, y = event.x // cell_size, event.y // cell_size
        if x >= self.game.map_size or y >= self.game.map_size:
            return
            
        clicked_unit, side = self.game.get_unit_at(x, y)
        
        # 选中己方单位
        if clicked_unit and side == "player" and not clicked_unit.has_acted:
            self.game.selected_unit = clicked_unit
            ability_text = ""
            if clicked_unit.type == UnitType.MEDIC:
                ability_text = "\n💊 特殊: 点击友军单位治疗25HP"
            elif clicked_unit.type == UnitType.SNIPER:
                ability_text = "\n🎯 特殊: 点击敌军单位狙击(双倍伤害+暴击)"
            elif clicked_unit.type == UnitType.ARMOR:
                ability_text = "\n💢 被动: 穿甲弹(对坦克+50%伤害)"
            elif clicked_unit.type == UnitType.AIR:
                ability_text = "\n💥 被动: 空袭(伤害+30%)"
                
            self.unit_info_label.config(text=f"{clicked_unit.icon} {clicked_unit.name}\n攻击:{clicked_unit.attack} 防御:{clicked_unit.defense}\n生命:{clicked_unit.health}/{clicked_unit.max_health}\n移动:{clicked_unit.movement} 范围:{clicked_unit.range}{ability_text}")
            self.update_map()
            return
            
        # 执行行动
        if self.game.selected_unit:
            success = False
            action_type = ""
            
            # 医疗兵治疗友军
            if self.game.selected_unit.type == UnitType.MEDIC and clicked_unit and side == "player":
                success = self.game.use_special_ability(self.game.selected_unit, clicked_unit)
                action_type = "治疗"
            
            # 狙击手狙击敌军
            elif self.game.selected_unit.type == UnitType.SNIPER and clicked_unit and side == "ai":
                success = self.game.use_special_ability(self.game.selected_unit, clicked_unit)
                action_type = "狙击"
            
            # 普通移动/攻击
            else:
                success = self.game.move_unit(self.game.selected_unit, x, y)
                if success:
                    # 检查是否发生了攻击
                    target, _ = self.game.get_unit_at(x, y)
                    if target:
                        action_type = "攻击"
                    else:
                        action_type = "移动"
            
            if success:
                self.game.selected_unit.has_acted = True
                self.game.player_has_acted = True
                self.add_log_message(f"✅ {self.game.selected_unit.name} 执行了{action_type}")
                self.game.selected_unit = None
                self.update_map()
                self.update_status()
                
                winner = self.game.check_winner()
                if winner:
                    winner_name = "玩家" if winner == "Player" else "AI"
                    messagebox.showinfo("游戏结束", f"🏆 {winner_name} 获得胜利！🏆")
                    self.reset_game()
            else:
                self.add_log_message("❌ 行动失败，请检查距离和目标")
                
        self.update_map()
        
    def end_turn(self):
        if self.game.current_turn == "player":
            if not self.game.player_has_acted and self.game.player_units:
                if not messagebox.askyesno("确认", "还有单位未行动，确定要结束回合吗？"):
                    return
            self.game.next_turn()
            self.update_map()
            self.update_status()
            self.add_log_message("="*40 + "\n🤖 AI回合开始")
            self.ai_turn()
            
    def ai_turn(self):
        if self.game.current_turn != "ai":
            return
        
        self.game.ai_player.make_decision()
        self.update_map()
        self.update_status()
        
        winner = self.game.check_winner()
        if winner:
            winner_name = "玩家" if winner == "Player" else "AI"
            messagebox.showinfo("游戏结束", f"🏆 {winner_name} 获得胜利！🏆")
            self.reset_game()
            return
        
        self.add_log_message("🤖 AI回合结束\n" + "="*40 + "\n🎮 玩家回合开始")
        self.game.next_turn()
        self.update_status()
        
    def reset_game(self):
        self.game = WarGame()
        self.game.log_callback = self.add_log_message
        self.log_text.delete(1.0, tk.END)
        self.update_map()
        self.update_status()
        self.add_log_message("✨ 游戏已重置！ ✨")
        
    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    game = WarGameGUI()
    game.run()