# -*- coding: utf-8 -*-
"""
植物大战僵尸 - Pygame 简化版
操作：
    - 点击顶部卡片选择植物，再点击草坪种下
    - 点击阳光收集
    - 点击铲子后再点植物可以铲除
    - R 重新开始，ESC 退出
"""
import os
import math
import random
import sys

import pygame

pygame.init()

# ---------------- 基础设置 ----------------
W, H = 1000, 650
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("植物大战僵尸 - Pygame")
clock = pygame.time.Clock()
FPS = 60

# 网格
COLS, ROWS = 9, 5
CELL_W, CELL_H = 90, 100
GRID_X, GRID_Y = 160, 100
GRID_W, GRID_H = COLS * CELL_W, ROWS * CELL_H

# 颜色
C_BG = (58, 40, 24)
C_GRASS1 = (126, 200, 80)
C_GRASS2 = (110, 182, 68)
C_PANEL = (101, 67, 33)
C_PANEL2 = (150, 110, 60)


# ---------------- 字体 ----------------
# 直接查找常见中文字体文件，避开 pygame.font.match_font 在部分环境下
# （如某些打包的 Python）扫描 Windows 字体注册表时的 TypeError bug。
_CANDIDATE_FONTS = [
    # 项目目录优先
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "simhei.ttf"),
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "msyh.ttc"),
    # Windows
    "C:/Windows/Fonts/msyh.ttc",
    "C:/Windows/Fonts/msyhbd.ttc",
    "C:/Windows/Fonts/simhei.ttf",
    "C:/Windows/Fonts/simsun.ttc",
    "C:/Windows/Fonts/simkai.ttf",
    # macOS
    "/System/Library/Fonts/PingFang.ttc",
    "/System/Library/Fonts/STHeiti Light.ttc",
    "/Library/Fonts/Arial Unicode.ttf",
    # Linux
    "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
]


def _find_font():
    for path in _CANDIDATE_FONTS:
        try:
            if os.path.exists(path):
                return path
        except (TypeError, OSError):
            continue
    return None


_FONT_PATH = _find_font()


def get_font(size, bold=False):
    if _FONT_PATH:
        f = pygame.font.Font(_FONT_PATH, size)
    else:
        f = pygame.font.Font(None, size)
    f.set_bold(bold)
    return f


FONT_14 = get_font(14)
FONT_16 = get_font(16)
FONT_20 = get_font(20)
FONT_24 = get_font(24)
FONT_32 = get_font(32, True)
FONT_44 = get_font(44, True)


