import pygame
import random
import sys
import os

pygame.init()
WIDTH, HEIGHT = 1100, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("KARDS 风格卡牌游戏 - 简化版")
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
LIGHT_GRAY = (200, 200, 200)
GREEN = (0, 200, 0)
DARK_GREEN = (0, 100, 0)
RED = (200, 0, 0)
BLUE = (0, 0, 200)
YELLOW = (255, 215, 0)
ORANGE = (255, 140, 0)
PURPLE = (128, 0, 128)


def get_font(size):
    font_paths = [
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/msyh.ttf",
        "C:/Windows/Fonts/simsun.ttc",
        "C:/Windows/Fonts/arial.ttf",
    ]
    for path in font_paths:
        if os.path.exists(path):
            try:
                return pygame.font.Font(path, size)
            except Exception:
                continue
    try:
        return pygame.font.SysFont("simhei", size)
    except Exception:
        pass
    return pygame.font.Font(None, size)


font_small = get_font(13)
font_med = get_font(16)
font_large = get_font(20)
font_title = get_font(32)

MAX_HAND = 8
MAX_LINE = 5
HQ_DEFENSE = 20
MAX_COMMAND = 12

ENEMY_SUPPORT_Y = 50
ENEMY_FRONT_Y = 140
PLAYER_FRONT_Y = 240
PLAYER_SUPPORT_Y = 330
HAND_Y = 460

CARD_W, CARD_H = 95, 150
UNIT_W, UNIT_H = 95, 75
LINE_START_X = 130
LINE_SPACING = 100

