import pygame
import sys
import math
import random

# 初始化pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("保卫萝卜 - 塔防游戏")

# 颜色定义
BACKGROUND = (30, 60, 30)
PATH_COLOR = (180, 160, 100)
GRASS_COLOR = (70, 140, 70)
TOWER_BASE = (180, 180, 200)
TOWER_GUN = (80, 80, 120)
BULLET_COLOR = (255, 200, 0)
ENEMY_COLOR = (220, 80, 80)
HEALTH_BAR_GREEN = (80, 220, 80)
HEALTH_BAR_RED = (220, 80, 80)
UI_BG = (40, 40, 60)
UI_TEXT = (220, 220, 255)
BUTTON_COLOR = (70, 100, 150)
BUTTON_HOVER = (90, 130, 190)
RADISH_COLOR = (240, 120, 160)
RADISH_LEAVES = (100, 220, 100)
SLOW_COLOR = (100, 200, 255)
EXPLOSION_COLOR = (255, 150, 0)

# 游戏参数
FPS = 60
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)
big_font = pygame.font.SysFont(None, 48)
title_font = pygame.font.SysFont(None, 72)

# 路径定义
path = [
    (50, 350), (250, 350), (250, 200), (450, 200),
    (450, 450), (650, 450), (650, 300), (850, 300), (850, 500)
]

# 游戏状态
money = 150
health = 10
game_over = False
game_won = False
wave = 1
enemies_defeated = 0
enemies_per_wave = 15
spawn_timer = 0
spawn_delay = 40  # 帧数
selected_tower_type = None
tower_info_visible = False
info_tower = None

# 炮塔类型
TOWER_TYPES = {
    "basic": {"name": "基础炮塔", "cost": 60, "range": 150, "damage": 1, "cooldown": 30, "color": (180, 180, 200)},
    "sniper": {"name": "狙击炮塔", "cost": 120, "range": 300, "damage": 3, "cooldown": 60, "color": (100, 200, 100)},
    "machine": {"name": "机枪炮塔", "cost": 100, "range": 120, "damage": 0.5, "cooldown": 10, "color": (200, 100, 100)},
    "cannon": {"name": "加农炮塔", "cost": 150, "range": 130, "damage": 2, "cooldown": 40, "color": (200, 150, 50)},
    "freeze": {"name": "冰冻炮塔", "cost": 130, "range": 140, "damage": 0.2, "cooldown": 50, "color": (100, 180, 255)}
}

# 防御塔类


class Tower:
    def __init__(self, x, y, tower_type):
        self.x = x
        self.y = y
        self.type = tower_type
        self.stats = TOWER_TYPES[tower_type]
        self.range = self.stats["range"]
        self.damage = self.stats["damage"]
        self.cooldown = 0
        self.cooldown_max = self.stats["cooldown"]
        self.cost = self.stats["cost"]
        self.level = 1
        self.color = self.stats["color"]
        self.gun_color = (
            max(0, self.color[0]-50), max(0, self.color[1]-50), max(0, self.color[2]-50))

    def draw(self, surface):
        # 绘制塔基
        pygame.draw.circle(surface, self.color, (self.x, self.y), 20)
        # 绘制塔身
        pygame.draw.circle(surface, (max(0, self.color[0]-30), max(0, self.color[1]-30), max(0, self.color[2]-30)),
                           (self.x, self.y), 15)

        # 根据炮塔类型绘制不同样式
        if self.type == "basic":
            # 基础炮塔 - 单管
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y-5, 25, 10))
        elif self.type == "sniper":
            # 狙击炮塔 - 长管
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y-3, 35, 6))
            pygame.draw.circle(surface, (50, 50, 50), (self.x+40, self.y), 5)
        elif self.type == "machine":
            # 机枪炮塔 - 双管
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y-8, 25, 6))
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y+2, 25, 6))
        elif self.type == "cannon":
            # 加农炮塔 - 短粗管
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y-7, 30, 14))
        elif self.type == "freeze":
            # 冰冻炮塔 - 雪花标志
            pygame.draw.rect(surface, self.gun_color,
                             (self.x+5, self.y-5, 25, 10))
            pygame.draw.circle(surface, (200, 230, 255),
                               (self.x+15, self.y), 8, 2)

    def update(self, enemies):
        if self.cooldown > 0:
            self.cooldown -= 1
            return None

        # 寻找范围内的敌人
        for enemy in enemies:
            if not enemy.active or enemy.health <= 0:
                continue

            dist = math.sqrt((self.x - enemy.x)**2 + (self.y - enemy.y)**2)
            if dist <= self.range:
                self.cooldown = self.cooldown_max
                return Bullet(self.x, self.y, enemy, self.damage, self.type)
        return None