# ---------------- 工具函数 ----------------
def cell_center(col, row):
    return (GRID_X + col * CELL_W + CELL_W // 2,
            GRID_Y + row * CELL_H + CELL_H // 2)


def pos_to_cell(mx, my):
    if GRID_X <= mx < GRID_X + GRID_W and GRID_Y <= my < GRID_Y + GRID_H:
        return (mx - GRID_X) // CELL_W, (my - GRID_Y) // CELL_H
    return None


# ---------------- 数据 ----------------
PLANT_DATA = {
    'sunflower':  {'cost': 50,  'cd': 7.5,  'hp': 300},
    'peashooter': {'cost': 100, 'cd': 7.5,  'hp': 300},
    'wallnut':    {'cost': 50,  'cd': 20.0, 'hp': 4000},
    'cherrybomb': {'cost': 150, 'cd': 25.0, 'hp': 300},
}

ZOMBIE_DATA = {
    'normal': {'hp': 200,  'speed': 20.0},
    'cone':   {'hp': 560,  'speed': 20.0},
    'bucket': {'hp': 1300, 'speed': 18.0},
}


# ---------------- 植物绘制 ----------------
def draw_plant_shape(surf, kind, x, y, t=0.0, scale=1.0):
    s = scale

    if kind == 'sunflower':
        # 茎 + 叶
        pygame.draw.line(surf, (70, 150, 60), (x, y + 26 * s), (x, y + 2 * s),
                         max(1, int(6 * s)))
        pygame.draw.ellipse(surf, (95, 185, 75),
                            (x - 27 * s, y + 8 * s, 22 * s, 12 * s))
        pygame.draw.ellipse(surf, (95, 185, 75),
                            (x + 5 * s, y + 8 * s, 22 * s, 12 * s))
        # 花瓣
        for i in range(12):
            a = t * 1.5 + i * math.pi / 6
            px = x + math.cos(a) * 19 * s
            py = y - 8 * s + math.sin(a) * 19 * s
            pygame.draw.circle(surf, (255, 205, 50),
                               (int(px), int(py)), max(1, int(10 * s)))
        # 花心
        pygame.draw.circle(surf, (245, 160, 35),
                           (int(x), int(y - 8 * s)), max(1, int(15 * s)))
        pygame.draw.circle(surf, (150, 95, 45),
                           (int(x), int(y - 8 * s)), max(1, int(10 * s)))
        # 眼睛
        pygame.draw.circle(surf, (40, 40, 40),
                           (int(x - 5 * s), int(y - 10 * s)), max(1, int(2.5 * s)))
        pygame.draw.circle(surf, (40, 40, 40),
                           (int(x + 5 * s), int(y - 10 * s)), max(1, int(2.5 * s)))

    elif kind == 'peashooter':
        pygame.draw.line(surf, (70, 150, 60), (x - 2, y + 28 * s), (x - 2, y + 4 * s),
                         max(1, int(6 * s)))
        pygame.draw.ellipse(surf, (95, 185, 75),
                            (x - 28 * s, y + 12 * s, 22 * s, 12 * s))
        # 头
        pygame.draw.circle(surf, (95, 190, 80),
                           (int(x), int(y - 10 * s)), max(1, int(18 * s)))
        # 炮管
        pygame.draw.rect(surf, (80, 170, 70),
                         (x + 8 * s, y - 19 * s, 20 * s, 15 * s),
                         border_radius=max(1, int(6 * s)))
        pygame.draw.circle(surf, (55, 135, 50),
                           (int(x + 27 * s), int(y - 11 * s)), max(1, int(7 * s)))
        # 眼睛
        pygame.draw.circle(surf, (255, 255, 255),
                           (int(x - 2 * s), int(y - 16 * s)), max(1, int(5 * s)))
        pygame.draw.circle(surf, (30, 30, 30),
                           (int(x), int(y - 16 * s)), max(1, int(2.6 * s)))

    elif kind == 'wallnut':
        pygame.draw.ellipse(surf, (205, 155, 85),
                            (x - 23 * s, y - 30 * s, 46 * s, 62 * s))
        pygame.draw.ellipse(surf, (165, 115, 55),
                            (x - 23 * s, y - 30 * s, 46 * s, 62 * s),
                            max(1, int(2 * s)))
        # 眼睛
        pygame.draw.circle(surf, (60, 40, 20),
                           (int(x - 8 * s), int(y - 8 * s)), max(1, int(4 * s)))
        pygame.draw.circle(surf, (60, 40, 20),
                           (int(x + 8 * s), int(y - 8 * s)), max(1, int(4 * s)))
        # 嘴
        pygame.draw.arc(surf, (60, 40, 20),
                        (x - 11 * s, y - 2 * s, 22 * s, 16 * s),
                        math.pi, 2 * math.pi, max(1, int(2 * s)))

    elif kind == 'cherrybomb':
        pygame.draw.circle(surf, (215, 45, 45),
                           (int(x - 10 * s), int(y - 2 * s)), max(1, int(17 * s)))
        pygame.draw.circle(surf, (190, 25, 35),
                           (int(x + 12 * s), int(y + 4 * s)), max(1, int(15 * s)))
        # 茎
        pygame.draw.line(surf, (90, 150, 60),
                         (x - 10 * s, y - 16 * s), (x + 3 * s, y - 30 * s),
                         max(1, int(3 * s)))
        pygame.draw.line(surf, (90, 150, 60),
                         (x + 12 * s, y - 10 * s), (x + 3 * s, y - 30 * s),
                         max(1, int(3 * s)))
        # 眼睛
        pygame.draw.circle(surf, (255, 255, 255),
                           (int(x - 15 * s), int(y - 6 * s)), max(1, int(4 * s)))
        pygame.draw.circle(surf, (255, 255, 255),
                           (int(x - 3 * s), int(y - 2 * s)), max(1, int(4 * s)))
        pygame.draw.circle(surf, (30, 30, 30),
                           (int(x - 15 * s), int(y - 6 * s)), max(1, int(2 * s)))
        pygame.draw.circle(surf, (30, 30, 30),
                           (int(x - 3 * s), int(y - 2 * s)), max(1, int(2 * s)))


# ---------------- 植物 ----------------
class Plant:
    kind = 'plant'

    def __init__(self, col, row):
        self.col = col
        self.row = row
        self.x, self.y = cell_center(col, row)
        d = PLANT_DATA[self.kind]
        self.cost = d['cost']
        self.max_hp = d['hp']
        self.hp = self.max_hp
        self.anim = random.random() * 10
        self.dead = False
        self.flash = 0.0

    def update(self, dt, game):
        self.anim += dt
        if self.flash > 0:
            self.flash -= dt

    def hurt(self, dmg):
        self.hp -= dmg
        self.flash = 0.12
        if self.hp <= 0:
            self.hp = 0
            self.dead = True

    def draw(self, surf):
        draw_plant_shape(surf, self.kind, self.x, self.y, self.anim)
        if self.flash > 0:
            s = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA)
            s.fill((255, 255, 255, 70))
            surf.blit(s, (GRID_X + self.col * CELL_W, GRID_Y + self.row * CELL_H))
        if self.hp < self.max_hp:
            w = 52
            p = max(0.0, self.hp / self.max_hp)
            bx = self.x - w // 2
            by = self.y + 34
            pygame.draw.rect(surf, (50, 50, 50), (bx, by, w, 6), border_radius=3)
            pygame.draw.rect(surf, (90, 220, 90), (bx, by, int(w * p), 6),
                             border_radius=3)


