import tkinter as tk
import random
import time
import json
import os
from enum import Enum
from typing import List, Tuple, Dict
from PIL import Image, ImageTk
import math

class PlantType(Enum):
    """植物类型"""
    SUNFLOWER = "向日葵"
    PEASHOOTER = "豌豆射手"
    WALLNUT = "坚果墙"
    SNOW_PEA = "寒冰射手"
    CHERRY_BOMB = "樱桃炸弹"
    POTATO_MINE = "土豆地雷"
    REPEATER = "双发射手"
    THREEPEATER = "三线射手"
    GATLING_PEA = "机枪射手"
    SQUASH =  "倭瓜"

class ZombieType(Enum):
    """僵尸类型"""
    BASIC = "普通僵尸"
    CONEHEAD = "路障僵尸"
    BUCKETHEAD = "铁桶僵尸"
    NEWSPAPER = "报纸僵尸"
    FOOTBALL = "橄榄球僵尸"
    DANCER = "舞王僵尸"
    POLEVAULT = "撑杆僵尸"
    DOLPHIN = "海豚僵尸"
    GARGANTUAR = "巨人僵尸"

class CellType(Enum):
    """单元格类型"""
    EMPTY = 0
    PLANT = 1
    ZOMBIE = 2
    PROJECTILE = 3
    SUN = 4