# 子弹类


class Bullet:
    def __init__(self, x, y, target, damage, bullet_type):
        self.x = x
        self.y = y
        self.target = target
        self.speed = 8
        self.damage = damage
        self.active = True
        self.type = bullet_type
        self.effect = None

        # 根据子弹类型设置特效
        if bullet_type == "freeze":
            self.color = (100, 200, 255)
            self.effect = "slow"
            self.effect_duration = 180  # 3秒
        elif bullet_type == "cannon":
            self.color = (255, 150, 0)
            self.size = 8
        else:
            self.color = BULLET_COLOR
            self.size = 5

    def update(self):
        if not self.active or not self.target.active:
            self.active = False
            return False

        # 计算到目标的向量
        dx = self.target.x - self.x
        dy = self.target.y - self.y
        dist = math.sqrt(dx**2 + dy**2)

        if dist < self.speed:
            self.target.health -= self.damage

            # 应用特效
            if self.effect == "slow":
                self.target.slow_duration = self.effect_duration
                self.target.speed *= 0.5

            self.active = False
            return True

        # 移动子弹
        self.x += dx / dist * self.speed
        self.y += dy / dist * self.speed
        return False

    def draw(self, surface):
        if self.type == "cannon":
            pygame.draw.circle(surface, self.color,
                               (int(self.x), int(self.y)), self.size)
            pygame.draw.circle(surface, (255, 200, 100),
                               (int(self.x), int(self.y)), self.size-3)
        else:
            pygame.draw.circle(surface, self.color,
                               (int(self.x), int(self.y)), self.size)
            pygame.draw.circle(surface, (255, 255, 200),
                               (int(self.x), int(self.y)), self.size-2)

# 敌人类