class Sunflower(Plant):
    kind = 'sunflower'

    def __init__(self, col, row):
        super().__init__(col, row)
        self.timer = 5.0

    def update(self, dt, game):
        super().update(dt, game)
        self.timer -= dt
        if self.timer <= 0:
            self.timer = 22.0
            game.suns.append(Sun(self.x + random.randint(-14, 14),
                                 self.y - 16, self.y + 24, 25))


class Peashooter(Plant):
    kind = 'peashooter'

    def __init__(self, col, row):
        super().__init__(col, row)
        self.timer = 1.2

    def update(self, dt, game):
        super().update(dt, game)
        self.timer -= dt
        if self.timer <= 0:
            has = any(z.row == self.row and z.x > self.x - 30 and z.x < W + 60
                      for z in game.zombies)
            if has:
                self.timer = 1.4
                game.peas.append(Pea(self.x + 26, self.y - 14, self.row))
            else:
                self.timer = 0.0


class Wallnut(Plant):
    kind = 'wallnut'


class CherryBomb(Plant):
    kind = 'cherrybomb'

    def __init__(self, col, row):
        super().__init__(col, row)
        self.timer = 0.9
        self.exploded = False

    def update(self, dt, game):
        super().update(dt, game)
        self.timer -= dt
        if self.timer <= 0 and not self.exploded:
            self.exploded = True
            game.explode(self.x, self.y)
            self.dead = True


# ---------------- 子弹 ----------------
class Pea:
    def __init__(self, x, y, row):
        self.x = float(x)
        self.y = float(y)
        self.row = row
        self.speed = 380.0
        self.damage = 20
        self.dead = False
        self.t = 0.0

    def update(self, dt, game):
        self.t += dt
        self.x += self.speed * dt
        if self.x > W + 30:
            self.dead = True
            return
        for z in game.zombies:
            if z.dead:
                continue
            if z.row == self.row and abs(z.x - self.x) < 26:
                if z.y - 58 < self.y < z.y + 48:
                    z.hurt(self.damage)
                    self.dead = True
                    game.effects.append(HitEffect(self.x, self.y))
                    break

    def draw(self, surf):
        pygame.draw.circle(surf, (60, 150, 50), (int(self.x), int(self.y)), 8)
        pygame.draw.circle(surf, (140, 220, 100), (int(self.x) - 2, int(self.y) - 2), 4)