class Game:
    def __init__(self, root):
        self.root = root
        self.root.title("植物大战僵尸 - Plants vs Zombies")
        self.root.configure(bg="#8B4513")
        
        # 游戏设置
        self.grid_rows = 5
        self.grid_cols = 9
        self.cell_size = 80
        self.lawn_start_x = 150
        self.lawn_start_y = 50
        
        # 计算窗口大小
        self.width = self.lawn_start_x + self.grid_cols * self.cell_size + 200
        self.height = self.lawn_start_y + self.grid_rows * self.cell_size + 100
        
        # 屏幕居中
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x = (screen_width - self.width) // 2
        y = (screen_height - self.height) // 2
        self.root.geometry(f"{self.width}x{self.height}+{x}+{y}")
        self.root.resizable(False, False)
        
        # 游戏状态
        self.game_running = False
        self.game_paused = False
        self.level = 1
        self.sunlight = 50
        self.max_sunlight = 9999
        self.wave = 1
        self.max_wave = 5
        self.zombies_killed = 0
        self.zombies_in_wave = 0
        self.zombies_spawned = 0
        
        # 加载游戏数据
        self.load_game_data()
        
        # 草坪网格
        self.grid = [[CellType.EMPTY for _ in range(self.grid_cols)] for _ in range(self.grid_rows)]
        
        # 植物管理
        self.plants = []  # 每个植物是一个字典
        self.plant_cooldowns = {}  # 植物冷却时间
        self.plant_selected = None
        self.plant_preview = None
        
        # 僵尸管理
        self.zombies = []
        self.zombie_spawn_timer = 0
        self.zombie_spawn_interval = 5.0  # 秒
        
        # 子弹管理
        self.projectiles = []
        
        # 阳光管理
        self.sunlights = []
        self.sun_spawn_timer = 0
        self.sun_spawn_interval = 10.0
        
        # 游戏计时
        self.last_update = time.time()
        self.game_time = 0
        
        # 创建界面
        self.create_ui()
        
        # 绑定事件
        self.root.bind("<Button-1>", self.on_click)
        self.root.bind("<Motion>", self.on_mouse_move)
        
        # 显示主菜单
        self.show_main_menu()
    
    def create_ui(self):
        """创建用户界面"""
        # 主画布
        self.canvas = tk.Canvas(
            self.root,
            width=self.width,
            height=self.height,
            bg="#8B4513",
            highlightthickness=0
        )
        self.canvas.pack()
        
        # 绘制背景
        self.draw_background()
        
        # 创建植物卡片区域
        self.create_plant_cards()
        
        # 创建状态栏
        self.create_status_bar()
    
    def draw_background(self):
        """绘制游戏背景"""
        # 草坪背景
        self.canvas.create_rectangle(
            self.lawn_start_x, self.lawn_start_y,
            self.lawn_start_x + self.grid_cols * self.cell_size,
            self.lawn_start_y + self.grid_rows * self.cell_size,
            fill="#7CFC00",  # 草地绿
            outline="#556B2F",
            width=2
        )
        
        # 绘制网格线
        for row in range(self.grid_rows + 1):
            y = self.lawn_start_y + row * self.cell_size
            self.canvas.create_line(
                self.lawn_start_x, y,
                self.lawn_start_x + self.grid_cols * self.cell_size, y,
                fill="#556B2F", width=1
            )
        
        for col in range(self.grid_cols + 1):
            x = self.lawn_start_x + col * self.cell_size
            self.canvas.create_line(
                x, self.lawn_start_y,
                x, self.lawn_start_y + self.grid_rows * self.cell_size,
                fill="#556B2F", width=1
            )
        
        # 房屋背景
        self.canvas.create_rectangle(
            self.lawn_start_x - 100, self.lawn_start_y,
            self.lawn_start_x, self.lawn_start_y + self.grid_rows * self.cell_size,
            fill="#8B4513",  # 棕色房屋
            outline="#654321",
            width=3
        )
        
        # 窗户
        window_size = 20
        for i in range(self.grid_rows):
            y = self.lawn_start_y + i * self.cell_size + self.cell_size // 2
            self.canvas.create_rectangle(
                self.lawn_start_x - 60, y - window_size,
                self.lawn_start_x - 40, y + window_size,
                fill="#87CEEB",  # 天蓝色窗户
                outline="#4682B4",
                width=2
            )
    
    def create_plant_cards(self):
        """创建植物卡片"""
        self.plant_cards = []
        
        plant_types = [
            (PlantType.SUNFLOWER, 50, "☀️", "#FFD700"),
            (PlantType.PEASHOOTER, 100, "🌱", "#4CAF50"),
            (PlantType.WALLNUT, 50, "🥜", "#8B4513"),
            (PlantType.SNOW_PEA, 175, "❄️", "#87CEEB"),
            (PlantType.REPEATER, 200, "🌿", "#2E8B57"),
            (PlantType.POTATO_MINE, 25, "🥔", "#D2691E"),
            (PlantType.SQUASH, 50, "🥒", "#228B22"),
        ]
        
        card_width = 80
        card_height = 100
        start_x = 20
        start_y = 50
        
        for i, (plant_type, cost, emoji, color) in enumerate(plant_types):
            x = start_x
            y = start_y + i * (card_height + 10)
            
            # 卡片背景
            card_bg = self.canvas.create_rectangle(
                x, y,
                x + card_width, y + card_height,
                fill=color,
                outline="#654321",
                width=2,
                tags=f"plant_card_{plant_type.value}"
            )
            
            # 植物图标
            emoji_text = self.canvas.create_text(
                x + card_width // 2,
                y + 30,
                text=emoji,
                font=("Arial", 24),
                tags=f"plant_card_{plant_type.value}"
            )
            
            # 植物名称
            name_text = self.canvas.create_text(
                x + card_width // 2,
                y + 60,
                text=plant_type.value,
                font=("Microsoft YaHei", 10),
                width=card_width - 10,
                tags=f"plant_card_{plant_type.value}"
            )
            
            # 阳光消耗
            cost_text = self.canvas.create_text(
                x + card_width // 2,
                y + 85,
                text=f"☀️{cost}",
                font=("Arial", 12, "bold"),
                fill="#FFD700",
                tags=f"plant_card_{plant_type.value}"
            )
            
            self.plant_cards.append({
                "type": plant_type,
                "cost": cost,
                "emoji": emoji,
                "color": color,
                "x": x,
                "y": y,
                "width": card_width,
                "height": card_height,
                "id": plant_type.value
            })
    
    def create_status_bar(self):
        """创建状态栏"""
        status_height = 40
        
        # 状态栏背景
        self.canvas.create_rectangle(
            0, 0,
            self.width, status_height,
            fill="#556B2F",
            outline="#654321",
            width=2
        )
        
        # 阳光显示
        self.sunlight_label = tk.Label(
            self.root,
            text=f"☀️ {self.sunlight}",
            font=("Arial", 16, "bold"),
            fg="#FFD700",
            bg="#556B2F"
        )
        self.sunlight_window = self.canvas.create_window(100, 20, window=self.sunlight_label)
        
        # 波次显示
        self.wave_label = tk.Label(
            self.root,
            text=f"🌊 波次: {self.wave}/{self.max_wave}",
            font=("Microsoft YaHei", 12, "bold"),
            fg="white",
            bg="#556B2F"
        )
        self.wave_window = self.canvas.create_window(250, 20, window=self.wave_label)
        
        # 等级显示
        self.level_label = tk.Label(
            self.root,
            text=f"⭐ 等级: {self.level}",
            font=("Microsoft YaHei", 12, "bold"),
            fg="#FFD700",
            bg="#556B2F"
        )
        self.level_window = self.canvas.create_window(400, 20, window=self.level_label)
        
        # 僵尸击杀
        self.kills_label = tk.Label(
            self.root,
            text=f"💀 击杀: {self.zombies_killed}",
            font=("Microsoft YaHei", 12, "bold"),
            fg="white",
            bg="#556B2F"
        )
        self.kills_window = self.canvas.create_window(550, 20, window=self.kills_label)
        
        # 按钮框架
        button_frame = tk.Frame(self.root, bg="#556B2F")
        self.button_window = self.canvas.create_window(self.width - 150, 20, window=button_frame)
        
        self.start_btn = tk.Button(
            button_frame,
            text="开始游戏",
            command=self.start_game,
            font=("Microsoft YaHei", 10),
            bg="#4CAF50",
            fg="white",
            width=10
        )
        self.start_btn.pack(side=tk.LEFT, padx=5)
        
        self.pause_btn = tk.Button(
            button_frame,
            text="暂停",
            command=self.pause_game,
            font=("Microsoft YaHei", 10),
            bg="#FF9800",
            fg="white",
            width=10,
            state=tk.DISABLED
        )
        self.pause_btn.pack(side=tk.LEFT, padx=5)
    
    def show_main_menu(self):
        """显示主菜单"""
        self.clear_game_objects()
        
        # 覆盖层
        overlay = self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black", stipple="gray50"
        )
        
        # 标题
        title = self.canvas.create_text(
            self.width // 2,
            self.height // 4,
            text="植物大战僵尸",
            font=("Microsoft YaHei", 60, "bold"),
            fill="#4CAF50"
        )
        
        subtitle = self.canvas.create_text(
            self.width // 2,
            self.height // 4 + 70,
            text="Plants vs Zombies",
            font=("Arial", 30, "italic"),
            fill="#FFD700"
        )
        
        # 按钮
        menu_y = self.height // 2
        
        start_btn = tk.Button(
            self.root,
            text="开始游戏",
            command=self.start_game,
            font=("Microsoft YaHei", 20),
            bg="#4CAF50",
            fg="white",
            width=20
        )
        self.canvas.create_window(self.width // 2, menu_y, window=start_btn)
        
        level_btn = tk.Button(
            self.root,
            text=f"选择关卡 (当前: {self.level})",
            command=self.show_level_select,
            font=("Microsoft YaHei", 20),
            bg="#2196F3",
            fg="white",
            width=20
        )
        self.canvas.create_window(self.width // 2, menu_y + 60, window=level_btn)
        
        quit_btn = tk.Button(
            self.root,
            text="退出游戏",
            command=self.root.quit,
            font=("Microsoft YaHei", 20),
            bg="#F44336",
            fg="white",
            width=20
        )
        self.canvas.create_window(self.width // 2, menu_y + 120, window=quit_btn)
        
        # 最高分
        high_score = self.canvas.create_text(
            self.width // 2,
            self.height - 50,
            text=f"最高关卡: {self.load_high_level()}",
            font=("Arial", 20),
            fill="#FF9800"
        )
    
    def show_level_select(self):
        """显示关卡选择"""
        self.clear_canvas()
        
        # 背景
        self.draw_background()
        
        # 标题
        self.canvas.create_text(
            self.width // 2,
            50,
            text="选择关卡",
            font=("Microsoft YaHei", 40, "bold"),
            fill="#4CAF50"
        )
        
        # 关卡按钮
        buttons_per_row = 5
        button_size = 60
        padding = 20
        start_x = (self.width - (buttons_per_row * (button_size + padding))) // 2
        start_y = 150
        
        for i in range(1, 21):  # 20个关卡
            row = (i - 1) // buttons_per_row
            col = (i - 1) % buttons_per_row
            
            x = start_x + col * (button_size + padding)
            y = start_y + row * (button_size + padding)
            
            # 解锁状态
            unlocked = i <= self.load_high_level() + 1
            color = "#4CAF50" if unlocked else "#757575"
            state = tk.NORMAL if unlocked else tk.DISABLED
            
            level_btn = tk.Button(
                self.root,
                text=str(i),
                command=lambda lvl=i: self.select_level(lvl),
                font=("Microsoft YaHei", 16, "bold"),
                bg=color,
                fg="white",
                width=4,
                height=2,
                state=state
            )
            self.canvas.create_window(x + button_size//2, y + button_size//2, window=level_btn)
        
        # 返回按钮
        back_btn = tk.Button(
            self.root,
            text="返回主菜单",
            command=self.show_main_menu,
            font=("Microsoft YaHei", 16),
            bg="#607D8B",
            fg="white",
            width=20
        )
        self.canvas.create_window(self.width // 2, self.height - 50, window=back_btn)
    
    def select_level(self, level):
        """选择关卡"""
        self.level = level
        self.show_main_menu()
    
    def start_game(self):
        """开始游戏"""
        self.clear_canvas()
        
        # 重置游戏状态
        self.game_running = True
        self.game_paused = False
        self.wave = 1
        self.sunlight = 50
        self.zombies_killed = 0
        self.zombies_in_wave = 0
        self.zombies_spawned = 0
        
        # 清空所有对象
        self.grid = [[CellType.EMPTY for _ in range(self.grid_cols)] for _ in range(self.grid_rows)]
        self.plants.clear()
        self.plant_cooldowns.clear()
        self.zombies.clear()
        self.projectiles.clear()
        self.sunlights.clear()
        
        # 重置计时器
        self.last_update = time.time()
        self.game_time = 0
        self.zombie_spawn_timer = 0
        self.sun_spawn_timer = 0
        
        # 创建界面
        self.draw_background()
        self.create_plant_cards()
        self.create_status_bar()
        
        # 更新按钮状态
        self.start_btn.config(state=tk.DISABLED, text="游戏中")
        self.pause_btn.config(state=tk.NORMAL, text="暂停")
        
        # 开始游戏循环
        self.game_loop()
    
    def pause_game(self):
        """暂停/继续游戏"""
        if self.game_running:
            self.game_paused = not self.game_paused
            if self.game_paused:
                self.pause_btn.config(text="继续", bg="#4CAF50")
            else:
                self.pause_btn.config(text="暂停", bg="#FF9800")
                self.game_loop()
    
    def game_loop(self):
        """游戏主循环"""
        if not self.game_running or self.game_paused:
            return
        
        current_time = time.time()
        delta_time = current_time - self.last_update
        self.last_update = current_time
        self.game_time += delta_time
        
        # 更新所有游戏对象
        self.update_sunlights(delta_time)
        self.update_plants(delta_time)
        self.update_zombies(delta_time)
        self.update_projectiles(delta_time)
        self.spawn_zombies(delta_time)
        self.spawn_sunlights(delta_time)
        
        # 检查波次完成
        self.check_wave()
        
        # 检查游戏结束
        self.check_game_over()
        
        # 更新UI
        self.update_ui()
        
        # 继续游戏循环
        if self.game_running and not self.game_paused:
            self.root.after(16, self.game_loop)  # ~60 FPS
    
    def update_sunlights(self, delta_time):
        """更新阳光"""
        for sunlight in self.sunlights[:]:
            # 自动下降
            if not sunlight.get("collected", False):
                sunlight["y"] += 1
                
                # 检查是否落地
                if sunlight["y"] > self.height - 50:
                    self.sunlights.remove(sunlight)
                    continue
            
            # 绘制阳光
            self.draw_sunlight(sunlight)
    
    def draw_sunlight(self, sunlight):
        """绘制阳光"""
        x, y = sunlight["x"], sunlight["y"]
        size = sunlight["size"]
        
        # 删除旧的阳光图形
        if "canvas_id" in sunlight:
            self.canvas.delete(sunlight["canvas_id"])
        
        # 绘制阳光
        sunlight_id = self.canvas.create_oval(
            x - size, y - size,
            x + size, y + size,
            fill="#FFD700",
            outline="#FFA500",
            width=2
        )
        
        # 阳光中心
        self.canvas.create_oval(
            x - size//2, y - size//2,
            x + size//2, y + size//2,
            fill="#FFA500",
            outline=""
        )
        
        sunlight["canvas_id"] = sunlight_id
    
    def spawn_sunlights(self, delta_time):
        """生成阳光"""
        self.sun_spawn_timer += delta_time
        if self.sun_spawn_timer >= self.sun_spawn_interval:
            self.sun_spawn_timer = 0
            
            # 从天空掉落阳光
            for _ in range(3):
                x = random.randint(self.lawn_start_x, self.lawn_start_x + self.grid_cols * self.cell_size - 20)
                y = 50
                value = 25
                
                sunlight = {
                    "x": x,
                    "y": y,
                    "size": 15,
                    "value": value,
                    "collected": False
                }
                
                self.sunlights.append(sunlight)
    
    def update_plants(self, delta_time):
        """更新植物"""
        for plant in self.plants[:]:
            plant_type = plant["type"]
            
            # 绘制植物
            self.draw_plant(plant)
            
            # 植物特殊功能
            if plant_type == PlantType.SUNFLOWER:
                # 向日葵产生阳光
                plant["sun_timer"] += delta_time
                if plant["sun_timer"] >= 10.0:  # 每10秒产生阳光
                    plant["sun_timer"] = 0
                    self.create_sun_at_plant(plant)
            
            elif plant_type in [PlantType.PEASHOOTER, PlantType.SNOW_PEA, PlantType.REPEATER]:
                # 射击植物
                plant["shoot_timer"] += delta_time
                shoot_interval = 1.5 if plant_type == PlantType.REPEATER else 2.0
                
                if plant["shoot_timer"] >= shoot_interval:
                    plant["shoot_timer"] = 0
                    self.plant_shoot(plant)
    
    def draw_plant(self, plant):
        """绘制植物"""
        x, y = plant["x"], plant["y"]
        plant_type = plant["type"]
        
        # 删除旧的植物图形
        if "canvas_id" in plant:
            self.canvas.delete(plant["canvas_id"])
        
        # 根据植物类型绘制
        if plant_type == PlantType.SUNFLOWER:
            # 向日葵
            plant_id = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill="#FFD700",  # 黄色
                outline="#FFA500",
                width=2
            )
            
            # 花瓣
            for i in range(8):
                angle = i * math.pi / 4
                petal_x = x + 30 * math.cos(angle)
                petal_y = y + 30 * math.sin(angle)
                self.canvas.create_oval(
                    petal_x - 10, petal_y - 10,
                    petal_x + 10, petal_y + 10,
                    fill="#FFA500",
                    outline=""
                )
        
        elif plant_type == PlantType.PEASHOOTER:
            # 豌豆射手
            plant_id = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill="#4CAF50",  # 绿色
                outline="#2E7D32",
                width=2
            )
            
            # 嘴巴
            self.canvas.create_arc(
                x - 15, y - 15,
                x + 15, y + 15,
                start=0, extent=180,
                fill="#2E7D32",
                outline=""
            )
        
        elif plant_type == PlantType.WALLNUT:
            # 坚果墙
            plant_id = self.canvas.create_oval(
                x - 25, y - 25,
                x + 25, y + 25,
                fill="#8B4513",  # 棕色
                outline="#654321",
                width=3
            )
            
            # 裂纹效果（根据生命值）
            health_ratio = plant.get("health", 300) / 300
            if health_ratio < 0.5:
                # 绘制裂纹
                self.canvas.create_line(
                    x - 10, y - 10,
                    x + 10, y + 10,
                    fill="#654321",
                    width=2
                )
                self.canvas.create_line(
                    x + 10, y - 10,
                    x - 10, y + 10,
                    fill="#654321",
                    width=2
                )
        
        elif plant_type == PlantType.SNOW_PEA:
            # 寒冰射手
            plant_id = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill="#87CEEB",  # 浅蓝色
                outline="#4682B4",
                width=2
            )
            
            # 雪花符号
            self.canvas.create_text(
                x, y,
                text="❄️",
                font=("Arial", 20)
            )
        
        elif plant_type == PlantType.REPEATER:
            # 双发射手
            plant_id = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill="#2E8B57",  # 深绿色
                outline="#1B5E20",
                width=2
            )
            
            # 两个嘴巴
            self.canvas.create_oval(
                x - 25, y - 10,
                x - 15, y + 10,
                fill="#1B5E20",
                outline=""
            )
            self.canvas.create_oval(
                x + 15, y - 10,
                x + 25, y + 10,
                fill="#1B5E20",
                outline=""
            )
        
        elif plant_type == PlantType.POTATO_MINE:
            # 土豆地雷
            plant_id = self.canvas.create_oval(
                x - 15, y - 15,
                x + 15, y + 15,
                fill="#D2691E",  # 土豆色
                outline="#8B4513",
                width=2
            )
            
            # 引信
            self.canvas.create_line(
                x, y - 15,
                x, y - 30,
                fill="#8B4513",
                width=2
            )
        
        elif plant_type == PlantType.SQUASH:
            # 倭瓜
            plant_id = self.canvas.create_oval(
                x - 30, y - 20,
                x + 30, y + 20,
                fill="#228B22",  # 绿色
                outline="#006400",
                width=2
            )
            
            # 眼睛
            self.canvas.create_oval(
                x - 10, y - 5,
                x - 5, y,
                fill="white",
                outline=""
            )
            self.canvas.create_oval(
                x + 5, y - 5,
                x + 10, y,
                fill="white",
                outline=""
            )
        
        else:
            # 默认植物
            plant_id = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill="#4CAF50",
                outline="#2E7D32",
                width=2
            )
        
        plant["canvas_id"] = plant_id
        
        # 绘制植物血条
        if "health" in plant and "max_health" in plant:
            health_ratio = plant["health"] / plant["max_health"]
            bar_width = 40
            bar_height = 5
            bar_x = x - bar_width // 2
            bar_y = y - 40
            
            # 删除旧血条
            if "health_bar" in plant:
                self.canvas.delete(plant["health_bar"])
            
            # 绘制新血条
            health_color = "#4CAF50" if health_ratio > 0.5 else "#FF9800" if health_ratio > 0.2 else "#F44336"
            health_bar = self.canvas.create_rectangle(
                bar_x, bar_y,
                bar_x + bar_width * health_ratio, bar_y + bar_height,
                fill=health_color,
                outline=""
            )
            plant["health_bar"] = health_bar
    
    def create_sun_at_plant(self, plant):
        """在植物位置创建阳光"""
        x, y = plant["x"], plant["y"]
        value = 25
        
        sunlight = {
            "x": x,
            "y": y - 30,
            "size": 12,
            "value": value,
            "collected": False
        }
        
        self.sunlights.append(sunlight)
    
    def plant_shoot(self, plant):
        """植物射击"""
        plant_type = plant["type"]
        x, y = plant["x"], plant["y"]
        row = plant["row"]
        
        # 查找该行的第一个僵尸
        target_zombie = None
        for zombie in self.zombies:
            if zombie["row"] == row and zombie["x"] > x:
                if target_zombie is None or zombie["x"] < target_zombie["x"]:
                    target_zombie = zombie
        
        if target_zombie:
            # 创建子弹
            if plant_type == PlantType.SNOW_PEA:
                # 寒冰子弹
                projectile = {
                    "x": x + 20,
                    "y": y,
                    "row": row,
                    "speed": 5,
                    "damage": 1,
                    "type": "snow",
                    "color": "#87CEEB"
                }
            elif plant_type == PlantType.REPEATER:
                # 双发子弹
                for offset in [-5, 5]:
                    projectile = {
                        "x": x + 20 + offset,
                        "y": y + offset,
                        "row": row,
                        "speed": 5,
                        "damage": 1,
                        "type": "normal",
                        "color": "#4CAF50"
                    }
                    self.projectiles.append(projectile)
                return
            else:
                # 普通子弹
                projectile = {
                    "x": x + 20,
                    "y": y,
                    "row": row,
                    "speed": 5,
                    "damage": 1,
                    "type": "normal",
                    "color": "#4CAF50"
                }
            
            self.projectiles.append(projectile)
    
    def update_projectiles(self, delta_time):
        """更新子弹"""
        for projectile in self.projectiles[:]:
            # 移动子弹
            projectile["x"] += projectile["speed"]
            
            # 绘制子弹
            self.draw_projectile(projectile)
            
            # 检查碰撞
            self.check_projectile_collision(projectile)
            
            # 检查出界
            if projectile["x"] > self.width:
                self.projectiles.remove(projectile)
    
    def draw_projectile(self, projectile):
        """绘制子弹"""
        x, y = projectile["x"], projectile["y"]
        
        # 删除旧的子弹图形
        if "canvas_id" in projectile:
            self.canvas.delete(projectile["canvas_id"])
        
        if projectile["type"] == "snow":
            # 寒冰子弹
            projectile_id = self.canvas.create_oval(
                x - 5, y - 5,
                x + 5, y + 5,
                fill=projectile["color"],
                outline="#4682B4",
                width=1
            )
        else:
            # 普通子弹
            projectile_id = self.canvas.create_oval(
                x - 5, y - 5,
                x + 5, y + 5,
                fill=projectile["color"],
                outline="#2E7D32",
                width=1
            )
        
        projectile["canvas_id"] = projectile_id
    
    def check_projectile_collision(self, projectile):
        """检查子弹碰撞"""
        for zombie in self.zombies[:]:
            if zombie["row"] == projectile["row"]:
                dx = zombie["x"] - projectile["x"]
                dy = zombie["y"] - projectile["y"]
                distance = math.sqrt(dx*dx + dy*dy)
                
                if distance < zombie["size"] + 5:  # 子弹半径5
                    # 造成伤害
                    zombie["health"] -= projectile["damage"]
                    
                    # 寒冰效果
                    if projectile["type"] == "snow":
                        zombie["speed"] = max(0.2, zombie["speed"] * 0.5)
                        zombie["frozen"] = True
                        zombie["freeze_timer"] = 3.0
                    
                    # 爆炸效果
                    self.create_explosion(projectile["x"], projectile["y"], projectile["color"])
                    
                    # 移除子弹
                    if "canvas_id" in projectile:
                        self.canvas.delete(projectile["canvas_id"])
                    if projectile in self.projectiles:
                        self.projectiles.remove(projectile)
                    
                    # 检查僵尸是否死亡
                    if zombie["health"] <= 0:
                        self.zombie_killed(zombie)
                    
                    break
    
    def create_explosion(self, x, y, color):
        """创建爆炸效果"""
        for _ in range(8):
            angle = random.uniform(0, math.pi*2)
            distance = random.uniform(5, 15)
            dx = math.cos(angle) * distance
            dy = math.sin(angle) * distance
            
            particle_id = self.canvas.create_oval(
                x - 2, y - 2,
                x + 2, y + 2,
                fill=color,
                outline=""
            )
            
            # 动画效果
            def animate_particle(pid, ox, oy, pdx, pdy, frame=0):
                if frame < 10:
                    self.canvas.move(pid, pdx, pdy)
                    self.root.after(50, animate_particle, pid, ox, oy, pdx, pdy, frame+1)
                else:
                    self.canvas.delete(pid)
            
            self.root.after(10, animate_particle, particle_id, x, y, dx, dy)
    
    def spawn_zombies(self, delta_time):
        """生成僵尸"""
        if self.zombies_spawned < self.zombies_in_wave:
            self.zombie_spawn_timer += delta_time
            if self.zombie_spawn_timer >= self.zombie_spawn_interval:
                self.zombie_spawn_timer = 0
                self.zombies_spawned += 1
                self.create_zombie()
    
    def create_zombie(self):
        """创建僵尸"""
        row = random.randint(0, self.grid_rows - 1)
        zombie_type = self.get_zombie_type_for_wave()
        
        x = self.width + 50
        y = self.lawn_start_y + row * self.cell_size + self.cell_size // 2
        
        if zombie_type == ZombieType.BASIC:
            size = 25
            health = 10
            speed = 0.5
            color = "#556B2F"
            score = 10
        elif zombie_type == ZombieType.CONEHEAD:
            size = 30
            health = 20
            speed = 0.4
            color = "#8B4513"
            score = 20
        elif zombie_type == ZombieType.BUCKETHEAD:
            size = 35
            health = 30
            speed = 0.3
            color = "#808080"
            score = 30
        elif zombie_type == ZombieType.NEWSPAPER:
            size = 28
            health = 15
            speed = 0.6
            color = "#F5F5F5"
            score = 25
        elif zombie_type == ZombieType.FOOTBALL:
            size = 40
            health = 50
            speed = 0.8
            color = "#FF5722"
            score = 50
        elif zombie_type == ZombieType.DANCER:
            size = 30
            health = 25
            speed = 0.5
            color = "#9C27B0"
            score = 40
        else:  # 默认普通僵尸
            size = 25
            health = 10
            speed = 0.5
            color = "#556B2F"
            score = 10
        
        zombie = {
            "type": zombie_type,
            "x": x,
            "y": y,
            "row": row,
            "size": size,
            "health": health,
            "max_health": health,
            "speed": speed,
            "color": color,
            "score": score,
            "eating": False,
            "eat_timer": 0,
            "frozen": False,
            "freeze_timer": 0
        }
        
        self.zombies.append(zombie)
    
    def get_zombie_type_for_wave(self):
        """根据波次获取僵尸类型"""
        if self.wave == 1:
            types = [ZombieType.BASIC]
        elif self.wave == 2:
            types = [ZombieType.BASIC, ZombieType.CONEHEAD]
        elif self.wave == 3:
            types = [ZombieType.BASIC, ZombieType.CONEHEAD, ZombieType.BUCKETHEAD]
        elif self.wave == 4:
            types = [ZombieType.CONEHEAD, ZombieType.BUCKETHEAD, ZombieType.NEWSPAPER]
        else:  # wave >= 5
            types = [ZombieType.BUCKETHEAD, ZombieType.FOOTBALL, ZombieType.DANCER]
        
        return random.choice(types)
    
    def update_zombies(self, delta_time):
        """更新僵尸"""
        for zombie in self.zombies[:]:
            # 解冻效果
            if zombie.get("frozen", False):
                zombie["freeze_timer"] -= delta_time
                if zombie["freeze_timer"] <= 0:
                    zombie["frozen"] = False
                    zombie["speed"] = zombie.get("original_speed", 0.5)
            
            # 检查是否在吃植物
            eating_plant = False
            target_plant = None
            
            for plant in self.plants:
                if plant["row"] == zombie["row"]:
                    dx = zombie["x"] - plant["x"]
                    dy = zombie["y"] - plant["y"]
                    distance = math.sqrt(dx*dx + dy*dy)
                    
                    if distance < zombie["size"] + 20:  # 植物半径20
                        eating_plant = True
                        target_plant = plant
                        break
            
            if eating_plant and target_plant:
                # 吃植物
                zombie["eating"] = True
                zombie["eat_timer"] += delta_time
                
                if zombie["eat_timer"] >= 1.0:  # 每秒造成伤害
                    zombie["eat_timer"] = 0
                    
                    if "health" in target_plant:
                        target_plant["health"] -= 5
                        
                        if target_plant["health"] <= 0:
                            # 植物死亡
                            self.plant_died(target_plant)
            else:
                # 移动僵尸
                zombie["eating"] = False
                zombie["eat_timer"] = 0
                
                # 如果被冰冻，速度减半
                current_speed = zombie["speed"] * 0.5 if zombie.get("frozen", False) else zombie["speed"]
                zombie["x"] -= current_speed
            
            # 绘制僵尸
            self.draw_zombie(zombie)
            
            # 检查僵尸是否到达房屋
            if zombie["x"] < self.lawn_start_x:
                self.game_over_lose()
                return
    
    def draw_zombie(self, zombie):
        """绘制僵尸"""
        x, y = zombie["x"], zombie["y"]
        zombie_type = zombie["type"]
        
        # 删除旧的僵尸图形
        if "canvas_id" in zombie:
            self.canvas.delete(zombie["canvas_id"])
        
        if zombie_type == ZombieType.BASIC:
            # 普通僵尸
            zombie_id = self.canvas.create_oval(
                x - 25, y - 25,
                x + 25, y + 25,
                fill="#556B2F",  # 暗绿色
                outline="#2F4F4F",
                width=2
            )
            
            # 眼睛
            self.canvas.create_oval(
                x - 5, y - 5,
                x, y,
                fill="white",
                outline=""
            )
            self.canvas.create_oval(
                x + 5, y - 5,
                x + 10, y,
                fill="white",
                outline=""
            )
            
            # 嘴巴
            self.canvas.create_arc(
                x - 10, y + 5,
                x + 10, y + 20,
                start=0, extent=180,
                fill="#8B0000",
                outline=""
            )
        
        elif zombie_type == ZombieType.CONEHEAD:
            # 路障僵尸
            zombie_id = self.canvas.create_oval(
                x - 30, y - 30,
                x + 30, y + 30,
                fill="#8B4513",  # 棕色
                outline="#654321",
                width=2
            )
            
            # 路障
            self.canvas.create_rectangle(
                x - 20, y - 40,
                x + 20, y - 20,
                fill="#D2691E",
                outline="#8B4513",
                width=2
            )
        
        elif zombie_type == ZombieType.BUCKETHEAD:
            # 铁桶僵尸
            zombie_id = self.canvas.create_oval(
                x - 35, y - 35,
                x + 35, y + 35,
                fill="#808080",  # 灰色
                outline="#696969",
                width=2
            )
            
            # 铁桶
            self.canvas.create_rectangle(
                x - 25, y - 50,
                x + 25, y - 20,
                fill="#A9A9A9",
                outline="#696969",
                width=3
            )
        
        elif zombie_type == ZombieType.NEWSPAPER:
            # 报纸僵尸
            zombie_id = self.canvas.create_oval(
                x - 28, y - 28,
                x + 28, y + 28,
                fill="#F5F5F5",  # 白色
                outline="#D3D3D3",
                width=2
            )
            
            # 报纸
            self.canvas.create_rectangle(
                x - 15, y - 40,
                x + 15, y - 15,
                fill="white",
                outline="#D3D3D3",
                width=1
            )
            
            # 报纸文字
            self.canvas.create_text(
                x, y - 28,
                text="NEWS",
                font=("Arial", 8, "bold"),
                fill="black"
            )
        
        elif zombie_type == ZombieType.FOOTBALL:
            # 橄榄球僵尸
            zombie_id = self.canvas.create_oval(
                x - 40, y - 25,
                x + 40, y + 25,
                fill="#FF5722",  # 橙色
                outline="#D84315",
                width=2
            )
            
            # 头盔条纹
            for i in range(3):
                stripe_y = y - 15 + i * 15
                self.canvas.create_line(
                    x - 30, stripe_y,
                    x + 30, stripe_y,
                    fill="white",
                    width=3
                )
        
        elif zombie_type == ZombieType.DANCER:
            # 舞王僵尸
            zombie_id = self.canvas.create_oval(
                x - 30, y - 30,
                x + 30, y + 30,
                fill="#9C27B0",  # 紫色
                outline="#7B1FA2",
                width=2
            )
            
            # 舞王帽子
            self.canvas.create_rectangle(
                x - 20, y - 50,
                x + 20, y - 30,
                fill="#E1BEE7",
                outline="#7B1FA2",
                width=2
            )
        
        else:
            # 默认僵尸
            zombie_id = self.canvas.create_oval(
                x - 25, y - 25,
                x + 25, y + 25,
                fill="#556B2F",
                outline="#2F4F4F",
                width=2
            )
        
        zombie["canvas_id"] = zombie_id
        
        # 绘制僵尸血条
        if "health" in zombie and "max_health" in zombie:
            health_ratio = zombie["health"] / zombie["max_health"]
            bar_width = 50
            bar_height = 5
            bar_x = x - bar_width // 2
            bar_y = y - 50
            
            # 删除旧血条
            if "health_bar" in zombie:
                self.canvas.delete(zombie["health_bar"])
            
            # 绘制新血条
            health_color = "#4CAF50" if health_ratio > 0.5 else "#FF9800" if health_ratio > 0.2 else "#F44336"
            health_bar = self.canvas.create_rectangle(
                bar_x, bar_y,
                bar_x + bar_width * health_ratio, bar_y + bar_height,
                fill=health_color,
                outline=""
            )
            zombie["health_bar"] = health_bar
    
    def zombie_killed(self, zombie):
        """僵尸被击杀"""
        # 分数
        self.score += zombie["score"]
        self.zombies_killed += 1
        
        # 爆炸效果
        self.create_explosion(zombie["x"], zombie["y"], "#FF9800")
        
        # 掉落阳光
        if random.random() < 0.3:  # 30%几率掉落阳光
            self.create_sun_at_zombie(zombie)
        
        # 移除僵尸
        if "canvas_id" in zombie:
            self.canvas.delete(zombie["canvas_id"])
        if "health_bar" in zombie:
            self.canvas.delete(zombie["health_bar"])
        if zombie in self.zombies:
            self.zombies.remove(zombie)
    
    def create_sun_at_zombie(self, zombie):
        """在僵尸位置创建阳光"""
        x, y = zombie["x"], zombie["y"]
        value = 25
        
        sunlight = {
            "x": x,
            "y": y,
            "size": 12,
            "value": value,
            "collected": False
        }
        
        self.sunlights.append(sunlight)
    
    def plant_died(self, plant):
        """植物死亡"""
        # 从网格移除
        if 0 <= plant["row"] < self.grid_rows and 0 <= plant["col"] < self.grid_cols:
            self.grid[plant["row"]][plant["col"]] = CellType.EMPTY
        
        # 移除植物图形
        if "canvas_id" in plant:
            self.canvas.delete(plant["canvas_id"])
        if "health_bar" in plant:
            self.canvas.delete(plant["health_bar"])
        
        # 从植物列表移除
        if plant in self.plants:
            self.plants.remove(plant)
    
    def check_wave(self):
        """检查波次"""
        if not self.zombies and self.zombies_spawned >= self.zombies_in_wave:
            # 波次完成
            if self.wave < self.max_wave:
                self.wave += 1
                self.start_wave()
            else:
                self.game_over_win()
    
    def start_wave(self):
        """开始新波次"""
        # 重置僵尸计数
        self.zombies_spawned = 0
        self.zombies_in_wave = 5 + self.wave * 2  # 每波增加2个僵尸
        
        # 显示波次信息
        self.show_wave_message()
    
    def show_wave_message(self):
        """显示波次信息"""
        wave_text = f"波次 {self.wave}"
        
        text_id = self.canvas.create_text(
            self.width // 2,
            self.height // 2,
            text=wave_text,
            font=("Microsoft YaHei", 40, "bold"),
            fill="#FF9800"
        )
        
        # 倒计时
        countdown_text = self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 50,
            text="3",
            font=("Microsoft YaHei", 30, "bold"),
            fill="#F44336"
        )
        
        def countdown(num):
            if num > 0:
                self.canvas.itemconfig(countdown_text, text=str(num))
                self.root.after(1000, countdown, num-1)
            else:
                self.canvas.delete(text_id)
                self.canvas.delete(countdown_text)
        
        self.root.after(1000, countdown, 3)
    
    def check_game_over(self):
        """检查游戏结束"""
        # 检查是否有僵尸到达房屋
        for zombie in self.zombies:
            if zombie["x"] < self.lawn_start_x:
                self.game_over_lose()
                return
    
    def game_over_win(self):
        """游戏胜利"""
        self.game_running = False
        
        # 保存最高关卡
        if self.level > self.load_high_level():
            self.save_high_level(self.level)
        
        # 显示胜利画面
        overlay = self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black", stipple="gray25"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 - 50,
            text="🎉 胜利！ 🎉",
            font=("Microsoft YaHei", 60, "bold"),
            fill="#4CAF50"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 20,
            text=f"完成关卡 {self.level}",
            font=("Microsoft YaHei", 36),
            fill="#FFD700"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 80,
            text=f"击杀僵尸: {self.zombies_killed}",
            font=("Microsoft YaHei", 28),
            fill="white"
        )
        
        # 按钮
        next_btn = tk.Button(
            self.root,
            text="下一关卡",
            command=self.next_level,
            font=("Microsoft YaHei", 20),
            bg="#4CAF50",
            fg="white",
            width=15
        )
        
        menu_btn = tk.Button(
            self.root,
            text="返回主菜单",
            command=self.show_main_menu,
            font=("Microsoft YaHei", 20),
            bg="#2196F3",
            fg="white",
            width=15
        )
        
        self.canvas.create_window(
            self.width // 2,
            self.height // 2 + 160,
            window=next_btn
        )
        
        self.canvas.create_window(
            self.width // 2,
            self.height // 2 + 220,
            window=menu_btn
        )
        
        # 更新按钮状态
        self.start_btn.config(state=tk.NORMAL, text="开始游戏")
        self.pause_btn.config(state=tk.DISABLED)
    
    def game_over_lose(self):
        """游戏失败"""
        self.game_running = False
        
        # 显示失败画面
        overlay = self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black", stipple="gray25"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 - 50,
            text="💀 失败！ 💀",
            font=("Microsoft YaHei", 60, "bold"),
            fill="#F44336"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 20,
            text=f"僵尸攻入了你的房屋！",
            font=("Microsoft YaHei", 36),
            fill="#FF9800"
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 80,
            text=f"击杀僵尸: {self.zombies_killed}",
            font=("Microsoft YaHei", 28),
            fill="white"
        )
        
        # 按钮
        restart_btn = tk.Button(
            self.root,
            text="重新开始",
            command=self.start_game,
            font=("Microsoft YaHei", 20),
            bg="#4CAF50",
            fg="white",
            width=15
        )
        
        menu_btn = tk.Button(
            self.root,
            text="返回主菜单",
            command=self.show_main_menu,
            font=("Microsoft YaHei", 20),
            bg="#2196F3",
            fg="white",
            width=15
        )
        
        self.canvas.create_window(
            self.width // 2,
            self.height // 2 + 160,
            window=restart_btn
        )
        
        self.canvas.create_window(
            self.width // 2,
            self.height // 2 + 220,
            window=menu_btn
        )
        
        # 更新按钮状态
        self.start_btn.config(state=tk.NORMAL, text="开始游戏")
        self.pause_btn.config(state=tk.DISABLED)
    
    def next_level(self):
        """下一关卡"""
        self.level += 1
        self.start_game()
    
    def update_ui(self):
        """更新UI"""
        self.sunlight_label.config(text=f"☀️ {self.sunlight}")
        self.wave_label.config(text=f"🌊 波次: {self.wave}/{self.max_wave}")
        self.level_label.config(text=f"⭐ 等级: {self.level}")
        self.kills_label.config(text=f"💀 击杀: {self.zombies_killed}")
    
    def on_click(self, event):
        """鼠标点击事件"""
        if not self.game_running or self.game_paused:
            return
        
        # 检查是否点击了植物卡片
        for card in self.plant_cards:
            if (card["x"] <= event.x <= card["x"] + card["width"] and
                card["y"] <= event.y <= card["y"] + card["height"]):
                if self.sunlight >= card["cost"]:
                    self.plant_selected = card["type"]
                    self.plant_preview = {
                        "type": card["type"],
                        "cost": card["cost"],
                        "color": card["color"]
                    }
                return
        
        # 检查是否点击了阳光
        for sunlight in self.sunlights[:]:
            dx = sunlight["x"] - event.x
            dy = sunlight["y"] - event.y
            distance = math.sqrt(dx*dx + dy*dy)
            
            if distance < sunlight["size"]:
                # 收集阳光
                self.sunlight += sunlight["value"]
                self.sunlight = min(self.sunlight, self.max_sunlight)
                
                # 移除阳光
                if "canvas_id" in sunlight:
                    self.canvas.delete(sunlight["canvas_id"])
                if sunlight in self.sunlights:
                    self.sunlights.remove(sunlight)
                return
        
        # 检查是否点击了草坪
        if (self.lawn_start_x <= event.x <= self.lawn_start_x + self.grid_cols * self.cell_size and
            self.lawn_start_y <= event.y <= self.lawn_start_y + self.grid_rows * self.cell_size):
            
            if self.plant_selected:
                # 计算网格位置
                col = (event.x - self.lawn_start_x) // self.cell_size
                row = (event.y - self.lawn_start_y) // self.cell_size
                
                if 0 <= row < self.grid_rows and 0 <= col < self.grid_cols:
                    if self.grid[row][col] == CellType.EMPTY:
                        # 种植植物
                        self.plant_plant(row, col)
        
        # 清除植物选择
        self.plant_selected = None
        self.plant_preview = None
    
    def on_mouse_move(self, event):
        """鼠标移动事件"""
        if self.plant_preview:
            # 显示植物预览
            self.show_plant_preview(event.x, event.y)
    
    def show_plant_preview(self, x, y):
        """显示植物预览"""
        # 清除旧预览
        if hasattr(self, "preview_item"):
            self.canvas.delete(self.preview_item)
        
        # 创建新预览
        if self.plant_preview["type"] == PlantType.SUNFLOWER:
            self.preview_item = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill=self.plant_preview["color"],
                outline="#FFA500",
                width=2,
                stipple="gray50"
            )
        else:
            self.preview_item = self.canvas.create_oval(
                x - 20, y - 20,
                x + 20, y + 20,
                fill=self.plant_preview["color"],
                outline="#2E7D32",
                width=2,
                stipple="gray50"
            )
    
    def plant_plant(self, row, col):
        """种植植物"""
        plant_type = self.plant_selected
        
        # 计算实际位置
        x = self.lawn_start_x + col * self.cell_size + self.cell_size // 2
        y = self.lawn_start_y + row * self.cell_size + self.cell_size // 2
        
        # 创建植物对象
        if plant_type == PlantType.SUNFLOWER:
            plant = {
                "type": PlantType.SUNFLOWER,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 50,
                "max_health": 50,
                "sun_timer": 0
            }
        elif plant_type == PlantType.PEASHOOTER:
            plant = {
                "type": PlantType.PEASHOOTER,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 100,
                "max_health": 100,
                "shoot_timer": 0
            }
        elif plant_type == PlantType.WALLNUT:
            plant = {
                "type": PlantType.WALLNUT,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 300,
                "max_health": 300
            }
        elif plant_type == PlantType.SNOW_PEA:
            plant = {
                "type": PlantType.SNOW_PEA,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 100,
                "max_health": 100,
                "shoot_timer": 0
            }
        elif plant_type == PlantType.REPEATER:
            plant = {
                "type": PlantType.REPEATER,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 100,
                "max_health": 100,
                "shoot_timer": 0
            }
        elif plant_type == PlantType.POTATO_MINE:
            plant = {
                "type": PlantType.POTATO_MINE,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 10,
                "max_health": 10,
                "armed": False,
                "arm_timer": 0
            }
        elif plant_type == PlantType.SQUASH:
            plant = {
                "type": PlantType.SQUASH,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 100,
                "max_health": 100,
                "attack_timer": 0
            }
        else:
            plant = {
                "type": plant_type,
                "x": x,
                "y": y,
                "row": row,
                "col": col,
                "health": 100,
                "max_health": 100
            }
        
        # 扣除阳光
        card = next(c for c in self.plant_cards if c["type"] == plant_type)
        self.sunlight -= card["cost"]
        
        # 添加到植物列表
        self.plants.append(plant)
        
        # 更新网格
        self.grid[row][col] = CellType.PLANT
        
        # 清除预览
        self.plant_selected = None
        self.plant_preview = None
        if hasattr(self, "preview_item"):
            self.canvas.delete(self.preview_item)
    
    def clear_canvas(self):
        """清空画布"""
        self.canvas.delete("all")
    
    def clear_game_objects(self):
        """清除游戏对象"""
        # 清除所有图形对象
        for plant in self.plants:
            if "canvas_id" in plant:
                self.canvas.delete(plant["canvas_id"])
            if "health_bar" in plant:
                self.canvas.delete(plant["health_bar"])
        
        for zombie in self.zombies:
            if "canvas_id" in zombie:
                self.canvas.delete(zombie["canvas_id"])
            if "health_bar" in zombie:
                self.canvas.delete(zombie["health_bar"])
        
        for projectile in self.projectiles:
            if "canvas_id" in projectile:
                self.canvas.delete(projectile["canvas_id"])
        
        for sunlight in self.sunlights:
            if "canvas_id" in sunlight:
                self.canvas.delete(sunlight["canvas_id"])
        
        # 清空列表
        self.plants.clear()
        self.zombies.clear()
        self.projectiles.clear()
        self.sunlights.clear()
    
    def load_game_data(self):
        """加载游戏数据"""
        try:
            if os.path.exists("pvz_data.json"):
                with open("pvz_data.json", "r") as f:
                    data = json.load(f)
                    self.level = data.get("level", 1)
        except:
            self.level = 1
    
    def load_high_level(self):
        """加载最高关卡"""
        try:
            if os.path.exists("pvz_high_level.json"):
                with open("pvz_high_level.json", "r") as f:
                    data = json.load(f)
                    return data.get("high_level", 1)
        except:
            return 1
    
    def save_high_level(self, level):
        """保存最高关卡"""
        try:
            data = {"high_level": level}
            with open("pvz_high_level.json", "w") as f:
                json.dump(data, f)
        except:
            pass

def main():
    root = tk.Tk()
    game = Game(root)
    root.mainloop()

if __name__ == "__main__":
    main()