class Enemy:
    def __init__(self, path, wave):
        self.path = path
        self.path_index = 0
        self.x, self.y = path[0]

        # 根据波数增强敌人
        self.max_health = 5 + (wave - 1) * 2
        self.health = self.max_health
        self.speed = 1.0 + (wave - 1) * 0.1
        self.original_speed = self.speed
        self.reward = 10 + (wave - 1) * 2
        self.slow_duration = 0

        self.active = True
        self.type = random.choice(["normal", "fast", "tank"])

        # 根据敌人类型调整属性
        if self.type == "fast":
            self.speed *= 1.8
            self.health *= 0.7
            self.reward = int(self.reward * 1.3)
            self.color = (220, 120, 120)
        elif self.type == "tank":
            self.speed *= 0.7
            self.health *= 3.0
            self.reward = int(self.reward * 1.8)
            self.color = (180, 80, 80)
        else:
            self.color = ENEMY_COLOR

    def update(self):
        if not self.active:
            return False

        # 处理减速效果
        if self.slow_duration > 0:
            self.slow_duration -= 1
            if self.slow_duration == 0:
                self.speed = self.original_speed

        # 获取下一个路径点
        target_x, target_y = self.path[self.path_index]

        # 计算到目标的向量
        dx = target_x - self.x
        dy = target_y - self.y
        dist = math.sqrt(dx**2 + dy**2)

        # 移动到下一个点
        if dist < self.speed:
            self.path_index += 1
            if self.path_index >= len(self.path):
                self.active = False
                return True
            target_x, target_y = self.path[self.path_index]
            dx = target_x - self.x
            dy = target_y - self.y
            dist = math.sqrt(dx**2 + dy**2)

        # 移动敌人
        self.x += dx / dist * self.speed
        self.y += dy / dist * self.speed

        return False

    def draw(self, surface):
        # 绘制敌人
        pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 15)

        # 根据敌人类型绘制不同样式
        if self.type == "fast":
            pygame.draw.circle(surface, (max(0, self.color[0]-40), max(0, self.color[1]-40), max(0, self.color[2]-40)),
                               (int(self.x), int(self.y)), 10)
            # 绘制速度线
            pygame.draw.line(surface, (255, 255, 200),
                             (self.x, self.y-15), (self.x, self.y-25), 2)
        elif self.type == "tank":
            pygame.draw.rect(surface, (max(0, self.color[0]-50), max(0, self.color[1]-50), max(0, self.color[2]-50)),
                             (self.x-12, self.y-5, 24, 10))
            pygame.draw.rect(surface, (max(0, self.color[0]-50), max(0, self.color[1]-50), max(0, self.color[2]-50)),
                             (self.x-5, self.y-12, 10, 24))
        else:
            pygame.draw.circle(surface, (max(0, self.color[0]-40), max(0, self.color[1]-40), max(0, self.color[2]-40)),
                               (int(self.x), int(self.y)), 10)

        # 绘制血条
        bar_width = 40
        bar_height = 5
        health_ratio = self.health / self.max_health
        pygame.draw.rect(surface, HEALTH_BAR_RED,
                         (self.x - bar_width//2, self.y - 30, bar_width, bar_height))
        pygame.draw.rect(surface, HEALTH_BAR_GREEN,
                         (self.x - bar_width//2, self.y - 30, bar_width * health_ratio, bar_height))

        # 绘制减速效果
        if self.slow_duration > 0:
            pygame.draw.circle(surface, SLOW_COLOR,
                               (int(self.x), int(self.y)), 18, 2)

# 爆炸效果类


class Explosion:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 5
        self.max_radius = 30
        self.growth_rate = 1.5
        self.active = True

    def update(self):
        self.radius += self.growth_rate
        if self.radius > self.max_radius:
            self.active = False

    def draw(self, surface):
        alpha = 255 * (1 - self.radius / self.max_radius)
        s = pygame.Surface(
            (self.max_radius*2, self.max_radius*2), pygame.SRCALPHA)
        pygame.draw.circle(s, (*EXPLOSION_COLOR, int(alpha)),
                           (self.max_radius, self.max_radius), int(self.radius), 3)
        pygame.draw.circle(s, (255, 255, 200, int(alpha/2)),
                           (self.max_radius, self.max_radius), int(self.radius/2), 2)
        surface.blit(s, (int(self.x - self.max_radius),
                     int(self.y - self.max_radius)))


# 游戏对象
towers = []
bullets = []
enemies = []
explosions = []
selected_tower_pos = None

# 绘制路径


def draw_path():
    for i in range(len(path) - 1):
        pygame.draw.line(screen, PATH_COLOR, path[i], path[i+1], 40)

    # 绘制起点和终点
    pygame.draw.circle(screen, (120, 90, 60), path[0], 20)
    pygame.draw.circle(screen, (140, 110, 80), path[0], 15)
    pygame.draw.circle(screen, (160, 130, 100), path[0], 10)

# 绘制草地


def draw_grass():
    for i in range(0, WIDTH, 40):
        for j in range(0, HEIGHT, 40):
            if random.random() > 0.3:
                pygame.draw.line(screen, GRASS_COLOR, (i, j), (i, j-15), 2)

# 绘制萝卜


def draw_radish():
    x, y = path[-1]

    # 绘制叶子
    pygame.draw.ellipse(screen, RADISH_LEAVES, (x-25, y-70, 50, 40))
    pygame.draw.ellipse(screen, (max(0, RADISH_LEAVES[0]-20), max(0, RADISH_LEAVES[1]-20), max(0, RADISH_LEAVES[2]-20)),
                        (x-30, y-60, 30, 30))
    pygame.draw.ellipse(screen, (max(0, RADISH_LEAVES[0]-20), max(0, RADISH_LEAVES[1]-20), max(0, RADISH_LEAVES[2]-20)),
                        (x, y-60, 30, 30))

    # 绘制萝卜身体
    pygame.draw.circle(screen, RADISH_COLOR, (x, y), 30)
    pygame.draw.ellipse(screen, (max(0, RADISH_COLOR[0]-40), max(0, RADISH_COLOR[1]-40), max(0, RADISH_COLOR[2]-40)),
                        (x-20, y-15, 40, 30))

    # 绘制萝卜眼睛
    pygame.draw.circle(screen, (255, 255, 255), (x-10, y-5), 8)
    pygame.draw.circle(screen, (255, 255, 255), (x+10, y-5), 8)
    pygame.draw.circle(screen, (0, 0, 0), (x-10, y-5), 4)
    pygame.draw.circle(screen, (0, 0, 0), (x+10, y-5), 4)

    # 绘制萝卜嘴巴
    pygame.draw.arc(screen, (200, 80, 120), (x-10, y, 20, 15), 0, math.pi, 3)

    # 绘制生命值
    pygame.draw.rect(screen, HEALTH_BAR_RED, (x-30, y-100, 60, 10))
    pygame.draw.rect(screen, HEALTH_BAR_GREEN,
                     (x-30, y-100, 60 * (health/10), 10))

# 绘制UI


def draw_ui():
    # 绘制顶部UI
    pygame.draw.rect(screen, UI_BG, (0, 0, WIDTH, 50))

    # 显示金币
    money_text = font.render(f"金币: {money}", True, UI_TEXT)
    screen.blit(money_text, (20, 15))

    # 显示生命值
    health_text = font.render(f"生命值: {health}", True, UI_TEXT)
    screen.blit(health_text, (150, 15))

    # 显示波数
    wave_text = font.render(f"波数: {wave}/10", True, UI_TEXT)
    screen.blit(wave_text, (280, 15))

    # 显示击败敌人数
    defeated_text = font.render(
        f"击败敌人: {enemies_defeated}/{wave * enemies_per_wave}", True, UI_TEXT)
    screen.blit(defeated_text, (400, 15))

    # 绘制炮塔选择区域
    pygame.draw.rect(screen, (50, 50, 70), (0, HEIGHT-150, WIDTH, 150))
    pygame.draw.line(screen, (80, 80, 100), (0, HEIGHT-150),
                     (WIDTH, HEIGHT-150), 3)

    # 标题
    towers_text = font.render("选择炮塔类型:", True, UI_TEXT)
    screen.blit(towers_text, (20, HEIGHT-140))

    # 绘制炮塔按钮
    button_width = 150
    button_height = 100
    spacing = 20
    start_x = 20

    for i, (tower_id, tower_data) in enumerate(TOWER_TYPES.items()):
        x = start_x + i * (button_width + spacing)
        y = HEIGHT - 130
        button_rect = pygame.Rect(x, y, button_width, button_height)

        # 按钮颜色
        if selected_tower_type == tower_id:
            color = (max(0, tower_data["color"][0]//2), max(
                0, tower_data["color"][1]//2), max(0, tower_data["color"][2]//2))
        elif button_rect.collidepoint(pygame.mouse.get_pos()):
            color = (max(0, tower_data["color"][0]//1.2), max(
                0, tower_data["color"][1]//1.2), max(0, tower_data["color"][2]//1.2))
        else:
            color = tower_data["color"]

        pygame.draw.rect(screen, color, button_rect)
        pygame.draw.rect(screen, (max(
            0, color[0]//1.5), max(0, color[1]//1.5), max(0, color[2]//1.5)), button_rect, 3)

        # 炮塔名称
        name_text = font.render(tower_data["name"], True, (255, 255, 255))
        screen.blit(name_text, (x + button_width//2 -
                    name_text.get_width()//2, y + 10))

        # 炮塔价格
        cost_text = font.render(
            f"价格: {tower_data['cost']}", True, (255, 255, 200))
        screen.blit(cost_text, (x + button_width//2 -
                    cost_text.get_width()//2, y + 40))

        # 炮塔图标 - 确保颜色值不小于0
        icon_color = (
            max(0, color[0] - 50),
            max(0, color[1] - 50),
            max(0, color[2] - 50)
        )
        pygame.draw.circle(screen, icon_color,
                           (x + button_width//2, y + 75), 15)

        # 根据炮塔类型绘制特殊图标
        if tower_id == "sniper":
            pygame.draw.rect(screen, (50, 50, 50),
                             (x + button_width//2 + 5, y + 75 - 3, 20, 6))
        elif tower_id == "machine":
            pygame.draw.rect(screen, (50, 50, 50),
                             (x + button_width//2 + 5, y + 75 - 8, 20, 6))
            pygame.draw.rect(screen, (50, 50, 50),
                             (x + button_width//2 + 5, y + 75 + 2, 20, 6))
        elif tower_id == "cannon":
            pygame.draw.rect(screen, (50, 50, 50),
                             (x + button_width//2 + 5, y + 75 - 7, 25, 14))
        elif tower_id == "freeze":
            pygame.draw.circle(screen, (200, 230, 255),
                               (x + button_width//2, y + 75), 10, 2)

# 绘制炮塔信息


def draw_tower_info():
    if not tower_info_visible or not info_tower:
        return

    # 创建半透明背景
    info_surface = pygame.Surface((300, 200), pygame.SRCALPHA)
    info_surface.fill((30, 30, 50, 220))

    # 绘制边框
    pygame.draw.rect(info_surface, (100, 100, 150), (0, 0, 300, 200), 3)

    # 标题
    title = font.render(
        f"{TOWER_TYPES[info_tower.type]['name']} 信息", True, (255, 255, 200))
    info_surface.blit(title, (150 - title.get_width()//2, 15))

    # 属性
    damage_text = font.render(f"伤害: {info_tower.damage}", True, UI_TEXT)
    info_surface.blit(damage_text, (30, 50))

    range_text = font.render(f"范围: {info_tower.range}", True, UI_TEXT)
    info_surface.blit(range_text, (30, 80))

    speed_text = font.render(
        f"攻速: {60/(info_tower.cooldown_max/FPS):.1f}次/秒", True, UI_TEXT)
    info_surface.blit(speed_text, (30, 110))

    # 特殊效果
    if info_tower.type == "freeze":
        effect_text = font.render("效果: 减速敌人50%", True, SLOW_COLOR)
        info_surface.blit(effect_text, (30, 140))

    # 关闭按钮
    pygame.draw.rect(info_surface, (180, 80, 80), (250, 10, 40, 20))
    close_text = font.render("X", True, (255, 255, 255))
    info_surface.blit(close_text, (265, 12))

    # 绘制到屏幕
    screen.blit(info_surface, (WIDTH//2 - 150, HEIGHT//2 - 100))

# 游戏结束画面


def draw_game_over():
    overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
    overlay.fill((0, 0, 0, 180))
    screen.blit(overlay, (0, 0))

    if game_won:
        text = big_font.render("胜利! 萝卜安全了!", True, (100, 255, 100))
    else:
        text = big_font.render("游戏结束! 萝卜被吃掉了!", True, (255, 100, 100))

    text_rect = text.get_rect(center=(WIDTH//2, HEIGHT//2 - 50))
    screen.blit(text, text_rect)

    restart_text = font.render("按R键重新开始", True, (200, 200, 255))
    restart_rect = restart_text.get_rect(center=(WIDTH//2, HEIGHT//2 + 20))
    screen.blit(restart_text, restart_rect)

    # 显示分数
    score_text = font.render(
        f"最终分数: {enemies_defeated * 10 + money}", True, (255, 255, 150))
    score_rect = score_text.get_rect(center=(WIDTH//2, HEIGHT//2 + 60))
    screen.blit(score_text, score_rect)

# 重置游戏


def reset_game():
    global money, health, game_over, game_won, wave, enemies_defeated, towers, bullets, enemies, explosions, selected_tower_type
    money = 150
    health = 10
    game_over = False
    game_won = False
    wave = 1
    enemies_defeated = 0
    towers = []
    bullets = []
    enemies = []
    explosions = []
    selected_tower_type = None

# 绘制开始界面


def draw_start_screen():
    screen.fill((20, 40, 20))

    # 标题
    title_text = title_font.render("保卫萝卜", True, (100, 220, 100))
    screen.blit(title_text, (WIDTH//2 - title_text.get_width()//2, 150))

    # 绘制萝卜
    pygame.draw.circle(screen, RADISH_COLOR, (WIDTH//2, 300), 60)
    pygame.draw.ellipse(screen, (max(0, RADISH_COLOR[0]-40), max(0, RADISH_COLOR[1]-40), max(0, RADISH_COLOR[2]-40)),
                        (WIDTH//2-40, 300-15, 80, 50))
    pygame.draw.circle(screen, (255, 255, 255), (WIDTH//2-20, 300-5), 15)
    pygame.draw.circle(screen, (255, 255, 255), (WIDTH//2+20, 300-5), 15)
    pygame.draw.circle(screen, (0, 0, 0), (WIDTH//2-20, 300-5), 7)
    pygame.draw.circle(screen, (0, 0, 0), (WIDTH//2+20, 300-5), 7)
    pygame.draw.arc(screen, (200, 80, 120),
                    (WIDTH//2-20, 300+10, 40, 30), 0, math.pi, 5)

    # 绘制叶子
    pygame.draw.ellipse(screen, RADISH_LEAVES, (WIDTH//2-40, 300-100, 80, 60))
    pygame.draw.ellipse(screen, (max(0, RADISH_LEAVES[0]-20), max(0, RADISH_LEAVES[1]-20), max(0, RADISH_LEAVES[2]-20)),
                        (WIDTH//2-60, 300-90, 40, 40))
    pygame.draw.ellipse(screen, (max(0, RADISH_LEAVES[0]-20), max(0, RADISH_LEAVES[1]-20), max(0, RADISH_LEAVES[2]-20)),
                        (WIDTH//2+20, 300-90, 40, 40))

    # 开始按钮
    pygame.draw.rect(screen, BUTTON_COLOR, (WIDTH//2-100, 400, 200, 60))
    if pygame.Rect(WIDTH//2-100, 400, 200, 60).collidepoint(pygame.mouse.get_pos()):
        pygame.draw.rect(screen, BUTTON_HOVER, (WIDTH//2-100, 400, 200, 60), 3)
    else:
        pygame.draw.rect(screen, BUTTON_HOVER, (WIDTH//2-100, 400, 200, 60), 2)

    start_text = big_font.render("开始游戏", True, (255, 255, 255))
    screen.blit(start_text, (WIDTH//2 - start_text.get_width()//2, 415))

    # 游戏说明
    instructions = [
        "游戏目标: 保护萝卜不被敌人吃掉",
        "操作方法:",
        "1. 从底部选择炮塔类型",
        "2. 在地图上点击放置炮塔",
        "3. 合理布置炮塔抵御敌人进攻",
        "4. 击败所有敌人波次获得胜利"
    ]

    for i, text in enumerate(instructions):
        text_surface = font.render(text, True, (200, 220, 200))
        screen.blit(text_surface, (WIDTH//2 -
                    text_surface.get_width()//2, 480 + i*30))


# 游戏主循环
running = True
start_screen = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            if start_screen:
                # 检查是否点击了开始按钮
                if WIDTH//2-100 <= event.pos[0] <= WIDTH//2+100 and 400 <= event.pos[1] <= 460:
                    start_screen = False
                continue

            if game_over:
                continue

            x, y = event.pos

            # 检查是否点击了炮塔信息关闭按钮
            if tower_info_visible:
                if WIDTH//2+100 <= x <= WIDTH//2+140 and HEIGHT//2-100 <= y <= HEIGHT//2-80:
                    tower_info_visible = False
                continue

            # 检查是否点击了炮塔选择按钮
            if HEIGHT-150 <= y <= HEIGHT:
                button_width = 150
                spacing = 20
                start_x = 20

                for i, tower_id in enumerate(TOWER_TYPES.keys()):
                    btn_x = start_x + i * (button_width + spacing)
                    btn_y = HEIGHT - 130
                    if btn_x <= x <= btn_x + button_width and btn_y <= y <= btn_y + 100:
                        if money >= TOWER_TYPES[tower_id]["cost"]:
                            selected_tower_type = tower_id
                        break

            # 检查是否在地图上放置了防御塔
            elif selected_tower_type and y < HEIGHT-160:
                # 确保不在路径上放置防御塔
                on_path = False
                for i in range(len(path) - 1):
                    p1 = path[i]
                    p2 = path[i+1]
                    dist = abs((p2[0]-p1[0])*(p1[1]-y) - (p1[0]-x)*(p2[1]-p1[1])
                               ) / math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)
                    if dist < 30:
                        on_path = True
                        break

                # 确保不在萝卜附近放置
                radish_dist = math.sqrt(
                    (x - path[-1][0])**2 + (y - path[-1][1])**2)
                if radish_dist < 50:
                    on_path = True

                # 确保不在其他塔附近放置
                too_close = False
                for tower in towers:
                    if math.sqrt((x - tower.x)**2 + (y - tower.y)**2) < 50:
                        too_close = True
                        break

                if not on_path and not too_close and money >= TOWER_TYPES[selected_tower_type]["cost"]:
                    towers.append(Tower(x, y, selected_tower_type))
                    money -= TOWER_TYPES[selected_tower_type]["cost"]
                    selected_tower_type = None

                # 点击现有炮塔查看信息
                for tower in towers:
                    if math.sqrt((x - tower.x)**2 + (y - tower.y)**2) < 25:
                        tower_info_visible = True
                        info_tower = tower
                        break

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r and game_over:
                reset_game()
            if event.key == pygame.K_ESCAPE:
                selected_tower_type = None

    if start_screen:
        draw_start_screen()
        pygame.display.flip()
        clock.tick(FPS)
        continue

    if not game_over:
        # 生成敌人
        spawn_timer += 1
        if spawn_timer >= spawn_delay and len(enemies) < 8 and enemies_defeated < wave * enemies_per_wave:
            enemies.append(Enemy(path, wave))
            spawn_timer = 0

        # 更新敌人
        for enemy in enemies[:]:
            reached_end = enemy.update()
            if reached_end:
                health -= 1
                enemies.remove(enemy)
                if health <= 0:
                    game_over = True
            elif enemy.health <= 0:
                money += enemy.reward
                enemies_defeated += 1
                enemies.remove(enemy)
                explosions.append(Explosion(enemy.x, enemy.y))

        # 更新防御塔
        for tower in towers:
            bullet = tower.update(enemies)
            if bullet:
                bullets.append(bullet)

        # 更新子弹
        for bullet in bullets[:]:
            hit = bullet.update()
            if hit or not bullet.active:
                if bullet in bullets:
                    bullets.remove(bullet)

        # 更新爆炸效果
        for explosion in explosions[:]:
            explosion.update()
            if not explosion.active:
                explosions.remove(explosion)

        # 检查是否进入下一波
        if enemies_defeated >= wave * enemies_per_wave and len(enemies) == 0:
            wave += 1
            money += 100  # 波次奖励
            if wave > 10:
                game_over = True
                game_won = True

    # 绘制游戏
    screen.fill(BACKGROUND)
    draw_grass()
    draw_path()
    draw_radish()

    # 绘制防御塔范围（如果选择了位置）
    if selected_tower_type:
        pygame.draw.circle(screen, (100, 100, 200, 100), pygame.mouse.get_pos(
        ), TOWER_TYPES[selected_tower_type]["range"], 2)
        pygame.draw.circle(
            screen, TOWER_TYPES[selected_tower_type]["color"], pygame.mouse.get_pos(), 20)

    # 绘制防御塔
    for tower in towers:
        tower.draw(screen)
        # 绘制范围（当鼠标悬停时）
        if math.sqrt((pygame.mouse.get_pos()[0] - tower.x)**2 + (pygame.mouse.get_pos()[1] - tower.y)**2) < 25:
            pygame.draw.circle(screen, (100, 100, 200, 100),
                               (tower.x, tower.y), tower.range, 1)

    # 绘制子弹
    for bullet in bullets:
        bullet.draw(screen)

    # 绘制敌人
    for enemy in enemies:
        enemy.draw(screen)

    # 绘制爆炸效果
    for explosion in explosions:
        explosion.draw(screen)

    # 绘制UI
    draw_ui()

    # 绘制炮塔信息
    draw_tower_info()

    # 绘制游戏结束画面
    if game_over:
        draw_game_over()

    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()
sys.exit()