# ---------------- 僵尸 ----------------
class Zombie:
    def __init__(self, row, kind):
        d = ZOMBIE_DATA[kind]
        self.row = row
        self.kind = kind
        self.max_hp = d['hp']
        self.hp = float(self.max_hp)
        self.speed = d['speed']
        self.x = float(W + random.randint(20, 90))
        self.y = cell_center(0, row)[1] + 10
        self.anim = random.random() * 10
        self.dead = False
        self.eating = False
        self.flash = 0.0

    def hurt(self, dmg):
        self.hp -= dmg
        self.flash = 0.08
        if self.hp <= 0:
            self.hp = 0
            self.dead = True

    def update(self, dt, game):
        self.anim += dt
        if self.flash > 0:
            self.flash -= dt

        target = None
        for p in game.plants:
            if p.row != self.row or p.dead:
                continue
            d = p.x - self.x
            if -52 < d < 20:
                if target is None or p.x > target.x:
                    target = p

        if target is not None:
            self.eating = True
            target.hurt(100 * dt)
        else:
            self.eating = False
            self.x -= self.speed * dt

    def draw(self, surf):
        x, y = self.x, self.y
        if self.eating:
            bob = math.sin(self.anim * 16) * 2.5
        else:
            bob = math.sin(self.anim * 7) * 2.5

        # 腿
        pygame.draw.line(surf, (60, 80, 60), (x - 8, y + 22), (x - 11, y + 40), 7)
        pygame.draw.line(surf, (60, 80, 60), (x + 8, y + 22), (x + 12, y + 40), 7)
        # 身体
        body = pygame.Rect(x - 17, y - 14 + bob, 34, 40)
        pygame.draw.rect(surf, (105, 125, 95), body, border_radius=8)
        pygame.draw.rect(surf, (78, 98, 72), (x - 17, y + 8 + bob, 34, 13))
        # 手臂
        arm_y = y - 6 + bob
        pygame.draw.line(surf, (140, 165, 120), (x + 12, arm_y), (x + 31, arm_y + 7), 8)
        pygame.draw.line(surf, (140, 165, 120), (x - 8, arm_y), (x - 25, arm_y + 11), 8)
        # 头
        hy = y - 34 + bob
        pygame.draw.circle(surf, (160, 185, 140), (int(x), int(hy)), 19)
        # 眼睛
        pygame.draw.circle(surf, (240, 240, 230), (int(x - 7), int(hy - 3)), 5)
        pygame.draw.circle(surf, (240, 240, 230), (int(x + 6), int(hy - 3)), 5)
        pygame.draw.circle(surf, (25, 25, 25), (int(x - 8), int(hy - 3)), 2)
        pygame.draw.circle(surf, (25, 25, 25), (int(x + 5), int(hy - 3)), 2)
        # 嘴
        pygame.draw.rect(surf, (70, 40, 40), (x - 9, hy + 8, 18, 6), border_radius=2)
        pygame.draw.line(surf, (240, 240, 230), (x - 4, hy + 8), (x - 4, hy + 13), 2)
        pygame.draw.line(surf, (240, 240, 230), (x + 4, hy + 8), (x + 4, hy + 13), 2)

        # 护具（血量降低后掉落）
        if self.kind == 'bucket' and self.hp > 560:
            pygame.draw.rect(surf, (155, 158, 168),
                             (x - 19, hy - 36, 38, 28), border_radius=5)
            pygame.draw.rect(surf, (105, 108, 118),
                             (x - 19, hy - 36, 38, 28), 3, border_radius=5)
            pygame.draw.line(surf, (200, 205, 215),
                             (x - 14, hy - 32), (x - 14, hy - 12), 3)
        elif (self.kind == 'cone' and self.hp > 200) or \
             (self.kind == 'bucket' and 200 < self.hp <= 560):
            pts = [(x - 16, hy - 12), (x + 16, hy - 12), (x, hy - 44)]
            pygame.draw.polygon(surf, (225, 125, 35), pts)
            pygame.draw.polygon(surf, (175, 85, 20), pts, 3)

        # 受击白闪
        if self.flash > 0:
            s = pygame.Surface((60, 100), pygame.SRCALPHA)
            s.fill((255, 255, 255, 90))
            surf.blit(s, (x - 30, y - 60))

        # 血条
        if self.hp < self.max_hp:
            w = 44
            p = max(0.0, self.hp / self.max_hp)
            bx = x - w // 2
            by = y - 66
            pygame.draw.rect(surf, (50, 50, 50), (bx, by, w, 5), border_radius=2)
            col = (230, 70, 70) if p > 0.35 else (255, 140, 40)
            pygame.draw.rect(surf, col, (bx, by, int(w * p), 5), border_radius=2)


