import pygame
import random
import sys
import math
import time
import os

# 初始化 Pygame
try:
    pygame.init()
    pygame.mixer.init()
    print("Pygame初始化成功")
except Exception as e:
    print(f"Pygame初始化失败: {e}")
    print("请确保已安装pygame: pip install pygame")
    sys.exit(1)

# 游戏窗口设置
WIDTH, HEIGHT = 900, 650
CELL_SIZE = 80
GRID_WIDTH = 9
GRID_HEIGHT = 5
GRID_OFFSET_X = 100  # 网格左侧偏移

try:
    # 设置窗口居中显示
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF | pygame.HWSURFACE)
    pygame.display.set_caption("植物大战僵尸 - 修复版")
    print(f"游戏窗口创建成功: {WIDTH}x{HEIGHT}")
except Exception as e:
    print(f"创建窗口失败: {e}")
    print("尝试使用备用模式...")
    try:
        screen = pygame.display.set_mode((800, 600))
    except:
        print("无法创建窗口，请检查显示设置")
        sys.exit(1)

# 颜色定义 - 修复这里！
BACKGROUND = (40, 120, 40)  # 草地绿
GRID_LINE = (30, 100, 30)
UI_BG = (50, 50, 80)
UI_BORDER = (100, 100, 150)
SUN_COLOR = (255, 200, 0)
PLANT_GREEN = (50, 200, 50)
ZOMBIE_GREEN = (100, 150, 100)
ZOMBIE_SKIN = (150, 200, 150)
RED = (255, 50, 50)
YELLOW = (255, 255, 0)  # 这就是向日葵的颜色！
BLUE = (100, 200, 255)
ICE_BLUE = (150, 220, 255)
PURPLE = (180, 100, 220)
ORANGE = (255, 150, 50)
BROWN = (150, 100, 50)
DARK_GREEN = (30, 120, 30)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PEA_COLOR = (50, 255, 50)
ICE_PEA_COLOR = (150, 220, 255)
FIRE_COLOR = (255, 100, 0)

# 字体初始化
try:
    # 尝试加载系统字体，失败则使用默认字体
    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, 18)
    print("字体初始化成功")
except:
    # 创建备用字体
    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, 18)
    print("使用备用字体")

