import pygame
import sys
import random
import time
from pygame.locals import *

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 1000, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("植物大战僵尸 - 塔防游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (50, 200, 50)
DARK_GREEN = (0, 100, 0)
YELLOW = (255, 255, 50)
RED = (255, 50, 50)
BLUE = (50, 100, 255)
ORANGE = (255, 165, 0)
PURPLE = (180, 50, 230)
BROWN = (139, 69, 19)
SKY_BLUE = (135, 206, 235)
GRASS_GREEN = (60, 180, 75)
LIGHT_GREEN = (144, 238, 144)
GRAY = (100, 100, 100)
LIGHT_GRAY = (200, 200, 200)
DARK_GRAY = (50, 50, 50)

# 加载字体
try:
    font_large = pygame.font.Font(None, 48)
    font_medium = pygame.font.Font(None, 36)
    font_small = pygame.font.Font(None, 24)
    font_tiny = pygame.font.Font(None, 20)
except:
    font_large = pygame.font.SysFont(None, 48)
    font_medium = pygame.font.SysFont(None, 36)
    font_small = pygame.font.SysFont(None, 24)
    font_tiny = pygame.font.SysFont(None, 20)

# 游戏参数
GRID_SIZE = 80
GRID_WIDTH = 9
GRID_HEIGHT = 5
SUN_COST = 50
SUN_VALUE = 25
FPS = 60

class Plant:
    """植物基类"""
    def __init__(self, x, y, plant_type="sunflower"):
        self.x = x
        self.y = y
        self.type = plant_type
        self.health = 100
        self.cost = 100
        self.attack_power = 0
        self.attack_range = 0
        self.attack_speed = 0
        self.attack_timer = 0
        self.sun_production = 0
        self.sun_timer = 0
        self.animation_frame = 0
        
        if plant_type == "sunflower":  # 向日葵
            self.color = YELLOW
            self.cost = 50
            self.sun_production = 25
            self.sun_timer = 300  # 5秒生产一个太阳
        elif plant_type == "pea_shooter":  # 豌豆射手
            self.color = GREEN
            self.cost = 100
            self.attack_power = 20
            self.attack_range = 400
            self.attack_speed = 60  # 每秒发射一次
        elif plant_type == "walnut":  # 坚果墙
            self.color = BROWN
            self.cost = 50
            self.health = 300
        elif plant_type == "cherry_bomb":  # 樱桃炸弹
            self.color = RED
            self.cost = 150
            self.explode_timer = 180  # 3秒后爆炸
    
    def update(self):
        """更新植物状态"""
        self.animation_frame += 1
        
        if self.type == "sunflower":
            self.sun_timer -= 1
            if self.sun_timer <= 0:
                self.sun_timer = 300
                return True  # 产生太阳
                
        elif self.type == "pea_shooter":
            if self.attack_timer > 0:
                self.attack_timer -= 1
                
        elif self.type == "cherry_bomb":
            if self.explode_timer > 0:
                self.explode_timer -= 1
                if self.explode_timer <= 0:
                    return "explode"  # 爆炸
        
        return False
    
    def draw(self, screen):
        """绘制植物"""
        x, y = int(self.x), int(self.y)
        size = GRID_SIZE - 10
        
        # 绘制植物主体
        if self.type == "sunflower":
            # 向日葵
            pygame.draw.circle(screen, self.color, (x + size//2, y + size//2), size//2)
            pygame.draw.circle(screen, ORANGE, (x + size//2, y + size//2), size//4)
            
            # 绘制花瓣
            for i in range(8):
                angle = self.animation_frame * 0.1 + i * 45
                px = x + size//2 + int((size//2 + 5) * pygame.math.Vector2(1, 0).rotate(angle).x)
                py = y + size//2 + int((size//2 + 5) * pygame.math.Vector2(1, 0).rotate(angle).y)
                pygame.draw.circle(screen, YELLOW, (px, py), 8)
                
        elif self.type == "pea_shooter":
            # 豌豆射手
            pygame.draw.rect(screen, self.color, (x, y, size, size), border_radius=10)
            
            # 绘制嘴巴
            mouth_rect = pygame.Rect(x + size - 20, y + size//2 - 10, 20, 20)
            pygame.draw.ellipse(screen, (100, 50, 0), mouth_rect)
            
            # 绘制眼睛
            pygame.draw.circle(screen, BLACK, (x + 20, y + 20), 5)
            pygame.draw.circle(screen, WHITE, (x + 20, y + 20), 2)
            
        elif self.type == "walnut":
            # 坚果墙
            pygame.draw.rect(screen, self.color, (x, y, size, size), border_radius=5)
            
            # 绘制裂缝
            health_percent = self.health / 300
            if health_percent < 0.7:
                pygame.draw.line(screen, BLACK, (x + 10, y + 20), (x + size - 10, y + 40), 2)
            if health_percent < 0.4:
                pygame.draw.line(screen, BLACK, (x + 20, y + 50), (x + size - 20, y + 30), 2)
                
        elif self.type == "cherry_bomb":
            # 樱桃炸弹
            if self.explode_timer > 60 or (self.explode_timer // 10) % 2 == 0:
                pygame.draw.circle(screen, self.color, (x + size//2, y + size//2), size//2)
                
                # 绘制引线
                fuse_length = max(0, (180 - self.explode_timer) * 0.5)
                pygame.draw.line(screen, DARK_GRAY, 
                               (x + size//2, y), 
                               (x + size//2, y - fuse_length), 3)
    
    def can_attack(self):
        """检查是否可以攻击"""
        if self.type == "pea_shooter" and self.attack_timer <= 0:
            self.attack_timer = self.attack_speed
            return True
        return False
    
    def get_rect(self):
        """获取碰撞矩形"""
        return pygame.Rect(self.x, self.y, GRID_SIZE - 10, GRID_SIZE - 10)
    
    def take_damage(self, damage):
        """受到伤害"""
        self.health -= damage
        return self.health <= 0

class Pea:
    """豌豆子弹类"""
    def __init__(self, x, y, target_x):
        self.x = x
        self.y = y + 20
        self.speed = 5
        self.power = 20
        self.target_x = target_x
        self.size = 8
        
    def update(self):
        """更新位置"""
        self.x += self.speed
    
    def draw(self, screen):
        """绘制豌豆"""
        pygame.draw.circle(screen, GREEN, (int(self.x), int(self.y)), self.size)
        pygame.draw.circle(screen, DARK_GREEN, (int(self.x), int(self.y)), self.size, 2)
    
    def is_off_screen(self):
        """检查是否离开屏幕"""
        return self.x > WIDTH or self.x < 0
    
    def collides_with(self, zombie_rect):
        """检查是否与僵尸碰撞"""
        pea_rect = pygame.Rect(self.x - self.size, self.y - self.size, 
                              self.size * 2, self.size * 2)
        return pea_rect.colliderect(zombie_rect)

class Zombie:
    """僵尸类"""
    def __init__(self, lane, zombie_type="normal"):
        self.lane = lane
        self.type = zombie_type
        self.x = WIDTH
        self.y = 100 + lane * GRID_SIZE
        self.speed = 0.5
        self.health = 100
        self.attack_power = 10
        self.attack_speed = 60
        self.attack_timer = 0
        self.is_eating = False
        self.animation_frame = 0
        self.width = 60
        self.height = 80
        
        if zombie_type == "normal":
            self.color = (100, 150, 100)
            self.health = 100
        elif zombie_type == "conehead":
            self.color = (150, 150, 150)
            self.health = 200
        elif zombie_type == "buckethead":
            self.color = (100, 100, 100)
            self.health = 300
            self.width = 70
    
    def update(self, plants_in_lane):
        """更新僵尸状态"""
        self.animation_frame += 1
        
        # 检查前方是否有植物
        target_plant = None
        for plant in plants_in_lane:
            if plant.x < self.x < plant.x + GRID_SIZE:
                target_plant = plant
                break
        
        if target_plant:
            # 攻击植物
            self.is_eating = True
            if self.attack_timer <= 0:
                self.attack_timer = self.attack_speed
                return ("attack", target_plant, self.attack_power)
            else:
                self.attack_timer -= 1
        else:
            # 移动
            self.is_eating = False
            self.x -= self.speed
        
        return None
    
    def draw(self, screen):
        """绘制僵尸"""
        x, y = int(self.x), int(self.y)
        
        # 绘制身体
        pygame.draw.rect(screen, self.color, (x, y, self.width, self.height))
        
        # 绘制头部
        if self.type == "conehead":
            # 锥头僵尸
            pygame.draw.polygon(screen, (200, 200, 200), 
                              [(x + 10, y), (x + self.width - 10, y), 
                               (x + self.width//2, y - 30)])
        elif self.type == "buckethead":
            # 铁桶僵尸
            pygame.draw.rect(screen, (80, 80, 80), 
                           (x + 10, y - 20, self.width - 20, 20))
        
        # 绘制脸部
        eye_radius = 5
        eye_y = y + 20
        
        # 眼睛
        pygame.draw.circle(screen, BLACK, (x + 20, eye_y), eye_radius)
        pygame.draw.circle(screen, BLACK, (x + 40, eye_y), eye_radius)
        
        # 嘴巴
        if self.is_eating:
            # 吃东西的嘴巴
            pygame.draw.ellipse(screen, RED, (x + 15, y + 40, 30, 20))
        else:
            # 正常嘴巴
            pygame.draw.arc(screen, RED, (x + 15, y + 40, 30, 20), 0, 3.14, 3)
        
        # 绘制手臂摆动
        arm_swing = 0
        if not self.is_eating:
            arm_swing = int(10 * (self.animation_frame % 30) / 15)
            if arm_swing > 10:
                arm_swing = 20 - arm_swing
        
        # 手臂
        pygame.draw.line(screen, self.color, (x, y + 20), 
                        (x - 20, y + 20 + arm_swing), 10)
        pygame.draw.line(screen, self.color, (x, y + 40), 
                        (x - 20, y + 40 - arm_swing), 10)
        
        # 绘制腿部
        leg_swing = 0
        if not self.is_eating:
            leg_swing = int(15 * ((self.animation_frame + 15) % 30) / 15)
            if leg_swing > 15:
                leg_swing = 30 - leg_swing
        
        pygame.draw.line(screen, self.color, (x + 15, y + self.height), 
                        (x + 5, y + self.height + 20 + leg_swing), 10)
        pygame.draw.line(screen, self.color, (x + 45, y + self.height), 
                        (x + 55, y + self.height + 20 - leg_swing), 10)
    
    def take_damage(self, damage):
        """受到伤害"""
        self.health -= damage
        return self.health <= 0
    
    def get_rect(self):
        """获取碰撞矩形"""
        return pygame.Rect(self.x, self.y, self.width, self.height)
    
    def is_at_house(self):
        """检查是否到达房子"""
        return self.x < 100

class Sun:
    """太阳类"""
    def __init__(self, x, y, is_falling=True):
        self.x = x
        self.y = y
        self.value = SUN_VALUE
        self.size = 30
        self.is_falling = is_falling
        self.fall_speed = 1
        self.collected = False
        self.life_timer = 600  # 10秒后消失
        self.rotation = 0
        
    def update(self):
        """更新太阳"""
        if self.is_falling:
            self.y += self.fall_speed
            if self.y > HEIGHT - 100:
                self.is_falling = False
        
        self.life_timer -= 1
        self.rotation = (self.rotation + 2) % 360
        
        return self.life_timer <= 0
    
    def draw(self, screen):
        """绘制太阳"""
        if self.collected:
            return
            
        x, y = int(self.x), int(self.y)
        
        # 绘制太阳主体
        pygame.draw.circle(screen, YELLOW, (x, y), self.size)
        pygame.draw.circle(screen, ORANGE, (x, y), self.size, 3)
        
        # 绘制太阳光芒
        for i in range(12):
            angle = (self.rotation + i * 30) * 3.14159 / 180
            px1 = x + int(self.size * pygame.math.Vector2(1, 0).rotate(angle).x)
            py1 = y + int(self.size * pygame.math.Vector2(1, 0).rotate(angle).y)
            px2 = x + int((self.size + 10) * pygame.math.Vector2(1, 0).rotate(angle).x)
            py2 = y + int((self.size + 10) * pygame.math.Vector2(1, 0).rotate(angle).y)
            
            pygame.draw.line(screen, ORANGE, (px1, py1), (px2, py2), 4)
    
    def is_clicked(self, pos):
        """检查是否被点击"""
        if self.collected:
            return False
            
        distance = ((pos[0] - self.x) ** 2 + (pos[1] - self.y) ** 2) ** 0.5
        return distance <= self.size
    
    def get_rect(self):
        """获取碰撞矩形"""
        return pygame.Rect(self.x - self.size, self.y - self.size, 
                          self.size * 2, self.size * 2)

class Game:
    """游戏主类"""
    def __init__(self):
        self.plants = []
        self.zombies = []
        self.peas = []
        self.suns = []
        self.sunlight = 50
        self.score = 0
        self.wave = 1
        self.zombies_killed = 0
        self.game_state = "start"  # start, playing, game_over, victory
        self.zombie_timer = 0
        self.sun_timer = 0
        self.wave_timer = 0
        self.selected_plant = None
        self.grid = [[None for _ in range(GRID_HEIGHT)] for _ in range(GRID_WIDTH)]
        self.lawnmowers = [True] * GRID_HEIGHT
        
        self.init_game()
    
    def init_game(self):
        """初始化游戏"""
        self.plants = []
        self.zombies = []
        self.peas = []
        self.suns = []
        self.sunlight = 50
        self.score = 0
        self.wave = 1
        self.zombies_killed = 0
        self.zombie_timer = 0
        self.sun_timer = 0
        self.wave_timer = 300  # 5秒后开始第一波
        self.selected_plant = None
        self.grid = [[None for _ in range(GRID_HEIGHT)] for _ in range(GRID_WIDTH)]
        self.lawnmowers = [True] * GRID_HEIGHT
        
        # 生成初始太阳
        for _ in range(3):
            x = random.randint(100, WIDTH - 100)
            y = random.randint(100, HEIGHT - 200)
            self.suns.append(Sun(x, y, is_falling=False))
    
    def update(self):
        """更新游戏状态"""
        if self.game_state != "playing":
            return
        
        # 生成自然掉落的太阳
        self.sun_timer += 1
        if self.sun_timer >= 300:  # 每5秒生成一个太阳
            self.sun_timer = 0
            x = random.randint(100, WIDTH - 100)
            self.suns.append(Sun(x, 0))
        
        # 更新太阳
        for sun in self.suns[:]:
            if sun.update():
                self.suns.remove(sun)
        
        # 更新植物
        for plant in self.plants[:]:
            result = plant.update()
            
            if result == True:  # 向日葵产生太阳
                self.suns.append(Sun(plant.x + GRID_SIZE//2, plant.y))
            elif result == "explode":  # 樱桃炸弹爆炸
                # 爆炸效果
                for zombie in self.zombies[:]:
                    if abs(zombie.x - plant.x) < 200 and abs(zombie.y - plant.y) < 200:
                        if zombie.take_damage(1000):  # 秒杀
                            self.zombies.remove(zombie)
                            self.zombies_killed += 1
                            self.score += 10
                self.plants.remove(plant)
        
        # 更新豌豆
        for pea in self.peas[:]:
            pea.update()
            
            # 检查豌豆是否击中僵尸
            for zombie in self.zombies[:]:
                if pea.collides_with(zombie.get_rect()):
                    if zombie.take_damage(pea.power):
                        self.zombies.remove(zombie)
                        self.zombies_killed += 1
                        self.score += 10
                    if pea in self.peas:
                        self.peas.remove(pea)
                    break
            
            if pea.is_off_screen():
                if pea in self.peas:
                    self.peas.remove(pea)
        
        # 检查豌豆射手是否可以攻击
        for plant in self.plants:
            if plant.type == "pea_shooter" and plant.can_attack():
                # 检查前方是否有僵尸
                for zombie in self.zombies:
                    if (zombie.y // GRID_SIZE == plant.y // GRID_SIZE and 
                        zombie.x > plant.x and zombie.x - plant.x < plant.attack_range):
                        self.peas.append(Pea(plant.x + GRID_SIZE, plant.y + GRID_SIZE//2, zombie.x))
                        break
        
        # 生成僵尸波次
        self.wave_timer -= 1
        if self.wave_timer <= 0:
            self.spawn_zombie_wave()
            self.wave_timer = 600  # 10秒后下一波
        
        # 更新僵尸
        for zombie in self.zombies[:]:
            # 获取同一行的植物
            lane = zombie.y // GRID_SIZE
            plants_in_lane = [p for p in self.plants if p.y // GRID_SIZE == lane]
            
            result = zombie.update(plants_in_lane)
            
            if result:
                action, target_plant, damage = result
                if action == "attack":
                    if target_plant.take_damage(damage):
                        self.plants.remove(target_plant)
            
            # 检查僵尸是否到达房子
            if zombie.is_at_house():
                # 检查该行是否有割草机
                lane = zombie.y // GRID_SIZE
                if self.lawnmowers[lane]:
                    # 触发割草机
                    self.lawnmowers[lane] = False
                    # 清除该行所有僵尸
                    for z in self.zombies[:]:
                        if z.y // GRID_SIZE == lane:
                            self.zombies.remove(z)
                            self.zombies_killed += 1
                            self.score += 10
                else:
                    # 游戏结束
                    self.game_state = "game_over"
        
        # 检查是否完成所有波次
        if self.wave > 5 and len(self.zombies) == 0:
            self.game_state = "victory"
    
    def spawn_zombie_wave(self):
        """生成僵尸波次"""
        if self.wave > 5:
            return
            
        zombies_in_wave = 2 + self.wave
        
        for _ in range(zombies_in_wave):
            lane = random.randint(0, GRID_HEIGHT - 1)
            y = 100 + lane * GRID_SIZE
            
            # 根据波次选择僵尸类型
            if self.wave == 1:
                zombie_type = "normal"
            elif self.wave <= 3:
                zombie_type = random.choice(["normal", "conehead"])
            else:
                zombie_type = random.choice(["normal", "conehead", "buckethead"])
            
            self.zombies.append(Zombie(lane, zombie_type))
        
        self.wave += 1
    
    def draw(self, screen):
        """绘制游戏"""
        # 绘制背景
        screen.fill(SKY_BLUE)
        
        # 绘制天空
        for i in range(3):
            cloud_x = (i * 300) % (WIDTH + 300) - 150
            cloud_y = 50 + i * 20
            cloud_size = 20 + i * 5
            
            pygame.draw.circle(screen, WHITE, (int(cloud_x), cloud_y), cloud_size)
            pygame.draw.circle(screen, WHITE, (int(cloud_x) - cloud_size//2, cloud_y), cloud_size//2)
            pygame.draw.circle(screen, WHITE, (int(cloud_x) + cloud_size//2, cloud_y), cloud_size//2)
        
        # 绘制草地
        pygame.draw.rect(screen, GRASS_GREEN, (100, 100, WIDTH-200, GRID_HEIGHT*GRID_SIZE))
        
        # 绘制网格
        for x in range(GRID_WIDTH):
            for y in range(GRID_HEIGHT):
                rect = pygame.Rect(100 + x * GRID_SIZE, 100 + y * GRID_SIZE, GRID_SIZE, GRID_SIZE)
                pygame.draw.rect(screen, DARK_GREEN, rect, 1)
                
                # 高亮选中的格子
                if self.selected_plant and self.is_mouse_over_grid(rect):
                    pygame.draw.rect(screen, YELLOW, rect, 3)
        
        # 绘制房子
        pygame.draw.rect(screen, BROWN, (50, 100, 50, GRID_HEIGHT*GRID_SIZE))
        
        # 绘制割草机
        for lane in range(GRID_HEIGHT):
            if self.lawnmowers[lane]:
                y = 100 + lane * GRID_SIZE
                pygame.draw.rect(screen, RED, (60, y + 10, 30, 20))
                pygame.draw.rect(screen, DARK_GRAY, (70, y, 20, 10))
                pygame.draw.circle(screen, BLACK, (75, y + 30), 5)
                pygame.draw.circle(screen, BLACK, (85, y + 30), 5)
        
        # 绘制太阳
        for sun in self.suns:
            sun.draw(screen)
        
        # 绘制豌豆
        for pea in self.peas:
            pea.draw(screen)
        
        # 绘制僵尸
        for zombie in self.zombies:
            zombie.draw(screen)
        
        # 绘制植物
        for plant in self.plants:
            plant.draw(screen)
        
        # 绘制HUD
        self.draw_hud(screen)
        
        # 绘制游戏状态界面
        if self.game_state == "start":
            self.draw_start_screen(screen)
        elif self.game_state == "game_over":
            self.draw_game_over_screen(screen)
        elif self.game_state == "victory":
            self.draw_victory_screen(screen)
    
    def draw_hud(self, screen):
        """绘制游戏信息界面"""
        # 绘制太阳数量
        sun_text = font_medium.render(f"太阳: {self.sunlight}", True, YELLOW)
        screen.blit(sun_text, (20, 20))
        
        # 绘制分数
        score_text = font_medium.render(f"分数: {self.score}", True, WHITE)
        screen.blit(score_text, (20, 60))
        
        # 绘制波次
        wave_text = font_medium.render(f"波次: {min(self.wave, 5)}/5", True, WHITE)
        screen.blit(wave_text, (20, 100))
        
        # 绘制杀敌数
        kills_text = font_medium.render(f"杀敌: {self.zombies_killed}", True, WHITE)
        screen.blit(kills_text, (20, 140))
        
        # 绘制植物选择栏
        plant_types = [
            ("sunflower", "向日葵", 50, YELLOW),
            ("pea_shooter", "豌豆射手", 100, GREEN),
            ("walnut", "坚果墙", 50, BROWN),
            ("cherry_bomb", "樱桃炸弹", 150, RED)
        ]
        
        for i, (plant_type, name, cost, color) in enumerate(plant_types):
            x = 200 + i * 120
            y = 20
            
            # 绘制植物卡片背景
            card_rect = pygame.Rect(x, y, 100, 80)
            is_selected = (self.selected_plant == plant_type)
            
            if self.sunlight >= cost:
                card_color = color
            else:
                card_color = GRAY
                
            pygame.draw.rect(screen, card_color, card_rect, border_radius=5)
            pygame.draw.rect(screen, BLACK, card_rect, 2, border_radius=5)
            
            if is_selected:
                pygame.draw.rect(screen, YELLOW, card_rect, 3, border_radius=5)
            
            # 绘制植物图标
            icon_size = 30
            icon_x = x + 50
            icon_y = y + 25
            
            if plant_type == "sunflower":
                pygame.draw.circle(screen, YELLOW, (icon_x, icon_y), icon_size//2)
                pygame.draw.circle(screen, ORANGE, (icon_x, icon_y), icon_size//4)
            elif plant_type == "pea_shooter":
                pygame.draw.rect(screen, GREEN, (icon_x-15, icon_y-15, 30, 30), border_radius=5)
            elif plant_type == "walnut":
                pygame.draw.rect(screen, BROWN, (icon_x-15, icon_y-15, 30, 30), border_radius=5)
            elif plant_type == "cherry_bomb":
                pygame.draw.circle(screen, RED, (icon_x, icon_y), icon_size//2)
            
            # 绘制植物名称
            name_text = font_tiny.render(name, True, BLACK)
            screen.blit(name_text, (x + 10, y + 55))
            
            # 绘制价格
            cost_text = font_tiny.render(str(cost), True, WHITE)
            screen.blit(cost_text, (x + 40, y + 5))
        
        # 绘制控制说明
        controls = [
            "点击植物卡片选择植物",
            "点击草地种植植物",
            "点击太阳收集阳光",
            "ESC: 取消选择/返回菜单"
        ]
        
        for i, control in enumerate(controls):
            control_text = font_tiny.render(control, True, LIGHT_GRAY)
            screen.blit(control_text, (WIDTH - 200, 20 + i * 25))
    
    def draw_start_screen(self, screen):
        """绘制开始画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 标题
        title_text = font_large.render("植物大战僵尸", True, GREEN)
        screen.blit(title_text, (WIDTH//2 - 120, HEIGHT//2 - 150))
        
        # 游戏说明
        instructions = [
            "游戏目标: 抵御5波僵尸进攻，保护你的房子",
            "",
            "游戏说明:",
            "1. 收集太阳能量来购买植物",
            "2. 种植植物来防御僵尸",
            "3. 每行都有一个割草机，可清除整行僵尸",
            "4. 完成5波僵尸攻击获得胜利",
            "",
            "植物介绍:",
            "🌻 向日葵: 生产太阳能量 (50阳光)",
            "🌱 豌豆射手: 发射豌豆攻击僵尸 (100阳光)",
            "🌰 坚果墙: 高血量，阻挡僵尸前进 (50阳光)",
            "💣 樱桃炸弹: 3秒后爆炸，清除周围僵尸 (150阳光)",
            "",
            "僵尸介绍:",
            "🧟 普通僵尸: 基础敌人",
            "📎 锥头僵尸: 有锥头保护，更耐打",
            "🪣 铁桶僵尸: 有铁桶保护，非常耐打",
            "",
            "提示: 合理安排植物，注意收集太阳!"
        ]
        
        for i, instruction in enumerate(instructions):
            color = YELLOW if i == 0 else WHITE
            instruction_text = font_tiny.render(instruction, True, color)
            screen.blit(instruction_text, (WIDTH//2 - 300, HEIGHT//2 - 100 + i * 20))
        
        # 开始游戏提示
        start_text = font_medium.render("按空格键开始游戏", True, GREEN)
        screen.blit(start_text, (WIDTH//2 - 100, HEIGHT - 100))
    
    def draw_game_over_screen(self, screen):
        """绘制游戏结束画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 游戏结束文字
        game_over_text = font_large.render("游戏结束!", True, RED)
        screen.blit(game_over_text, (WIDTH//2 - 100, HEIGHT//2 - 100))
        
        # 统计信息
        stats = [
            f"最终分数: {self.score}",
            f"完成波次: {min(self.wave, 5)}/5",
            f"消灭僵尸: {self.zombies_killed}",
            f"收集太阳: {self.sunlight}"
        ]
        
        for i, stat in enumerate(stats):
            stat_text = font_medium.render(stat, True, WHITE)
            screen.blit(stat_text, (WIDTH//2 - 100, HEIGHT//2 - 50 + i * 40))
        
        # 重新开始提示
        restart_text = font_medium.render("按R键重新开始", True, GREEN)
        screen.blit(restart_text, (WIDTH//2 - 80, HEIGHT//2 + 120))
        
        menu_text = font_medium.render("按ESC键返回菜单", True, YELLOW)
        screen.blit(menu_text, (WIDTH//2 - 100, HEIGHT//2 + 170))
    
    def draw_victory_screen(self, screen):
        """绘制胜利画面"""
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        # 胜利文字
        victory_text = font_large.render("恭喜胜利!", True, YELLOW)
        screen.blit(victory_text, (WIDTH//2 - 100, HEIGHT//2 - 150))
        
        complete_text = font_medium.render("你成功抵御了所有僵尸进攻!", True, GREEN)
        screen.blit(complete_text, (WIDTH//2 - 150, HEIGHT//2 - 100))
        
        # 最终统计
        stats = [
            f"最终分数: {self.score}",
            f"消灭僵尸: {self.zombies_killed}",
            f"剩余阳光: {self.sunlight}",
            f"完成波次: 5/5"
        ]
        
        for i, stat in enumerate(stats):
            stat_text = font_medium.render(stat, True, WHITE)
            screen.blit(stat_text, (WIDTH//2 - 100, HEIGHT//2 - 50 + i * 40))
        
        # 重新开始提示
        restart_text = font_medium.render("按R键重新开始游戏", True, GREEN)
        screen.blit(restart_text, (WIDTH//2 - 100, HEIGHT//2 + 150))
        
        menu_text = font_medium.render("按ESC键返回主菜单", True, YELLOW)
        screen.blit(menu_text, (WIDTH//2 - 100, HEIGHT//2 + 200))
    
    def is_mouse_over_grid(self, rect):
        """检查鼠标是否在网格上"""
        mouse_pos = pygame.mouse.get_pos()
        return rect.collidepoint(mouse_pos)
    
    def plant_at(self, grid_x, grid_y):
        """在指定位置种植植物"""
        if self.selected_plant and self.grid[grid_x][grid_y] is None:
            plant_info = {
                "sunflower": ("向日葵", 50, YELLOW),
                "pea_shooter": ("豌豆射手", 100, GREEN),
                "walnut": ("坚果墙", 50, BROWN),
                "cherry_bomb": ("樱桃炸弹", 150, RED)
            }
            
            if self.selected_plant in plant_info:
                name, cost, color = plant_info[self.selected_plant]
                
                if self.sunlight >= cost:
                    x = 100 + grid_x * GRID_SIZE
                    y = 100 + grid_y * GRID_SIZE
                    
                    new_plant = Plant(x, y, self.selected_plant)
                    self.plants.append(new_plant)
                    self.grid[grid_x][grid_y] = new_plant
                    self.sunlight -= cost
                    self.selected_plant = None
                    return True
        
        return False
    
    def collect_sun(self, sun):
        """收集太阳"""
        if not sun.collected:
            sun.collected = True
            self.sunlight += sun.value
            self.suns.remove(sun)
            return True
        return False

def main():
    """主游戏函数"""
    clock = pygame.time.Clock()
    game = Game()
    
    # 主游戏循环
    running = True
    while running:
        clock.tick(FPS)
        
        # 处理事件
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if game.game_state in ["playing", "game_over", "victory"]:
                        if game.selected_plant:
                            game.selected_plant = None
                        else:
                            game.game_state = "start"
                    else:
                        running = False
                elif event.key == K_SPACE:
                    if game.game_state == "start":
                        game.game_state = "playing"
                elif event.key == K_r:
                    if game.game_state in ["game_over", "victory"]:
                        game.init_game()
                        game.game_state = "playing"
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    mouse_pos = pygame.mouse.get_pos()
                    
                    if game.game_state == "playing":
                        # 检查是否点击植物卡片
                        plant_types = ["sunflower", "pea_shooter", "walnut", "cherry_bomb"]
                        for i, plant_type in enumerate(plant_types):
                            card_rect = pygame.Rect(200 + i * 120, 20, 100, 80)
                            if card_rect.collidepoint(mouse_pos):
                                game.selected_plant = plant_type
                                break
                        
                        # 检查是否点击太阳
                        for sun in game.suns[:]:
                            if sun.is_clicked(mouse_pos):
                                game.collect_sun(sun)
                                break
                        
                        # 检查是否点击网格种植植物
                        if game.selected_plant:
                            for x in range(GRID_WIDTH):
                                for y in range(GRID_HEIGHT):
                                    rect = pygame.Rect(100 + x * GRID_SIZE, 100 + y * GRID_SIZE, 
                                                      GRID_SIZE, GRID_SIZE)
                                    if rect.collidepoint(mouse_pos):
                                        if game.plant_at(x, y):
                                            game.selected_plant = None
                                        break
        
        # 更新游戏状态
        if game.game_state == "playing":
            game.update()
        
        # 绘制游戏
        game.draw(screen)
        
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()