END_BTN = pygame.Rect(WIDTH - 130, 5, 120, 35)
RESTART_BTN = pygame.Rect(WIDTH // 2 - 70, HEIGHT // 2 + 30, 140, 45)


class Card:
    def __init__(self, name, card_type, cost, attack=0, health=0, faction="德国", effect=None):
        self.name = name
        self.card_type = card_type
        self.cost = cost
        self.attack = attack
        self.health = health
        self.max_health = health
        self.faction = faction
        self.effect = effect


def create_card_pool():
    return [
        Card("步兵班", "单位", 1, 1, 2, "德国"),
        Card("掷弹兵", "单位", 2, 2, 3, "德国"),
        Card("伞兵", "单位", 3, 3, 2, "德国", "空降"),
        Card("国民突击队", "单位", 1, 1, 1, "德国"),
        Card("四号坦克", "单位", 4, 4, 5, "德国"),
        Card("虎式坦克", "单位", 7, 7, 8, "德国", "重甲"),
        Card("豹式坦克", "单位", 5, 5, 6, "德国"),
        Card("野战炮", "单位", 2, 1, 3, "德国", "远程"),
        Card("火箭炮", "单位", 4, 2, 4, "德国", "远程"),
        Card("战斗机", "单位", 3, 3, 3, "德国", "飞行"),
        Card("轰炸机", "单位", 5, 4, 4, "德国", "飞行"),
        Card("闪电战", "指令", 2, 0, 0, "德国", "抽牌"),
        Card("铁拳", "指令", 3, 0, 0, "德国", "伤害3"),
        Card("炮击", "指令", 4, 0, 0, "德国", "总部伤害2"),
        Card("增援", "指令", 1, 0, 0, "德国", "治疗2"),
        Card("意大利步兵", "单位", 1, 1, 2, "意大利"),
        Card("意大利坦克", "单位", 3, 3, 4, "意大利"),
        Card("地中海舰队", "指令", 3, 0, 0, "意大利", "群伤1"),
        Card("日本步兵", "单位", 1, 2, 1, "日本"),
        Card("零式战斗机", "单位", 4, 4, 3, "日本", "飞行"),
        Card("神风特攻", "指令", 2, 0, 0, "日本", "伤害4"),
    ]


class Unit:
    def __init__(self, card, owner, line):
        self.card = card
        self.name = card.name
        self.attack = card.attack
        self.health = card.health
        self.max_health = card.max_health
        self.owner = owner
        self.line = line
        self.has_attacked = False
        self.just_deployed = True

    def can_attack(self):
        if self.has_attacked:
            return False
        if self.card.effect == "远程":
            return True
        if self.line == "front":
            return True
        return False

    def can_attack_target(self, target):
        """检查是否能攻击指定单位"""
        # 飞行规则
        if self.card.effect == "飞行" and target.card.effect not in ("飞行", "远程"):
            return False
        if target.card.effect == "飞行" and self.card.effect not in ("飞行", "远程"):
            return False
        return True

    def take_damage(self, dmg):
        if self.card.effect == "重甲":
            dmg = max(0, dmg - 1)
        self.health -= dmg
        return self.health <= 0


class Player:
    def __init__(self, name, is_player=True):
        self.name = name
        self.is_player = is_player
        self.hq = HQ_DEFENSE
        self.command = 0
        self.max_command = 0
        self.deck = []
        self.hand = []
        self.support = []
        self.front = []
        self.graveyard = []
        self.fatigue = 0

    def draw_card(self):
        if len(self.hand) >= MAX_HAND:
            return None
        if not self.deck:
            self.fatigue += 1
            self.hq -= self.fatigue
            return None
        card = self.deck.pop(0)
        self.hand.append(card)
        return card

    def start_turn(self):
        if self.max_command < MAX_COMMAND:
            self.max_command += 1
        self.command = self.max_command
        for unit in self.support + self.front:
            unit.has_attacked = False
            unit.just_deployed = False

    def get_owner(self):
        return "player" if self.is_player else "enemy"


class Game:
    def __init__(self):
        self.card_pool = create_card_pool()
        self.player = Player("玩家", True)
        self.enemy = Player("敌人", False)
        self.turn = "player"
        self.selected_card = None
        self.selected_unit = None
        self.message = "你的回合 - 点击卡牌部署"
        self.game_over = False
        self.winner = None
        self.enemy_ai_timer = 0
        self.setup_decks()
        self.setup_hands()
        self.player.start_turn()

    def setup_decks(self):
        main_cards = [c for c in self.card_pool if c.faction == "德国"]
        ally_cards = [c for c in self.card_pool if c.faction != "德国"]

        p_deck = [random.choice(main_cards) for _ in range(24)]
        p_deck += [random.choice(ally_cards) for _ in range(12)]
        p_deck += [random.choice(main_cards) for _ in range(4)]
        random.shuffle(p_deck)
        self.player.deck = p_deck

        e_deck = [random.choice(main_cards) for _ in range(24)]
        e_deck += [random.choice(ally_cards) for _ in range(12)]
        e_deck += [random.choice(main_cards) for _ in range(4)]
        random.shuffle(e_deck)
        self.enemy.deck = e_deck

    def setup_hands(self):
        for _ in range(4):
            self.player.draw_card()
        for _ in range(5):
            self.enemy.draw_card()

    def next_turn(self):
        if self.game_over:
            return
        if self.turn == "player":
            self.turn = "enemy"
            self.enemy.start_turn()
            self.enemy.draw_card()
            self.message = "敌人回合..."
            self.enemy_ai_timer = 0
        else:
            self.turn = "player"
            self.player.start_turn()
            self.player.draw_card()
            self.message = "你的回合 - 点击卡牌部署"

    def check_game_over(self):
        if self.player.hq <= 0:
            self.game_over = True
            self.winner = "敌人"
        elif self.enemy.hq <= 0:
            self.game_over = True
            self.winner = "玩家"

    def play_card(self, player, card, target_line=None):
        if card.cost > player.command:
            return False
        if card.card_type == "单位":
            if target_line == "support" and len(player.support) < MAX_LINE:
                unit = Unit(card, player.get_owner(), "support")
                player.support.append(unit)
                player.command -= card.cost
                player.hand.remove(card)
                return True
            elif target_line == "front" and len(player.front) < MAX_LINE:
                unit = Unit(card, player.get_owner(), "front")
                player.front.append(unit)
                player.command -= card.cost
                player.hand.remove(card)
                return True
            return False
        elif card.card_type == "指令":
            if self.resolve_instruction(player, card):
                player.command -= card.cost
                player.hand.remove(card)
                player.graveyard.append(card)
                return True
            return False
        return False

    def resolve_instruction(self, player, card):
        effect = card.effect
        opponent = self.enemy if player == self.player else self.player

        if effect == "抽牌":
            for _ in range(2):
                player.draw_card()
            return True
        elif effect == "伤害3":
            targets = opponent.front + opponent.support
            if targets:
                self.damage_unit(random.choice(targets), 3)
                return True
            return False
        elif effect == "伤害4":
            targets = opponent.front + opponent.support
            if targets:
                self.damage_unit(random.choice(targets), 4)
                return True
            return False
        elif effect == "总部伤害2":
            opponent.hq -= 2
            self.check_game_over()
            return True
        elif effect == "群伤1":
            for u in opponent.front[:] + opponent.support[:]:
                self.damage_unit(u, 1)
            return True
        elif effect == "治疗2":
            all_units = player.support + player.front
            wounded = [u for u in all_units if u.health < u.max_health]
            if wounded:
                target = random.choice(wounded)
                target.health = min(target.max_health, target.health + 2)
                return True
            return False
        return True

    def damage_unit(self, unit, dmg):
        died = unit.take_damage(dmg)
        if died:
            owner = self.player if unit.owner == "player" else self.enemy
            if unit in owner.support:
                owner.support.remove(unit)
            elif unit in owner.front:
                owner.front.remove(unit)
            owner.graveyard.append(unit.card)
        return died

    def attack(self, attacker, target):
        """返回 True 表示攻击已执行（无论成功失败），False 表示无效"""
        if target == "hq":
            if attacker.owner == "player":
                self.enemy.hq -= attacker.attack
            else:
                self.player.hq -= attacker.attack
            self.message = f"{attacker.name} 攻击总部 -{attacker.attack}"
            attacker.has_attacked = True
            self.check_game_over()
            return True

        # 目标合法性检查 - 如果不合法，标记已攻击并返回
        if not attacker.can_attack_target(target):
            self.message = f"{attacker.name} 无法攻击 {target.name}（飞行限制）"
            attacker.has_attacked = True  # 标记为已攻击，避免AI死循环
            return False

        died = self.damage_unit(target, attacker.attack)
        if died:
            self.message = f"{attacker.name} 击毁 {target.name}"
        else:
            self.message = f"{attacker.name} 攻击 {target.name}"

        if target.health > 0 and target.attack > 0:
            died2 = self.damage_unit(attacker, target.attack)
            if died2:
                self.message += f"，{attacker.name} 被反击摧毁"
                return True

        attacker.has_attacked = True
        self.check_game_over()
        return True

    def enemy_ai(self):
        """敌人AI：每40帧执行一步，确保不会卡住"""
        self.enemy_ai_timer += 1
        if self.enemy_ai_timer % 40 != 0:
            return

        enemy = self.enemy
        player = self.player
        action_taken = False

        # 1. 使用指令卡
        for card in enemy.hand[:]:
            if card.card_type == "指令" and card.cost <= enemy.command:
                if self.play_card(enemy, card):
                    return  # 一步完成，等下一帧

        # 2. 部署单位
        for card in enemy.hand[:]:
            if card.card_type == "单位" and card.cost <= enemy.command:
                if len(enemy.front) < MAX_LINE:
                    if self.play_card(enemy, card, "front"):
                        return
                elif len(enemy.support) < MAX_LINE:
                    if self.play_card(enemy, card, "support"):
                        return

        # 3. 攻击 - 遍历所有可用单位
        for unit in (enemy.front + enemy.support)[:]:
            if unit.has_attacked or not unit.can_attack():
                continue

            # 找合法的攻击目标
            valid_targets = []
            for target in player.front + player.support:
                if unit.can_attack_target(target):
                    valid_targets.append(target)

            if valid_targets:
                target = min(valid_targets, key=lambda u: u.health)
                self.attack(unit, target)
                return  # 攻击完等下一帧

            # 攻击玩家总部
            if unit.line == "front" or unit.card.effect == "远程":
                self.attack(unit, "hq")
                return

        # 4. 所有单位都不能攻击了 → 结束回合
        # 关键：把所有单位标记为已攻击，避免下次循环还尝试攻击
        for unit in enemy.front + enemy.support:
            unit.has_attacked = True

        self.next_turn()

    def force_end_enemy_turn(self):
        """强制结束敌人回合（防止卡死）"""
        for unit in self.enemy.front + self.enemy.support:
            unit.has_attacked = True
        self.next_turn()


# ==================== 绘制函数 ====================

def draw_card(surface, card, x, y, w, h, selected=False, playable=True):
    if selected:
        color = (255, 235, 130)
    elif not playable:
        color = (180, 180, 180)
    else:
        color = (240, 240, 240)

    pygame.draw.rect(surface, color, (x, y, w, h), border_radius=6)
    pygame.draw.rect(surface, BLACK, (x, y, w, h), 2, border_radius=6)

    pygame.draw.circle(surface, BLUE if playable else GRAY, (x + 15, y + 15), 12)
    cs = font_small.render(str(card.cost), True, WHITE)
    surface.blit(cs, (x + 15 - cs.get_width() // 2, y + 15 - cs.get_height() // 2))

    ns = font_small.render(card.name[:6], True, BLACK)
    surface.blit(ns, (x + 4, y + 32))

    ts = font_small.render(card.card_type, True, GRAY)
    surface.blit(ts, (x + 4, y + 50))

    if card.card_type == "单位":
        atk = font_med.render(str(card.attack), True, RED)
        surface.blit(atk, (x + 6, y + h - 25))
        hp = font_med.render(str(card.health), True, DARK_GREEN)
        surface.blit(hp, (x + w - 22, y + h - 25))

    fc = RED if card.faction == "德国" else (BLUE if card.faction == "意大利" else ORANGE)
    pygame.draw.circle(surface, fc, (x + w - 11, y + 11), 5)


def draw_unit(surface, unit, x, y, w, h, selected=False):
    if selected:
        color = (255, 235, 130)
    else:
        color = (225, 225, 225) if unit.owner == "player" else (225, 195, 195)

    pygame.draw.rect(surface, color, (x, y, w, h), border_radius=5)
    pygame.draw.rect(surface, BLACK, (x, y, w, h), 2, border_radius=5)

    ns = font_small.render(unit.name[:5], True, BLACK)
    surface.blit(ns, (x + 3, y + 3))

    atk = font_med.render(str(unit.attack), True, RED)
    surface.blit(atk, (x + 5, y + h - 22))
    hpc = DARK_GREEN if unit.health > unit.max_health // 2 else RED
    hp = font_med.render(str(unit.health), True, hpc)
    surface.blit(hp, (x + w - 20, y + h - 22))

    if unit.card.effect in ("飞行", "远程", "重甲"):
        es = font_small.render(unit.card.effect[:2], True, PURPLE)
        surface.blit(es, (x + w - 28, y + 3))

    if unit.has_attacked:
        pygame.draw.line(surface, GRAY, (x + 4, y + 4), (x + w - 4, y + h - 4), 2)


def draw_hq(surface, hq, x, y, w, h, owner):
    color = (80, 80, 180) if owner == "player" else (180, 80, 80)
    pygame.draw.rect(surface, color, (x, y, w, h), border_radius=8)
    pygame.draw.rect(surface, BLACK, (x, y, w, h), 2, border_radius=8)

    ratio = max(0, hq / HQ_DEFENSE)
    bw = int((w - 16) * ratio)
    bc = GREEN if ratio > 0.5 else (YELLOW if ratio > 0.25 else RED)
    pygame.draw.rect(surface, bc, (x + 8, y + h - 14, bw, 6))

    hs = font_med.render(f"总部 {hq}", True, WHITE)
    surface.blit(hs, (x + 8, y + 6))


def get_unit_pos(unit, owner, index):
    if owner == "player":
        y = PLAYER_SUPPORT_Y if unit.line == "support" else PLAYER_FRONT_Y
    else:
        y = ENEMY_SUPPORT_Y if unit.line == "support" else ENEMY_FRONT_Y
    return (LINE_START_X + index * LINE_SPACING, y)


def get_clicked_unit(game, mouse_pos):
    for unit in game.player.front:
        idx = game.player.front.index(unit)
        x, y = get_unit_pos(unit, "player", idx)
        if pygame.Rect(x, y, UNIT_W, UNIT_H).collidepoint(mouse_pos):
            return unit, "player"
    for unit in game.player.support:
        idx = game.player.support.index(unit)
        x, y = get_unit_pos(unit, "player", idx)
        if pygame.Rect(x, y, UNIT_W, UNIT_H).collidepoint(mouse_pos):
            return unit, "player"
    for unit in game.enemy.front:
        idx = game.enemy.front.index(unit)
        x, y = get_unit_pos(unit, "enemy", idx)
        if pygame.Rect(x, y, UNIT_W, UNIT_H).collidepoint(mouse_pos):
            return unit, "enemy"
    for unit in game.enemy.support:
        idx = game.enemy.support.index(unit)
        x, y = get_unit_pos(unit, "enemy", idx)
        if pygame.Rect(x, y, UNIT_W, UNIT_H).collidepoint(mouse_pos):
            return unit, "enemy"
    return None, None


def main():
    game = Game()
    running = True

    player_front_rect = pygame.Rect(0, PLAYER_FRONT_Y - 5, WIDTH, UNIT_H + 10)
    player_support_rect = pygame.Rect(0, PLAYER_SUPPORT_Y - 5, WIDTH, UNIT_H + 10)

    # 防止AI卡死的计时器
    enemy_stuck_timer = 0

    while running:
        mouse_pos = pygame.mouse.get_pos()
        clicked = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                clicked = True
            # 按空格强制结束敌人回合（调试用，可选）
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and game.turn == "enemy":
                    game.force_end_enemy_turn()
                    enemy_stuck_timer = 0

        screen.fill((45, 75, 45))

        pygame.draw.rect(screen, (85, 45, 45), (0, ENEMY_SUPPORT_Y - 5, WIDTH, UNIT_H + 10))
        pygame.draw.rect(screen, (65, 65, 85), (0, ENEMY_FRONT_Y - 5, WIDTH, UNIT_H + 10))
        pygame.draw.line(screen, BLACK, (0, 228), (WIDTH, 228), 2)
        pygame.draw.line(screen, YELLOW, (0, 229), (WIDTH, 229), 1)
        pygame.draw.rect(screen, (65, 65, 85), (0, PLAYER_FRONT_Y - 5, WIDTH, UNIT_H + 10))
        pygame.draw.rect(screen, (45, 85, 45), (0, PLAYER_SUPPORT_Y - 5, WIDTH, UNIT_H + 10))

        screen.blit(font_small.render("敌方支援", True, WHITE), (5, ENEMY_SUPPORT_Y + 25))
        screen.blit(font_small.render("敌方前线", True, WHITE), (5, ENEMY_FRONT_Y + 25))
        screen.blit(font_small.render("我方前线", True, WHITE), (5, PLAYER_FRONT_Y + 25))
        screen.blit(font_small.render("我方支援", True, WHITE), (5, PLAYER_SUPPORT_Y + 25))

        draw_hq(screen, game.enemy.hq, 15, 5, 110, 45, "enemy")
        draw_hq(screen, game.player.hq, 15, PLAYER_SUPPORT_Y + UNIT_H + 10, 110, 45, "player")

        screen.blit(font_small.render(f"指挥点 {game.player.command}/{game.player.max_command}", True, WHITE),
                    (140, PLAYER_SUPPORT_Y + UNIT_H + 15))
        screen.blit(font_small.render(f"牌库 {len(game.player.deck)}", True, WHITE),
                    (140, PLAYER_SUPPORT_Y + UNIT_H + 35))
        screen.blit(font_small.render(f"敌方指挥 {game.enemy.command}/{game.enemy.max_command}", True, WHITE),
                    (140, ENEMY_SUPPORT_Y + UNIT_H + 5))
        screen.blit(font_small.render(f"敌方牌库 {len(game.enemy.deck)}", True, WHITE),
                    (140, ENEMY_SUPPORT_Y + UNIT_H + 25))

        msg_surf = font_large.render(game.message, True, YELLOW)
        screen.blit(msg_surf, (WIDTH // 2 - msg_surf.get_width() // 2, 232))

        for i in range(len(game.enemy.hand)):
            x = WIDTH // 2 - len(game.enemy.hand) * 15 + i * 30
            y = 8
            pygame.draw.rect(screen, (100, 50, 50), (x, y, 25, 38), border_radius=3)
            pygame.draw.rect(screen, BLACK, (x, y, 25, 38), 2, border_radius=3)

        hand_count = len(game.player.hand)
        total_w = hand_count * (CARD_W + 6) - 6
        start_x = (WIDTH - total_w) // 2
        for i, card in enumerate(game.player.hand):
            x = start_x + i * (CARD_W + 6)
            selected = (game.selected_card == card)
            playable = card.cost <= game.player.command and game.turn == "player"
            draw_card(screen, card, x, HAND_Y, CARD_W, CARD_H, selected, playable)

        for i, unit in enumerate(game.player.support):
            x, y = get_unit_pos(unit, "player", i)
            draw_unit(screen, unit, x, y, UNIT_W, UNIT_H, game.selected_unit == unit)
        for i, unit in enumerate(game.player.front):
            x, y = get_unit_pos(unit, "player", i)
            draw_unit(screen, unit, x, y, UNIT_W, UNIT_H, game.selected_unit == unit)
        for i, unit in enumerate(game.enemy.support):
            x, y = get_unit_pos(unit, "enemy", i)
            draw_unit(screen, unit, x, y, UNIT_W, UNIT_H)
        for i, unit in enumerate(game.enemy.front):
            x, y = get_unit_pos(unit, "enemy", i)
            draw_unit(screen, unit, x, y, UNIT_W, UNIT_H)

        btn_color = GREEN if game.turn == "player" else GRAY
        pygame.draw.rect(screen, btn_color, END_BTN, border_radius=6)
        pygame.draw.rect(screen, BLACK, END_BTN, 2, border_radius=6)
        es = font_med.render("结束回合", True, WHITE)
        screen.blit(es, (END_BTN.x + END_BTN.w // 2 - es.get_width() // 2,
                         END_BTN.y + END_BTN.h // 2 - es.get_height() // 2))

        if game.game_over:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            screen.blit(overlay, (0, 0))
            ws = font_title.render(f"{game.winner} 胜利!", True, YELLOW)
            screen.blit(ws, (WIDTH // 2 - ws.get_width() // 2, HEIGHT // 2 - 60))
            pygame.draw.rect(screen, GREEN, RESTART_BTN, border_radius=8)
            rs = font_med.render("重新开始", True, WHITE)
            screen.blit(rs, (RESTART_BTN.x + RESTART_BTN.w // 2 - rs.get_width() // 2,
                             RESTART_BTN.y + RESTART_BTN.h // 2 - rs.get_height() // 2))

        # ===== AI 执行 =====
        if game.turn == "enemy" and not game.game_over:
            game.enemy_ai()
            # 卡死检测：如果敌人回合超过 6 秒（360帧）还没结束，强制结束
            enemy_stuck_timer += 1
            if enemy_stuck_timer > 360:
                game.message = "敌人回合超时，自动跳过"
                game.force_end_enemy_turn()
                enemy_stuck_timer = 0
        else:
            enemy_stuck_timer = 0

        if clicked and not game.game_over:
            if game.turn == "player":
                if END_BTN.collidepoint(mouse_pos):
                    game.next_turn()
                    continue

                hand_count = len(game.player.hand)
                total_w = hand_count * (CARD_W + 6) - 6
                start_x = (WIDTH - total_w) // 2
                for i, card in enumerate(game.player.hand):
                    x = start_x + i * (CARD_W + 6)
                    rect = pygame.Rect(x, HAND_Y, CARD_W, CARD_H)
                    if rect.collidepoint(mouse_pos):
                        if game.selected_card == card:
                            game.selected_card = None
                        else:
                            game.selected_card = card
                            game.selected_unit = None
                        break

                clicked_unit, owner = get_clicked_unit(game, mouse_pos)
                if owner == "player":
                    if game.selected_unit == clicked_unit:
                        game.selected_unit = None
                    else:
                        game.selected_unit = clicked_unit
                        game.selected_card = None

                if game.selected_card and game.selected_card.card_type == "单位":
                    if player_front_rect.collidepoint(mouse_pos):
                        if game.play_card(game.player, game.selected_card, "front"):
                            game.selected_card = None
                            game.message = "部署到前线"
                        else:
                            game.message = "无法部署（阵线满/费用不足）"
                    elif player_support_rect.collidepoint(mouse_pos):
                        if game.play_card(game.player, game.selected_card, "support"):
                            game.selected_card = None
                            game.message = "部署到支援阵线"
                        else:
                            game.message = "无法部署（阵线满/费用不足）"

                if game.selected_card and game.selected_card.card_type == "指令":
                    if game.play_card(game.player, game.selected_card):
                        game.selected_card = None
                        game.message = "指令生效"

                if game.selected_unit:
                    clicked_unit, owner = get_clicked_unit(game, mouse_pos)
                    if owner == "enemy" and clicked_unit:
                        if game.selected_unit.can_attack():
                            if game.selected_unit.can_attack_target(clicked_unit):
                                game.attack(game.selected_unit, clicked_unit)
                                game.selected_unit = None
                            else:
                                game.message = "该单位无法攻击飞行目标"
                                # 不重置选中，让玩家可以重新选目标
                        else:
                            game.message = "该单位无法攻击（需前线或远程）"

                    enemy_hq_rect = pygame.Rect(15, 5, 110, 45)
                    if enemy_hq_rect.collidepoint(mouse_pos):
                        if game.selected_unit.can_attack() and (game.selected_unit.line == "front" or game.selected_unit.card.effect == "远程"):
                            game.attack(game.selected_unit, "hq")
                            game.selected_unit = None
                        else:
                            game.message = "需要前线/远程单位才能攻击总部"

        if clicked and game.game_over:
            if RESTART_BTN.collidepoint(mouse_pos):
                game = Game()

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()