# 游戏状态
class Game:
    def __init__(self):
        self.grid = [[None for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
        self.zombies = []
        self.projectiles = []
        self.sunlights = []
        self.explosions = []
        self.sun_score = 200
        self.wave = 1
        self.zombies_killed = 0
        self.game_over = False
        self.won = False
        self.clock = pygame.time.Clock()
        self.last_sun_spawn = time.time()
        self.last_zombie_spawn = time.time()
        self.zombie_spawn_delay = 4.0
        self.sun_spawn_delay = 6.0
        self.selected_plant = None
        self.plant_cards = []
        self.init_plant_cards()
        self.start_time = time.time()
        self.message = ""
        self.message_timer = 0
        self.last_update = time.time()
        self.delta_time = 0
        
    def init_plant_cards(self):
        """初始化植物卡片"""
        plants = [
            {"name": "sunflower", "cost": 50, "type": "support", "cooldown": 7.5},
            {"name": "peashooter", "cost": 100, "type": "attacker", "cooldown": 7.5},
            {"name": "wallnut", "cost": 50, "type": "defense", "cooldown": 7.5},
            {"name": "iceshooter", "cost": 175, "type": "attacker", "cooldown": 7.5},
            {"name": "cherrybomb", "cost": 150, "type": "instant", "cooldown": 7.5},
            {"name": "potatomine", "cost": 25, "type": "instant", "cooldown": 7.5},
        ]
        
        x_pos = 10
        card_width = 120
        for plant in plants:
            card = PlantCard(x_pos, HEIGHT - 110, card_width, 100, plant)
            self.plant_cards.append(card)
            x_pos += card_width + 5
    
    def get_grid_pos(self, x, y):
        """将屏幕坐标转换为网格坐标"""
        col = (x - GRID_OFFSET_X) // CELL_SIZE
        row = y // CELL_SIZE
        if 0 <= col < GRID_WIDTH and 0 <= row < GRID_HEIGHT:
            return (row, col)
        return None
    
    def spawn_sunlight(self, x=None, y=None):
        """生成阳光"""
        if x is None:
            x = random.randint(50, WIDTH - 150)
            y = 0
        self.sunlights.append(Sunlight(x, y))
    
    def spawn_zombie(self):
        """生成僵尸"""
        row = random.randint(0, GRID_HEIGHT - 1)
        zombie = Zombie(WIDTH, row * CELL_SIZE + CELL_SIZE//2)
        self.zombies.append(zombie)
    
    def plant_selected_plant(self, row, col):
        """种植选中的植物"""
        if self.selected_plant and self.grid[row][col] is None:
            plant_type = self.selected_plant
            card = self.get_plant_card(plant_type)
            
            if card and self.sun_score >= card.cost and card.can_use():
                plant_class = {
                    "sunflower": Sunflower,
                    "peashooter": Peashooter,
                    "wallnut": Wallnut,
                    "iceshooter": IceShooter,
                    "cherrybomb": CherryBomb,
                    "potatomine": PotatoMine,
                }.get(plant_type)
                
                if plant_class:
                    plant = plant_class(col * CELL_SIZE + GRID_OFFSET_X, row * CELL_SIZE)
                    self.grid[row][col] = plant
                    self.sun_score -= card.cost
                    card.use()
                    self.selected_plant = None
                    self.show_message(f"种植了{self.get_plant_name(plant_type)}")
                    return True
        return False
    
    def get_plant_name(self, plant_type):
        """获取植物中文名称"""
        names = {
            "sunflower": "向日葵",
            "peashooter": "豌豆射手", 
            "wallnut": "坚果墙",
            "iceshooter": "寒冰射手",
            "cherrybomb": "樱桃炸弹",
            "potatomine": "土豆地雷"
        }
        return names.get(plant_type, plant_type)
    
    def get_plant_card(self, plant_name):
        """获取植物卡片"""
        for card in self.plant_cards:
            if card.plant_name == plant_name:
                return card
        return None
    
    def collect_sunlight(self, x, y):
        """收集阳光"""
        for sunlight in self.sunlights[:]:
            if sunlight.rect.collidepoint(x, y):
                self.sun_score += sunlight.value
                self.sunlights.remove(sunlight)
                return True
        return False
    
    def explode_at(self, x, y, radius, damage):
        """在指定位置产生爆炸效果"""
        # 创建爆炸效果
        self.explosions.append(Explosion(x, y))
        
        # 对范围内的僵尸造成伤害
        for zombie in self.zombies[:]:
            distance = math.sqrt((zombie.x - x)**2 + (zombie.y - y)**2)
            if distance <= radius:
                zombie.take_damage(damage)
    
    def show_message(self, text):
        """显示消息"""
        self.message = text
        self.message_timer = time.time()
    
    def update(self):
        if self.game_over or self.won:
            return
        
        current_time = time.time()
        self.delta_time = current_time - self.last_update
        self.last_update = current_time
        
        # 清除过期消息
        if self.message and current_time - self.message_timer > 2:
            self.message = ""
        
        # 自动生成阳光
        if current_time - self.last_sun_spawn > self.sun_spawn_delay:
            self.spawn_sunlight()
            self.last_sun_spawn = current_time
        
        # 生成僵尸（波次系统）
        if current_time - self.last_zombie_spawn > self.zombie_spawn_delay:
            num_zombies = min(self.wave, 3)
            for _ in range(num_zombies):
                self.spawn_zombie()
            self.last_zombie_spawn = current_time
            self.zombie_spawn_delay = max(1.5, 5.0 - self.wave * 0.4)
        
        # 更新植物卡片冷却
        for card in self.plant_cards:
            card.update(self.delta_time)
        
        # 更新所有植物
        for row in range(GRID_HEIGHT):
            for col in range(GRID_WIDTH):
                plant = self.grid[row][col]
                if plant:
                    plant.update(self, row, col)
                    
                    # 攻击型植物发射子弹
                    if hasattr(plant, 'can_shoot') and plant.can_shoot():
                        projectiles = plant.shoot()
                        if projectiles:
                            for projectile in projectiles:
                                if projectile:
                                    self.projectiles.append(projectile)
        
        # 更新所有僵尸
        for zombie in self.zombies[:]:
            zombie.update(self)
            
            # 检查僵尸是否到达房子
            if zombie.x < GRID_OFFSET_X - 20:
                self.game_over = True
                self.show_message("僵尸进入了你的房子！")
                break
            
            # 检查僵尸是否死亡
            if zombie.health <= 0:
                self.zombies.remove(zombie)
                self.zombies_killed += 1
                if self.zombies_killed >= self.wave * 5:
                    self.wave += 1
                    self.zombies_killed = 0
                    self.show_message(f"第{self.wave}波开始！")
        
        # 更新所有子弹
        for projectile in self.projectiles[:]:
            projectile.update()
            
            hit_zombie = False
            for zombie in self.zombies:
                if (abs(projectile.y - zombie.y) < 30 and
                    abs(projectile.x - zombie.x) < 30):
                    zombie.take_damage(projectile.damage, projectile.effect)
                    hit_zombie = True
                    break
            
            if hit_zombie or projectile.x > WIDTH or projectile.x < 0:
                if projectile in self.projectiles:
                    self.projectiles.remove(projectile)
        
        # 更新所有阳光
        for sunlight in self.sunlights[:]:
            sunlight.update()
            if sunlight.y > HEIGHT:
                self.sunlights.remove(sunlight)
        
        # 更新爆炸效果
        for explosion in self.explosions[:]:
            if not explosion.update():
                self.explosions.remove(explosion)
        
        # 检查胜利条件
        if current_time - self.start_time > 180:  # 3分钟
            self.won = True
            self.show_message("恭喜！你成功抵御了所有僵尸！")
    
    def draw(self):
        # 绘制背景
        screen.fill(BACKGROUND)
        
        # 绘制网格背景
        for row in range(GRID_HEIGHT):
            for col in range(GRID_WIDTH):
                rect = pygame.Rect(GRID_OFFSET_X + col * CELL_SIZE, row * CELL_SIZE, CELL_SIZE, CELL_SIZE)
                pygame.draw.rect(screen, (50, 140, 50), rect)
                pygame.draw.rect(screen, GRID_LINE, rect, 1)
        
        # 绘制房子（左侧）
        pygame.draw.rect(screen, (120, 80, 50), (30, 50, 60, HEIGHT-100))
        pygame.draw.rect(screen, (140, 100, 70), (35, 55, 50, HEIGHT-110))
        house_text = font_medium.render("家", True, WHITE)
        screen.blit(house_text, (50, HEIGHT//2-10))
        
        # 绘制所有游戏元素
        for sunlight in self.sunlights:
            sunlight.draw(screen)
        
        for projectile in self.projectiles:
            projectile.draw(screen)
        
        for explosion in self.explosions:
            explosion.draw(screen)
        
        for zombie in self.zombies:
            zombie.draw(screen)
        
        # 绘制植物
        for row in range(GRID_HEIGHT):
            for col in range(GRID_WIDTH):
                plant = self.grid[row][col]
                if plant:
                    plant.draw(screen)
        
        # 绘制UI面板
        pygame.draw.rect(screen, UI_BG, (0, GRID_HEIGHT * CELL_SIZE, WIDTH, HEIGHT - GRID_HEIGHT * CELL_SIZE))
        pygame.draw.line(screen, UI_BORDER, (0, GRID_HEIGHT * CELL_SIZE), (WIDTH, GRID_HEIGHT * CELL_SIZE), 3)
        
        # 绘制植物卡片
        for card in self.plant_cards:
            card.draw(screen, self.sun_score, self.selected_plant)
        
        # 绘制阳光计数
        sun_icon = font_medium.render("☀", True, SUN_COLOR)
        screen.blit(sun_icon, (WIDTH - 150, HEIGHT - 90))
        sun_text = font_medium.render(f": {self.sun_score}", True, WHITE)
        screen.blit(sun_text, (WIDTH - 120, HEIGHT - 90))
        
        # 绘制波次信息
        wave_text = font_medium.render(f"波次: {self.wave}", True, WHITE)
        screen.blit(wave_text, (WIDTH - 150, HEIGHT - 50))
        
        # 绘制消息
        if self.message:
            msg_surface = pygame.Surface((WIDTH, 30), pygame.SRCALPHA)
            msg_surface.fill((0, 0, 0, 150))
            screen.blit(msg_surface, (0, 0))
            
            msg_text = font_medium.render(self.message, True, YELLOW)
            screen.blit(msg_text, (WIDTH//2 - msg_text.get_width()//2, 0))
        
        # 绘制操作说明
        help_text = [
            "点击植物卡片选择植物 → 点击网格种植",
            "点击阳光收集阳光  R: 重新开始  ESC: 退出"
        ]
        
        for i, text in enumerate(help_text):
            help_surface = font_small.render(text, True, (200, 200, 255))
            screen.blit(help_surface, (WIDTH//2 - 200, HEIGHT - 40 + i * 20))
        
        # 游戏结束画面
        if self.game_over:
            self.draw_game_over()
        
        # 游戏胜利画面
        if self.won:
            self.draw_victory()
    
    def draw_game_over(self):
        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 - game_over_text.get_width()//2, HEIGHT//2 - 50))
        
        score_text = font_medium.render(f"坚持波次: {self.wave}  击杀: {self.zombies_killed}", True, YELLOW)
        screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, HEIGHT//2))
        
        restart_text = font_medium.render("按R重新开始，ESC退出", True, WHITE)
        screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 50))
    
    def draw_victory(self):
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 200))
        screen.blit(overlay, (0, 0))
        
        win_text = font_large.render("恭喜胜利! 成功抵御僵尸3分钟!", True, (0, 255, 0))
        screen.blit(win_text, (WIDTH//2 - win_text.get_width()//2, HEIGHT//2 - 50))
        
        wave_text = font_medium.render(f"最终波次: {self.wave}  击杀: {self.zombies_killed}", True, YELLOW)
        screen.blit(wave_text, (WIDTH//2 - wave_text.get_width()//2, HEIGHT//2))
        
        restart_text = font_medium.render("按R重新开始，ESC退出", True, WHITE)
        screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 50))

# 植物卡片类
class PlantCard:
    def __init__(self, x, y, width, height, plant_info):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.plant_name = plant_info["name"]
        self.cost = plant_info["cost"]
        self.plant_type = plant_info["type"]
        self.max_cooldown = plant_info["cooldown"]
        self.current_cooldown = 0
        self.rect = pygame.Rect(x, y, width, height)
        
        # 植物颜色映射 - 修复这里！
        self.colors = {
            "sunflower": YELLOW,  # 使用YELLOW而不是SUNFLOWER_COLOR
            "peashooter": PLANT_GREEN,
            "wallnut": BROWN,
            "iceshooter": ICE_BLUE,
            "cherrybomb": RED,
            "potatomine": (120, 80, 40)
        }
    
    def update(self, delta_time):
        if self.current_cooldown > 0:
            self.current_cooldown = max(0, self.current_cooldown - delta_time)
    
    def can_use(self):
        return self.current_cooldown <= 0
    
    def use(self):
        self.current_cooldown = self.max_cooldown
    
    def draw(self, screen, sun_score, selected_plant):
        # 卡片背景
        card_color = self.colors.get(self.plant_name, (100, 100, 100))
        
        if sun_score < self.cost:
            card_color = tuple(max(50, c-100) for c in card_color)  # 变暗
        
        if selected_plant == self.plant_name:
            pygame.draw.rect(screen, (255, 255, 200), self.rect, 3, border_radius=8)
        
        pygame.draw.rect(screen, card_color, self.rect, border_radius=8)
        pygame.draw.rect(screen, UI_BORDER, self.rect, 2, border_radius=8)
        
        # 绘制冷却覆盖
        if self.current_cooldown > 0:
            cooldown_height = (self.current_cooldown / self.max_cooldown) * self.height
            overlay = pygame.Surface((self.width, int(cooldown_height)), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 150))
            screen.blit(overlay, (self.x, self.y + self.height - cooldown_height))
            
            # 绘制冷却时间
            time_left = int(self.current_cooldown)
            if time_left > 0:
                cooldown_text = font_medium.render(str(time_left), True, WHITE)
                screen.blit(cooldown_text, (self.x + self.width//2 - 10, self.y + self.height//2 - 10))
        
        # 绘制植物图标
        self.draw_plant_icon(screen)
        
        # 绘制花费
        cost_color = SUN_COLOR if sun_score >= self.cost else (150, 150, 150)
        cost_text = font_small.render(str(self.cost), True, cost_color)
        screen.blit(cost_text, (self.x + 5, self.y + 5))
        
        # 绘制植物名称
        name_abbr = {
            "sunflower": "向日葵",
            "peashooter": "豌豆射手", 
            "wallnut": "坚果墙",
            "iceshooter": "寒冰射手",
            "cherrybomb": "樱桃炸弹",
            "potatomine": "土豆地雷"
        }.get(self.plant_name, "??")
        
        name_text = font_tiny.render(name_abbr, True, WHITE)
        screen.blit(name_text, (self.x + self.width//2 - name_text.get_width()//2, self.y + self.height - 20))
    
    def draw_plant_icon(self, screen):
        center_x = self.x + self.width // 2
        center_y = self.y + self.height // 2 - 10
        
        if self.plant_name == "sunflower":
            # 向日葵图标
            pygame.draw.circle(screen, YELLOW, (center_x, center_y), 20)  # 使用YELLOW
            pygame.draw.circle(screen, ORANGE, (center_x, center_y), 12)
        elif self.plant_name == "peashooter":
            # 豌豆射手图标
            pygame.draw.ellipse(screen, PLANT_GREEN, (center_x-15, center_y-10, 30, 20))
            pygame.draw.circle(screen, PEA_COLOR, (center_x + 10, center_y), 5)
        elif self.plant_name == "wallnut":
            # 坚果墙图标
            pygame.draw.circle(screen, BROWN, (center_x, center_y), 15)
            pygame.draw.line(screen, (100, 60, 30), 
                           (center_x - 8, center_y - 4),
                           (center_x + 8, center_y + 6), 3)
        elif self.plant_name == "iceshooter":
            # 寒冰射手图标
            pygame.draw.ellipse(screen, ICE_BLUE, (center_x-15, center_y-10, 30, 20))
            pygame.draw.circle(screen, BLUE, (center_x + 10, center_y), 5)
        elif self.plant_name == "cherrybomb":
            # 樱桃炸弹图标
            pygame.draw.circle(screen, RED, (center_x - 6, center_y), 10)
            pygame.draw.circle(screen, RED, (center_x + 6, center_y), 10)
        elif self.plant_name == "potatomine":
            # 土豆地雷图标
            pygame.draw.ellipse(screen, (120, 80, 40), (center_x-10, center_y-8, 20, 16))

# 植物基类
class Plant:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = CELL_SIZE - 10
        self.height = CELL_SIZE - 10
        self.health = 100
        self.max_health = 100
        self.plant_time = time.time()
        
    def draw(self, screen):
        # 绘制生命条
        if self.health < self.max_health:
            bar_width = 40
            bar_height = 6
            bar_x = self.x + (CELL_SIZE - bar_width) // 2
            bar_y = self.y - 10
            
            # 背景条
            pygame.draw.rect(screen, (100, 0, 0), (bar_x, bar_y, bar_width, bar_height))
            # 生命条
            health_width = int(bar_width * (self.health / self.max_health))
            pygame.draw.rect(screen, (0, 200, 0), (bar_x, bar_y, health_width, bar_height))

# 向日葵
class Sunflower(Plant):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.last_production = time.time()
        self.production_delay = 10.0
        
    def draw(self, screen):
        # 绘制花盘
        pygame.draw.circle(screen, YELLOW,  # 使用YELLOW
                         (int(self.x + CELL_SIZE//2), int(self.y + CELL_SIZE//2)), 25)
        
        # 绘制花瓣
        for i in range(12):
            angle = i * math.pi / 6
            petal_x = self.x + CELL_SIZE//2 + math.cos(angle) * 35
            petal_y = self.y + CELL_SIZE//2 + math.sin(angle) * 35
            pygame.draw.ellipse(screen, (255, 200, 0),
                              (petal_x - 10, petal_y - 6, 20, 12))
        
        # 绘制中心
        pygame.draw.circle(screen, (200, 150, 0),
                         (int(self.x + CELL_SIZE//2), int(self.y + CELL_SIZE//2)), 12)
        
        super().draw(screen)
    
    def update(self, game, row, col):
        current_time = time.time()
        if current_time - self.last_production > self.production_delay:
            sun_x = self.x + random.randint(-20, 20)
            sun_y = self.y + random.randint(-20, 20)
            game.spawn_sunlight(sun_x, sun_y)
            self.last_production = current_time

# 豌豆射手
class Peashooter(Plant):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.shoot_timer = time.time()
        self.shoot_delay = 2.0
        
    def draw(self, screen):
        # 绘制植物主体
        pygame.draw.ellipse(screen, PLANT_GREEN, 
                          (self.x + 10, self.y + 10, self.width, self.height))
        
        # 绘制"嘴巴"
        pygame.draw.arc(screen, BLACK, 
                       (self.x + 40, self.y + 20, 30, 40),
                       math.pi/4, 3*math.pi/4, 2)
        
        # 绘制叶子
        pygame.draw.ellipse(screen, (30, 180, 30),
                          (self.x, self.y + 30, 20, 20))
        pygame.draw.ellipse(screen, (30, 180, 30),
                          (self.x + 60, self.y + 30, 20, 20))
        
        super().draw(screen)
    
    def can_shoot(self):
        return time.time() - self.shoot_timer > self.shoot_delay
    
    def shoot(self):
        if self.can_shoot():
            self.shoot_timer = time.time()
            return [Pea(self.x + CELL_SIZE, self.y + CELL_SIZE//2, "normal")]
        return []

# 寒冰射手
class IceShooter(Peashooter):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.shoot_delay = 2.5
    
    def draw(self, screen):
        # 绘制植物主体
        pygame.draw.ellipse(screen, ICE_BLUE, 
                          (self.x + 10, self.y + 10, self.width, self.height))
        
        # 绘制"嘴巴"
        pygame.draw.arc(screen, (100, 100, 200), 
                       (self.x + 40, self.y + 20, 30, 40),
                       math.pi/4, 3*math.pi/4, 2)
        
        # 绘制叶子
        pygame.draw.ellipse(screen, (100, 180, 220),
                          (self.x, self.y + 30, 20, 20))
        pygame.draw.ellipse(screen, (100, 180, 220),
                          (self.x + 60, self.y + 30, 20, 20))
        
        super().draw(screen)
    
    def shoot(self):
        if self.can_shoot():
            self.shoot_timer = time.time()
            return [Pea(self.x + CELL_SIZE, self.y + CELL_SIZE//2, "ice")]

# 坚果墙
class Wallnut(Plant):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.health = 300
        self.max_health = 300
        
    def draw(self, screen):
        # 绘制坚果
        pygame.draw.ellipse(screen, (150, 100, 50),
                          (self.x + 5, self.y + 5, self.width, self.height))
        
        # 绘制纹理
        pygame.draw.ellipse(screen, (120, 80, 40),
                          (self.x + 15, self.y + 15, self.width - 20, self.height - 20))
        
        # 绘制裂缝
        pygame.draw.line(screen, (100, 60, 30),
                        (self.x + 20, self.y + 30),
                        (self.x + 60, self.y + 50), 4)
        pygame.draw.line(screen, (100, 60, 30),
                        (self.x + 40, self.y + 20),
                        (self.x + 50, self.y + 60), 3)
        
        super().draw(screen)
    
    def update(self, game, row, col):
        pass

# 土豆地雷
class PotatoMine(Plant):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.health = 50
        self.armed = False
        self.arm_time = 10.0
        self.explosion_radius = 100
        self.explosion_damage = 1000
        
    def draw(self, screen):
        # 绘制土豆
        if self.armed:
            color = (200, 100, 50)
        else:
            color = (120, 80, 40)
        
        pygame.draw.ellipse(screen, color,
                          (self.x + 10, self.y + 20, self.width - 20, self.height - 40))
        
        # 绘制倒计时
        if not self.armed:
            time_left = int(self.arm_time - (time.time() - self.plant_time))
            if time_left > 0:
                time_text = font_small.render(str(time_left), True, WHITE)
                screen.blit(time_text, (self.x + 35, self.y + 60))
        
        super().draw(screen)
    
    def update(self, game, row, col):
        # 检查是否准备完成
        if not self.armed and time.time() - self.plant_time > self.arm_time:
            self.armed = True
        
        # 检查是否有僵尸在附近
        if self.armed:
            for zombie in game.zombies:
                if (abs(zombie.x - (self.x + CELL_SIZE//2)) < 50 and
                    abs(zombie.y - (self.y + CELL_SIZE//2)) < 50):
                    # 爆炸！
                    game.explode_at(self.x + CELL_SIZE//2, self.y + CELL_SIZE//2, 
                                   self.explosion_radius, self.explosion_damage)
                    self.health = 0
                    break

# 樱桃炸弹
class CherryBomb(Plant):
    def __init__(self, x, y):
        super().__init__(x, y)
        self.health = 50
        self.explosion_timer = 3.0
        self.explosion_radius = 120
        self.explosion_damage = 1000
        
    def draw(self, screen):
        # 绘制樱桃
        pygame.draw.circle(screen, RED, (self.x + 30, self.y + 35), 20)
        pygame.draw.circle(screen, RED, (self.x + 50, self.y + 35), 20)
        
        # 绘制茎
        pygame.draw.line(screen, DARK_GREEN,
                        (self.x + 40, self.y + 20),
                        (self.x + 30, self.y + 35), 3)
        pygame.draw.line(screen, DARK_GREEN,
                        (self.x + 40, self.y + 20),
                        (self.x + 50, self.y + 35), 3)
        
        # 绘制倒计时
        time_left = int(self.explosion_timer - (time.time() - self.plant_time))
        if time_left > 0:
            time_text = font_small.render(str(time_left), True, WHITE)
            screen.blit(time_text, (self.x + 35, self.y + 60))
        
        super().draw(screen)
    
    def update(self, game, row, col):
        # 检查是否爆炸
        if time.time() - self.plant_time > self.explosion_timer:
            game.explode_at(self.x + CELL_SIZE//2, self.y + CELL_SIZE//2,
                          self.explosion_radius, self.explosion_damage)
            self.health = 0

# 豌豆类
class Pea:
    def __init__(self, x, y, effect="normal"):
        self.x = x
        self.y = y
        self.speed = 5
        self.damage = 20
        self.radius = 5
        self.effect = effect
        
        if effect == "normal":
            self.color = PEA_COLOR
        elif effect == "ice":
            self.color = ICE_BLUE
            self.damage = 15
        
    def update(self):
        self.x += self.speed
        
    def draw(self, screen):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
        
        if self.effect == "ice":
            pygame.draw.circle(screen, BLUE, (int(self.x), int(self.y)), self.radius-2)

# 阳光类
class Sunlight:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.value = 25
        self.speed = 1
        self.creation_time = time.time()
        self.float_offset = random.random() * math.pi * 2
        self.rect = pygame.Rect(x-20, y-20, 40, 40)
        
    def update(self):
        self.y += self.speed
        self.rect.y = int(self.y) - 20
        
        # 上下浮动效果
        self.y += math.sin(time.time() * 3 + self.float_offset) * 0.5
        
    def draw(self, screen):
        # 绘制阳光
        pygame.draw.circle(screen, SUN_COLOR, (int(self.x), int(self.y)), 20)
        
        # 绘制光芒
        for i in range(8):
            angle = i * math.pi / 4
            start_x = self.x + math.cos(angle) * 20
            start_y = self.y + math.sin(angle) * 20
            end_x = self.x + math.cos(angle) * 30
            end_y = self.y + math.sin(angle) * 30
            pygame.draw.line(screen, SUN_COLOR, 
                           (start_x, start_y), 
                           (end_x, end_y), 3)
        
        # 绘制阳光值
        value_text = font_small.render(str(self.value), True, BLACK)
        screen.blit(value_text, (self.x - 10, self.y - 8))

# 僵尸类
class Zombie:
    def __init__(self, x, y, zombie_type="normal"):
        self.x = x
        self.y = y
        self.zombie_type = zombie_type
        self.speed = 0.5
        self.health = 100
        self.max_health = 100
        self.width = 40
        self.height = 60
        self.last_attack = 0
        self.attack_delay = 1.0
        self.slow_timer = 0
        
    def update(self, game):
        # 减速效果
        current_speed = self.speed
        if time.time() - self.slow_timer < 2.0:
            current_speed *= 0.5
        
        # 检查前方是否有植物
        row = int(self.y // CELL_SIZE)
        col = int((self.x - GRID_OFFSET_X) // CELL_SIZE)
        
        plant_ahead = None
        if 0 <= col < GRID_WIDTH and 0 <= row < GRID_HEIGHT:
            plant_ahead = game.grid[row][col]
        
        if plant_ahead and self.x - plant_ahead.x < 50:
            # 攻击植物
            current_time = time.time()
            if current_time - self.last_attack > self.attack_delay:
                plant_ahead.health -= 20
                self.last_attack = current_time
                
                if plant_ahead.health <= 0:
                    game.grid[row][col] = None
        else:
            # 移动
            self.x -= current_speed
    
    def take_damage(self, amount, effect=None):
        self.health -= amount
        
        if effect == "ice":
            self.slow_timer = time.time()
    
    def draw(self, screen):
        # 绘制身体
        body_color = ZOMBIE_SKIN
        pygame.draw.rect(screen, body_color, 
                        (int(self.x - 20), int(self.y - 30), 40, 60))
        
        # 绘制头部
        head_color = ZOMBIE_GREEN
        pygame.draw.circle(screen, head_color, 
                         (int(self.x), int(self.y - 40)), 20)
        
        # 绘制眼睛
        pygame.draw.circle(screen, RED, (int(self.x - 8), int(self.y - 45)), 6)
        pygame.draw.circle(screen, RED, (int(self.x + 8), int(self.y - 45)), 6)
        pygame.draw.circle(screen, BLACK, (int(self.x - 8), int(self.y - 45)), 3)
        pygame.draw.circle(screen, BLACK, (int(self.x + 8), int(self.y - 45)), 3)
        
        # 绘制嘴巴
        pygame.draw.arc(screen, BLACK, 
                       (self.x - 15, self.y - 35, 30, 20),
                       math.pi/6, 5*math.pi/6, 2)
        
        # 绘制衣服
        pygame.draw.rect(screen, (80, 80, 120), 
                        (int(self.x - 15), int(self.y - 20), 30, 20))
        
        # 绘制手臂
        pygame.draw.rect(screen, body_color, 
                        (int(self.x - 30), int(self.y - 20), 10, 30))
        pygame.draw.rect(screen, body_color, 
                        (int(self.x + 20), int(self.y - 20), 10, 30))
        
        # 绘制生命条
        if self.health < self.max_health:
            bar_width = 40
            bar_height = 6
            bar_x = self.x - bar_width // 2
            bar_y = self.y - 60
            
            pygame.draw.rect(screen, (100, 0, 0), (int(bar_x), int(bar_y), bar_width, bar_height))
            health_width = int(bar_width * (self.health / self.max_health))
            health_color = (0, 200, 0)
            if time.time() - self.slow_timer < 2.0:
                health_color = (100, 200, 255)
            pygame.draw.rect(screen, health_color, (int(bar_x), int(bar_y), health_width, bar_height))

# 爆炸效果类
class Explosion:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 5
        self.max_radius = 60
        self.growth_rate = 4
        self.color = (255, 255, 0)
        self.alpha = 255
        
    def update(self):
        self.radius += self.growth_rate
        self.alpha -= 10
        return self.alpha > 0
        
    def draw(self, screen):
        surface = pygame.Surface((self.max_radius*2, self.max_radius*2), pygame.SRCALPHA)
        pygame.draw.circle(surface, (*self.color, self.alpha), 
                         (self.max_radius, self.max_radius), int(self.radius))
        pygame.draw.circle(surface, (255, 0, 0, self.alpha), 
                         (self.max_radius, self.max_radius), int(self.radius) - 10)
        screen.blit(surface, (int(self.x - self.max_radius), int(self.y - self.max_radius)))

# 主游戏循环
def main():
    print("=" * 60)
    print("植物大战僵尸 - 修复版")
    print("=" * 60)
    print("游戏说明:")
    print("1. 点击植物卡片选择植物")
    print("2. 点击网格中的空地种植植物")
    print("3. 点击阳光收集阳光（每个25阳光）")
    print("4. 保护左侧的房子不被僵尸入侵")
    print("5. 目标: 存活3分钟")
    print("=" * 60)
    print("植物类型:")
    print("- 向日葵 (50阳光): 定期产生阳光")
    print("- 豌豆射手 (100阳光): 发射豌豆攻击")
    print("- 坚果墙 (50阳光): 高生命值防御")
    print("- 寒冰射手 (175阳光): 发射冰冻豌豆减速僵尸")
    print("- 樱桃炸弹 (150阳光): 3秒后大范围爆炸")
    print("- 土豆地雷 (25阳光): 10秒后准备完成，僵尸靠近爆炸")
    print("=" * 60)
    
    game = Game()
    running = True
    
    # 主游戏循环
    while running:
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_r and (game.game_over or game.won):
                    # 重新开始游戏
                    game = Game()
                    print("游戏重新开始")
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    x, y = pygame.mouse.get_pos()
                    
                    # 检查是否点击了植物卡片
                    for card in game.plant_cards:
                        if card.rect.collidepoint(x, y) and game.sun_score >= card.cost and card.can_use():
                            game.selected_plant = card.plant_name
                            print(f"选择了: {game.get_plant_name(card.plant_name)}")
                            break
                    
                    # 检查是否点击了网格
                    grid_pos = game.get_grid_pos(x, y)
                    if grid_pos:
                        row, col = grid_pos
                        if game.plant_selected_plant(row, col):
                            print(f"在({row}, {col})种植了{game.selected_plant}")
                    
                    # 检查是否点击了阳光
                    for sunlight in game.sunlights[:]:
                        if sunlight.rect.collidepoint(x, y):
                            game.sun_score += sunlight.value
                            game.sunlights.remove(sunlight)
                            print(f"收集了阳光，当前阳光: {game.sun_score}")
                            break
        
        # 更新游戏状态
        game.update()
        
        # 绘制游戏
        game.draw()
        
        # 更新显示
        pygame.display.flip()
        
        # 控制帧率
        game.clock.tick(60)
    
    # 退出游戏
    pygame.quit()
    print("游戏结束")
    sys.exit(0)

# 运行游戏
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"游戏运行时发生错误: {e}")
        print("错误详情:")
        import traceback
        traceback.print_exc()
        input("按回车键退出...")