# ---------------- 阳光 ----------------
class Sun:
    def __init__(self, x, y, ty, value=25):
        self.x = float(x)
        self.y = float(y)
        self.ty = float(ty)
        self.value = value
        self.landed = False
        self.dead = False
        self.t = random.random() * 10
        self.life = 12.0

    def update(self, dt):
        self.t += dt
        if not self.landed:
            self.y += 55 * dt
            if self.y >= self.ty:
                self.y = self.ty
                self.landed = True
                self.life = 10.0
        else:
            self.life -= dt
            if self.life <= 0:
                self.dead = True

    def draw(self, surf):
        pulse = 1.0 + math.sin(self.t * 3) * 0.08
        r = max(1, int(22 * pulse))
        glow = pygame.Surface((r * 5, r * 5), pygame.SRCALPHA)
        pygame.draw.circle(glow, (255, 220, 80, 55),
                           (r * 2 + r // 2, r * 2 + r // 2), int(r * 1.9))
        pygame.draw.circle(glow, (255, 235, 120, 120),
                           (r * 2 + r // 2, r * 2 + r // 2), int(r * 1.3))
        surf.blit(glow, (self.x - r * 2 - r // 2, self.y - r * 2 - r // 2))
        pygame.draw.circle(surf, (250, 195, 40), (int(self.x), int(self.y)), r)
        pygame.draw.circle(surf, (255, 248, 170), (int(self.x), int(self.y)),
                           max(1, int(r * 0.68)))


# ---------------- 特效 ----------------
class HitEffect:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.t = 0.0
        self.life = 0.18

    def update(self, dt):
        self.t += dt
        return self.t >= self.life

    def draw(self, surf):
        p = min(1.0, self.t / self.life)
        r = max(1, int(4 + 12 * p))
        a = int(200 * (1 - p))
        s = pygame.Surface((r * 2 + 2, r * 2 + 2), pygame.SRCALPHA)
        pygame.draw.circle(s, (200, 255, 120, a), (r + 1, r + 1), r)
        surf.blit(s, (self.x - r - 1, self.y - r - 1))


class Explosion:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.t = 0.0
        self.life = 0.55

    def update(self, dt):
        self.t += dt
        return self.t >= self.life

    def draw(self, surf):
        p = min(1.0, self.t / self.life)
        r = max(1, int(40 + 110 * p))
        a = int(230 * (1 - p))
        s = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
        pygame.draw.circle(s, (255, 140, 30, a), (r, r), r)
        pygame.draw.circle(s, (255, 220, 90, a), (r, r), max(1, int(r * 0.66)))
        pygame.draw.circle(s, (255, 255, 220, a), (r, r), max(1, int(r * 0.33)))
        surf.blit(s, (self.x - r, self.y - r))


# ---------------- 卡片 ----------------
class Card:
    def __init__(self, cls, x, y):
        self.cls = cls
        self.x = x
        self.y = y
        self.w = 68
        self.h = 74
        data = PLANT_DATA[cls.kind]
        # 关键修复：从 PLANT_DATA 读取 cost / cd，不再依赖 cls 上的实例属性
        self.cost = data['cost']
        self.cd = 0.0
        self.cd_max = data['cd']

    def rect(self):
        return pygame.Rect(self.x, self.y, self.w, self.h)

    def draw(self, surf, sun, selected):
        r = self.rect()
        usable = (self.cd <= 0) and (sun >= self.cost)
        bg = (226, 205, 155) if usable else (150, 142, 125)
        pygame.draw.rect(surf, bg, r, border_radius=6)
        pygame.draw.rect(surf, (95, 65, 32), r, 2, border_radius=6)

        draw_plant_shape(surf, self.cls.kind, r.centerx, r.y + 32, 0.0, scale=0.6)

        txt = FONT_16.render(str(self.cost), True,
                             (25, 25, 25) if usable else (90, 90, 90))
        surf.blit(txt, (r.centerx - txt.get_width() // 2, r.bottom - 21))

        if self.cd > 0:
            h = int(self.h * (self.cd / self.cd_max))
            mask = pygame.Surface((self.w, h), pygame.SRCALPHA)
            mask.fill((0, 0, 0, 145))
            surf.blit(mask, (r.x, r.y))

        if selected:
            pygame.draw.rect(surf, (255, 245, 60), r, 3, border_radius=6)


# ---------------- 游戏主体 ----------------
class Game:
    def __init__(self):
        self.reset()

    def reset(self):
        self.sun = 100
        self.plants = []
        self.zombies = []
        self.peas = []
        self.suns = []
        self.effects = []
        self.selected = None
        self.shovel = False
        self.time = 0.0
        self.spawn_timer = 10.0
        self.sky_timer = 6.0
        self.state = 'playing'
        self.kills = 0

        self.cards = []
        cx = 8
        for cls in (Sunflower, Peashooter, Wallnut, CherryBomb):
            self.cards.append(Card(cls, cx, 8))
            cx += 76
        self.shovel_pos = (cx + 10, 8)
        self.restart_rect = pygame.Rect(W // 2 - 100, H // 2 + 40, 200, 52)

    def shovel_rect(self):
        return pygame.Rect(self.shovel_pos[0], self.shovel_pos[1], 60, 74)

    # ---------- 交互 ----------
    def handle_click(self, pos):
        mx, my = pos

        if self.state == 'lost':
            if self.restart_rect.collidepoint(pos):
                self.reset()
            return

        # 1. 收集阳光
        for s in self.suns:
            if not s.dead and (mx - s.x) ** 2 + (my - s.y) ** 2 < 32 ** 2:
                s.dead = True
                self.sun += s.value
                return

        # 2. 选择卡片
        for c in self.cards:
            if c.rect().collidepoint(pos):
                if c.cd <= 0 and self.sun >= c.cost:
                    self.selected = None if self.selected is c else c
                    self.shovel = False
                return

        # 3. 铲子
        if self.shovel_rect().collidepoint(pos):
            self.shovel = not self.shovel
            self.selected = None
            return

        # 4. 草坪
        cell = pos_to_cell(mx, my)
        if not cell:
            return
        col, row = cell

        if self.shovel:
            for p in self.plants:
                if p.col == col and p.row == row and not p.dead:
                    p.dead = True
                    break
            self.shovel = False
            return

        if self.selected:
            card = self.selected
            occupied = any(p.col == col and p.row == row and not p.dead
                           for p in self.plants)
            if occupied:
                return
            if card.cd <= 0 and self.sun >= card.cost:
                self.sun -= card.cost
                self.plants.append(card.cls(col, row))
                card.cd = card.cd_max
                self.selected = None

    # ---------- 逻辑 ----------
    def spawn_zombie(self):
        t = self.time
        if t < 60:
            kinds = ['normal']
            lo, hi = 8.0, 12.0
        elif t < 130:
            kinds = ['normal', 'normal', 'cone']
            lo, hi = 6.0, 9.0
        elif t < 220:
            kinds = ['normal', 'cone', 'cone', 'bucket']
            lo, hi = 5.0, 7.5
        else:
            kinds = ['normal', 'cone', 'bucket', 'bucket']
            lo, hi = 3.5, 5.5
        self.spawn_timer = random.uniform(lo, hi)
        self.zombies.append(Zombie(random.randint(0, ROWS - 1),
                                   random.choice(kinds)))

    def explode(self, x, y):
        self.effects.append(Explosion(x, y))
        for z in self.zombies:
            if abs(z.x - x) < 135 and abs(z.y - y) < 150:
                z.hurt(1800)

    def update(self, dt):
        for c in self.cards:
            if c.cd > 0:
                c.cd = max(0.0, c.cd - dt)

        self.effects = [e for e in self.effects if not e.update(dt)]

        if self.state != 'playing':
            return

        self.time += dt

        # 天降阳光
        self.sky_timer -= dt
        if self.sky_timer <= 0:
            self.sky_timer = random.uniform(7.0, 11.0)
            x = random.randint(GRID_X + 50, GRID_X + GRID_W - 50)
            ty = random.randint(GRID_Y + 60, GRID_Y + GRID_H - 40)
            self.suns.append(Sun(x, GRID_Y - 70, ty, 25))

        # 生成僵尸
        self.spawn_timer -= dt
        if self.spawn_timer <= 0:
            self.spawn_zombie()

        # 植物
        for p in self.plants:
            p.update(dt, self)
        self.plants = [p for p in self.plants if not p.dead]

        # 僵尸
        for z in self.zombies:
            z.update(dt, self)
        before = len(self.zombies)
        self.zombies = [z for z in self.zombies if not z.dead]
        self.kills += before - len(self.zombies)

        # 子弹
        for pe in self.peas:
            pe.update(dt, self)
        self.peas = [pe for pe in self.peas if not pe.dead]

        # 阳光
        for s in self.suns:
            s.update(dt)
        self.suns = [s for s in self.suns if not s.dead]

        # 失败判定
        for z in self.zombies:
            if z.x < GRID_X - 8:
                self.state = 'lost'
                break

    # ---------- 绘制 ----------
    def draw(self, surf):
        surf.fill(C_BG)

        # 左侧房屋区
        pygame.draw.rect(surf, (108, 78, 52), (0, 0, GRID_X, H))
        for yy in range(0, H, 40):
            pygame.draw.line(surf, (92, 66, 44), (0, yy), (GRID_X, yy), 2)
        pygame.draw.rect(surf, (78, 56, 36), (GRID_X - 8, 0, 8, H))

        # 草坪
        for r in range(ROWS):
            for c in range(COLS):
                color = C_GRASS1 if (r + c) % 2 == 0 else C_GRASS2
                pygame.draw.rect(surf, color,
                                 (GRID_X + c * CELL_W, GRID_Y + r * CELL_H,
                                  CELL_W, CELL_H))

        # 阳光
        for s in self.suns:
            s.draw(surf)

        # 植物
        for p in self.plants:
            p.draw(surf)

        # 子弹
        for pe in self.peas:
            pe.draw(surf)

        # 僵尸（按 y 排序）
        for z in sorted(self.zombies, key=lambda o: o.y):
            z.draw(surf)

        # 特效
        for e in self.effects:
            e.draw(surf)

        self.draw_ui(surf)
        self.draw_preview(surf)

        if self.state == 'lost':
            self.draw_gameover(surf)

    def draw_ui(self, surf):
        pygame.draw.rect(surf, C_PANEL, (0, 0, W, 90))
        pygame.draw.rect(surf, C_PANEL2, (0, 86, W, 4))

        for c in self.cards:
            c.draw(surf, self.sun, self.selected is c)

        # 铲子
        sr = self.shovel_rect()
        pygame.draw.rect(surf, (208, 178, 128), sr, border_radius=6)
        pygame.draw.rect(surf, (95, 65, 32), sr, 2, border_radius=6)
        cx, cy = sr.center
        pygame.draw.line(surf, (140, 92, 42), (cx - 10, cy - 20), (cx + 8, cy + 6), 7)
        pygame.draw.polygon(surf, (195, 200, 208),
                            [(cx + 2, cy + 2), (cx + 18, cy + 14),
                             (cx + 8, cy + 24), (cx - 6, cy + 12)])
        if self.shovel:
            pygame.draw.rect(surf, (255, 245, 60), sr, 3, border_radius=6)

        # 阳光数量
        sx = sr.right + 22
        pygame.draw.circle(surf, (250, 195, 40), (sx + 16, 34), 17)
        pygame.draw.circle(surf, (255, 248, 170), (sx + 16, 34), 11)
        txt = FONT_24.render(str(self.sun), True, (255, 255, 255))
        surf.blit(txt, (sx + 42, 20))

        # 信息
        info = FONT_16.render(
            f"时间 {int(self.time)}s    击杀 {self.kills}    R 重开 / ESC 退出",
            True, (235, 220, 190))
        surf.blit(info, (sx + 42, 54))

    def draw_preview(self, surf):
        mx, my = pygame.mouse.get_pos()
        cell = pos_to_cell(mx, my)

        if self.selected and cell:
            col, row = cell
            occupied = any(p.col == col and p.row == row and not p.dead
                           for p in self.plants)
            s = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA)
            s.fill((255, 60, 60, 70) if occupied else (255, 255, 255, 70))
            surf.blit(s, (GRID_X + col * CELL_W, GRID_Y + row * CELL_H))
            if not occupied:
                cx, cy = cell_center(col, row)
                draw_plant_shape(surf, self.selected.cls.kind, cx, cy, 0.0, 0.85)
        elif self.shovel and cell:
            col, row = cell
            s = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA)
            s.fill((255, 120, 120, 80))
            surf.blit(s, (GRID_X + col * CELL_W, GRID_Y + row * CELL_H))

        # 鼠标跟随的植物
        if self.selected:
            draw_plant_shape(surf, self.selected.cls.kind, mx, my, 0.0, 0.7)

    def draw_gameover(self, surf):
        ov = pygame.Surface((W, H), pygame.SRCALPHA)
        ov.fill((0, 0, 0, 160))
        surf.blit(ov, (0, 0))

        t1 = FONT_44.render("僵尸吃掉了你的脑子！", True, (255, 70, 70))
        surf.blit(t1, (W // 2 - t1.get_width() // 2, H // 2 - 110))

        t2 = FONT_20.render(
            f"存活时间 {int(self.time)} 秒      消灭僵尸 {self.kills} 只",
            True, (245, 245, 245))
        surf.blit(t2, (W // 2 - t2.get_width() // 2, H // 2 - 30))

        pygame.draw.rect(surf, (205, 65, 65), self.restart_rect, border_radius=10)
        pygame.draw.rect(surf, (255, 255, 255), self.restart_rect, 2, border_radius=10)
        t3 = FONT_24.render("重新开始", True, (255, 255, 255))
        surf.blit(t3, (self.restart_rect.centerx - t3.get_width() // 2,
                       self.restart_rect.centery - t3.get_height() // 2))


# ---------------- 主循环 ----------------
def main():
    game = Game()
    running = True

    while running:
        dt = clock.tick(FPS) / 1000.0
        dt = min(dt, 0.05)

        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:
                    game.reset()
                elif event.key == pygame.K_1:
                    game.handle_click(game.cards[0].rect().center)
                elif event.key == pygame.K_2:
                    game.handle_click(game.cards[1].rect().center)
                elif event.key == pygame.K_3:
                    game.handle_click(game.cards[2].rect().center)
                elif event.key == pygame.K_4:
                    game.handle_click(game.cards[3].rect().center)
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                game.handle_click(event.pos)

        game.update(dt)
        game.draw(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()