# -*- coding: utf-8 -*-
"""
植物大战僵尸 (Plants vs. Zombies) - Python/tkinter 版
纯 tkinter 实现，无需第三方依赖。
操作：
  - 上方卡片栏点击选中植物（消耗阳光），再点击草坪格子种植
  - 铲子按钮：点击后点击植物可铲除
  - 收集掉落的阳光
  - 抵御僵尸，别让它们走到房子！
"""
import tkinter as tk
import random
import time

# ---------------- 基本配置 ----------------
COLS = 9
ROWS = 5
CELL_W = 80
CELL_H = 96
LAWN_X = 90          # 草坪起始 x
LAWN_Y = 130         # 草坪起始 y
CARD_Y = 30
WIDTH = LAWN_X + COLS * CELL_W + 20
HEIGHT = LAWN_Y + ROWS * CELL_H + 30

# 颜色
C_LAWN_A = "#7cbb45"
C_LAWN_B = "#6cae3a"
C_GRASS = "#8ec85a"
CARD_BG = "#c8a86a"
CARD_SEL = "#ffe066"
SUN_COLOR = "#ffe600"

# ---------------- 植物定义 ----------------
# cost, hp, cooldown(ms), color, emoji, kind
PLANTS = {
    "sunflower": {"name": "向日葵", "cost": 50,  "hp": 60,  "cd": 5000,  "color": "#ffd21e", "emoji": "🌻", "kind": "sun"},
    "peashooter": {"name": "豌豆射手", "cost": 100, "hp": 60,  "cd": 5000,  "color": "#4caf50", "emoji": "🌱", "kind": "shoot"},
    "wallnut":   {"name": "坚果墙", "cost": 50,  "hp": 400, "cd": 10000, "color": "#c8955b", "emoji": "🥜", "kind": "wall"},
    "repeater":  {"name": "双发射手", "cost": 200, "hp": 60,  "cd": 8000,  "color": "#2e7d32", "emoji": "🌿", "kind": "shoot2"},
    "snowpea":   {"name": "寒冰射手", "cost": 175, "hp": 60,  "cd": 6000,  "color": "#4fc3f7", "emoji": "❄️", "kind": "snow"},
    "cherry":    {"name": "樱桃炸弹", "cost": 150, "hp": 999, "cd": 10000, "color": "#e53935", "emoji": "🍒", "kind": "boom"},
}
CARD_ORDER = ["sunflower", "peashooter", "wallnut", "repeater", "snowpea", "cherry"]

# ---------------- 僵尸定义 ----------------
ZOMBIES = {
    "normal":  {"hp": 100, "speed": 0.25, "color": "#8d6e63", "emoji": "🧟", "dmg": 20, "armor": 0},
    "cone":    {"hp": 100, "speed": 0.25, "color": "#8d6e63", "emoji": "🧟", "dmg": 20, "armor": 80, "acolor": "#ff9800"},
    "bucket":  {"hp": 100, "speed": 0.22, "color": "#8d6e63", "emoji": "🧟", "dmg": 20, "armor": 160, "acolor": "#90a4ae"},
    "fast":    {"hp": 70,  "speed": 0.5,  "color": "#a1887f", "emoji": "🏃", "dmg": 15, "armor": 0},
}

# ================= 游戏主体 =================
class Game:
    def __init__(self, root):
        self.root = root
        self.root.title("植物大战僵尸 · Python版")
        self.root.resized = False
        self.root.geometry(f"{WIDTH}x{HEIGHT}")
        self.root.configure(bg="#2e3d1f")

        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#33502a", highlightthickness=0)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.on_click)
        self.canvas.bind("<Motion>", self.on_hover)

        self.reset_state()
        self.last_time = time.time()
        self.spawn_timer = 0
        self.sun_timer = 0
        self.wave = 0
        self.running = True
        self.hover_cell = None
        self.loop()

    # ---------- 状态初始化 ----------
    def reset_state(self):
        self.sun = 150
        self.plants = {}          # (r,c) -> plant dict
        self.peas = []            # 豌豆
        self.zombies = []         # 僵尸
        self.suns = []            # 阳光下落物
        self.particles = []       # 特效
        self.selected = None      # 选中的植物卡片 key
        self.shovel = False       # 铲子模式
        self.card_cd = {k: 0 for k in PLANTS}   # 冷却结束时间戳
        self.game_over = False
        self.win = False
        self.kills = 0
        self.canvas.delete("all")
        self.draw_static()

    # ---------- 静态绘制 ----------
    def draw_static(self):
        # 顶部栏
        self.canvas.create_rectangle(0, 0, WIDTH, LAWN_Y - 8, fill="#1f2d16", outline="")
        # 卡片
        self.card_rects = {}
        x = 12
        for key in CARD_ORDER:
            p = PLANTS[key]
            rect = self.canvas.create_rectangle(x, CARD_Y, x + 66, CARD_Y + 82, fill=CARD_BG, outline="#5d4a2a", width=2)
            self.canvas.create_text(x + 33, CARD_Y + 20, text=p["emoji"], font=("Segoe UI Emoji", 20))
            self.canvas.create_text(x + 33, CARD_Y + 45, text=p["name"], font=("Microsoft YaHei", 8), fill="#3a2c12")
            cost = self.canvas.create_text(x + 33, CARD_Y + 65, text=f"☀{p['cost']}", font=("Microsoft YaHei", 9, "bold"), fill="#7a3b00")
            self.card_rects[key] = {"rect": rect, "x": x, "cost_txt": cost}
            x += 74
        # 铲子按钮
        self.shovel_rect = self.canvas.create_rectangle(x + 6, CARD_Y, x + 66, CARD_Y + 82, fill="#9e9e9e", outline="#555", width=2)
        self.canvas.create_text(x + 36, CARD_Y + 41, text="🪓", font=("Segoe UI Emoji", 22))
        # 阳光显示
        self.sun_bg = self.canvas.create_rectangle(WIDTH - 96, 8, WIDTH - 8, 40, fill="#3b4d29", outline="#c8a86a", width=2)
        self.sun_text = self.canvas.create_text(WIDTH - 52, 24, text=f"☀ {self.sun}", font=("Microsoft YaHei", 13, "bold"), fill=SUN_COLOR)
        # 波次显示
        self.wave_text = self.canvas.create_text(WIDTH - 52, 58, text="波次 0", font=("Microsoft YaHei", 10), fill="#ddd")
        # 草坪棋盘
        for r in range(ROWS):
            for c in range(COLS):
                x0 = LAWN_X + c * CELL_W
                y0 = LAWN_Y + r * CELL_H
                color = C_LAWN_A if (r + c) % 2 == 0 else C_LAWN_B
                self.canvas.create_rectangle(x0, y0, x0 + CELL_W, y0 + CELL_H, fill=color, outline="#5c8a30", width=1)
        # 房子（右侧）
        self.canvas.create_rectangle(LAWN_X + COLS * CELL_W, LAWN_Y, WIDTH - 4, LAWN_Y + ROWS * CELL_H, fill="#5d4037", outline="")
        self.canvas.create_text(LAWN_X + COLS * CELL_W + 20, LAWN_Y + ROWS * CELL_H // 2, text="🏠", font=("Segoe UI Emoji", 40))

    # ---------- 坐标工具 ----------
    def cell_at(self, px, py):
        if px < LAWN_X or py < LAWN_Y:
            return None
        c = (px - LAWN_X) // CELL_W
        r = (py - LAWN_Y) // CELL_H
        if 0 <= r < ROWS and 0 <= c < COLS:
            return (r, c)
        return None

    def cell_center(self, r, c):
        return (LAWN_X + c * CELL_W + CELL_W // 2, LAWN_Y + r * CELL_H + CELL_H // 2)

    # ---------- 交互 ----------
    def on_hover(self, ev):
        cell = self.cell_at(ev.x, ev.y)
        self.hover_cell = cell

    def on_click(self, ev):
        if self.game_over:
            self.reset_state()
            return
        x, y = ev.x, ev.y

        # 点击卡片
        for key, info in self.card_rects.items():
            ix = info["x"]
            if ix <= x <= ix + 66 and CARD_Y <= y <= CARD_Y + 82:
                self.try_select(key)
                return
        # 铲子
        sx = self.card_rects[CARD_ORDER[-1]]["x"] + 74 + 6
        if sx <= x <= sx + 60 and CARD_Y <= y <= CARD_Y + 82:
            self.shovel = not self.shovel
            self.selected = None
            return

        # 点击阳光
        for s in self.suns:
            if (x - s["x"]) ** 2 + (y - s["y"]) ** 2 <= 22 ** 2:
                self.sun += s["v"]
                self.suns.remove(s)
                return

        # 草坪操作
        cell = self.cell_at(x, y)
        if not cell:
            return
        r, c = cell
        if self.shovel:
            if cell in self.plants:
                del self.plants[cell]
                self.shovel = False
            return
        if self.selected:
            self.try_plant(r, c)

    def try_select(self, key):
        now = time.time()
        if now < self.card_cd[key]:
            return
        if self.sun < PLANTS[key]["cost"]:
            return
        self.selected = key
        self.shovel = False

    def try_plant(self, r, c):
        if (r, c) in self.plants:
            return
        key = self.selected
        p = PLANTS[key]
        if self.sun < p["cost"]:
            return
        self.sun -= p["cost"]
        self.card_cd[key] = time.time() + p["cd"] / 1000
        cx, cy = self.cell_center(r, c)
        self.plants[(r, c)] = {
            "key": key, "kind": p["kind"], "hp": p["hp"], "maxhp": p["hp"],
            "x": cx, "y": cy, "r": r, "c": c,
            "timer": 0, "shot": 0,
        }
        self.selected = None

    # ---------- 生成僵尸 / 阳光 ----------
    def maybe_spawn(self, dt):
        self.spawn_timer -= dt
        # 随波次加快
        interval = max(2.5, 8 - self.wave * 0.4)
        if self.spawn_timer <= 0:
            self.spawn_timer = interval
            self.wave += 1
            row = random.randint(0, ROWS - 1)
            # 选择僵尸类型（波次越高越难）
            pool = ["normal"]
            if self.wave >= 3:
                pool.append("cone")
            if self.wave >= 6:
                pool.append("bucket")
            if self.wave >= 4:
                pool.append("fast")
            ztype = random.choice(pool)
            z = dict(ZOMBIES[ztype])
            z["type"] = ztype
            z["hp"] = z["hp"]
            z["armor"] = z.get("armor", 0)
            z["maxarmor"] = z["armor"]
            z["row"] = row
            z["x"] = WIDTH - 20
            z["y"] = self.cell_center(row, 0)[1]
            z["eat_cd"] = 0
            z["slow"] = 0
            self.zombies.append(z)
            # 每几波来一拨
            if self.wave % 5 == 0:
                for _ in range(2):
                    r2 = random.randint(0, ROWS - 1)
                    zz = dict(ZOMBIES[random.choice(pool)])
                    zz["type"] = "normal"
                    zz["row"] = r2
                    zz["x"] = WIDTH - 20 - random.randint(30, 120)
                    zz["y"] = self.cell_center(r2, 0)[1]
                    zz["eat_cd"] = 0
                    zz["slow"] = 0
                    zz["maxarmor"] = 0
                    self.zombies.append(zz)

    def maybe_sun(self, dt):
        self.sun_timer -= dt
        if self.sun_timer <= 0:
            self.sun_timer = random.uniform(6, 10)
            # 天空阳光
            self.suns.append({
                "x": random.randint(LAWN_X, WIDTH - 60),
                "y": LAWN_Y - 10, "vy": 0.6, "target": None,
                "life": 8, "v": 25,
            })

    # ---------- 主循环 ----------
    def loop(self):
        if not self.running:
            return
        now = time.time()
        dt = now - self.last_time
        self.last_time = now
        if dt > 0.1:
            dt = 0.1
        if not self.game_over:
            self.update(dt)
        self.render()
        self.root.after(30, self.loop)

    def update(self, dt):
        self.maybe_spawn(dt)
        self.maybe_sun(dt)

        # 植物行为
        for (r, c), pl in list(self.plants.items()):
            kind = pl["kind"]
            pl["timer"] += dt
            if kind == "sun" and pl["timer"] >= 6:
                pl["timer"] = 0
                self.suns.append({"x": pl["x"], "y": pl["y"], "vy": 0.4, "target": None, "life": 8, "v": 25})
            elif kind == "shoot" and pl["timer"] >= 1.4:
                if self.zombie_in_row(r, pl["x"]):
                    pl["timer"] = 0
                    self.peas.append({"x": pl["x"] + 20, "y": pl["y"] - 6, "vx": 5.5, "dmg": 20, "slow": 0})
            elif kind == "shoot2" and pl["timer"] >= 1.4:
                if self.zombie_in_row(r, pl["x"]):
                    pl["timer"] = 0
                    self.peas.append({"x": pl["x"] + 20, "y": pl["y"] - 6, "vx": 5.5, "dmg": 20, "slow": 0})
                    self.peas.append({"x": pl["x"] + 12, "y": pl["y"] - 6, "vx": 5.5, "dmg": 20, "slow": 0, "delay": 6})
            elif kind == "snow" and pl["timer"] >= 1.5:
                if self.zombie_in_row(r, pl["x"]):
                    pl["timer"] = 0
                    self.peas.append({"x": pl["x"] + 20, "y": pl["y"] - 6, "vx": 5.0, "dmg": 15, "slow": 3})

        # 樱桃炸弹：种植后立即爆炸（通过 timer 判定）
        for (r, c), pl in list(self.plants.items()):
            if pl["kind"] == "boom" and pl["timer"] >= 0.8 and not pl.get("done"):
                pl["done"] = True
                self.explode(pl["x"], pl["y"], r)
                del self.plants[(r, c)]

        # 豌豆移动
        for p in self.peas:
            if p.get("delay", 0) > 0:
                p["delay"] -= 1
                continue
            p["x"] += p["vx"]
        # 豌豆碰撞
        for p in list(self.peas):
            if p.get("delay", 0) > 0:
                continue
            if p["x"] > WIDTH:
                self.peas.remove(p)
                continue
            for z in self.zombies:
                if abs(z["y"] - p["y"]) < CELL_H // 2 and 0 < p["x"] - z["x"] < 26:
                    self.hurt_zombie(z, p["dmg"])
                    if p["slow"]:
                        z["slow"] = p["slow"]
                    if p in self.peas:
                        self.peas.remove(p)
                    break

        # 僵尸移动 & 吃植物
        for z in self.zombies:
            if z["slow"] > 0:
                z["slow"] -= dt
            speed = z["speed"] * (0.4 if z["slow"] > 0 else 1)
            z["eat_cd"] -= dt
            # 找同行最近植物
            target = None
            best = 9999
            for (r, c), pl in self.plants.items():
                if r == z["row"] and pl["x"] < z["x"]:
                    d = z["x"] - pl["x"]
                    if d < best:
                        best = d
                        target = pl
            if target and best < 45:
                # 吃
                if z["eat_cd"] <= 0:
                    target["hp"] -= z["dmg"]
                    z["eat_cd"] = 0.6
                    if target["hp"] <= 0:
                        key = (target["r"], target["c"])
                        if key in self.plants:
                            del self.plants[key]
            else:
                z["x"] -= speed
            if z["x"] < LAWN_X - 10:
                self.game_over = True
                self.win = False

        # 移除死亡僵尸
        for z in list(self.zombies):
            if z["hp"] <= 0:
                self.zombies.remove(z)
                self.kills += 1
                self.sun += 10  # 击杀奖励

        # 阳光下落
        for s in list(self.suns):
            s["life"] -= dt
            if s["life"] <= 0:
                self.suns.remove(s)
                continue
            if s["y"] < LAWN_Y + ROWS * CELL_H - 40 and s.get("target") is None:
                s["y"] += s["vy"]
                s["vy"] += 0.03
            else:
                s["y"] = min(s["y"], LAWN_Y + ROWS * CELL_H - 40)
        # 粒子
        for pt in list(self.particles):
            pt["x"] += pt["vx"]; pt["y"] += pt["vy"]; pt["vy"] += 0.2; pt["life"] -= dt
            if pt["life"] <= 0:
                self.particles.remove(pt)

        # 胜利判定：存活较久且清场
        if self.wave >= 20 and not self.zombies:
            self.game_over = True
            self.win = True

    def zombie_in_row(self, r, x):
        for z in self.zombies:
            if z["row"] == r and z["x"] > x:
                return True
        return False

    def hurt_zombie(self, z, dmg):
        if z["armor"] > 0:
            z["armor"] -= dmg
            if z["armor"] < 0:
                z["hp"] += z["armor"]  # 溢出伤害
                z["armor"] = 0
        else:
            z["hp"] -= dmg

    def explode(self, x, y, r):
        for z in list(self.zombies):
            if abs(z["row"] - r) <= 1 and abs(z["x"] - x) < CELL_W * 1.5:
                self.hurt_zombie(z, 200)
        for _ in range(24):
            self.particles.append({"x": x, "y": y, "vx": random.uniform(-6, 6), "vy": random.uniform(-7, 2), "life": 0.8, "color": random.choice(["#ff5252", "#ff9800", "#ffeb3b"])})

    # ---------- 渲染 ----------
    def render(self):
        cv = self.canvas
        cv.delete("all")
        # 重绘背景
        self.draw_static()

        # 卡片可用状态 / 冷却遮罩
        now = time.time()
        for key, info in self.card_rects.items():
            ix = info["x"]
            if now < self.card_cd[key]:
                total = PLANTS[key]["cd"] / 1000
                left = (self.card_cd[key] - now) / total
                cv.create_rectangle(ix, CARD_Y + 82 * (1 - left), ix + 66, CARD_Y + 82, fill="#000000", stipple="gray50", outline="")
            if self.sun < PLANTS[key]["cost"]:
                cv.create_rectangle(ix, CARD_Y, ix + 66, CARD_Y + 82, fill="#000000", stipple="gray25", outline="")
        # 选中框
        if self.selected:
            ix = self.card_rects[self.selected]["x"]
            cv.create_rectangle(ix - 2, CARD_Y - 2, ix + 68, CARD_Y + 84, outline=CARD_SEL, width=3)
        if self.shovel:
            sx = self.card_rects[CARD_ORDER[-1]]["x"] + 74 + 6
            cv.create_rectangle(sx - 2, CARD_Y - 2, sx + 62, CARD_Y + 84, outline="#ff5252", width=3)

        # 悬浮格高亮
        if self.hover_cell and not self.game_over:
            r, c = self.hover_cell
            x0 = LAWN_X + c * CELL_W; y0 = LAWN_Y + r * CELL_H
            color = "#ff5252" if (self.shovel and (r, c) in self.plants) or (self.selected and (r, c) in self.plants) else "#ffffff"
            cv.create_rectangle(x0, y0, x0 + CELL_W, y0 + CELL_H, outline=color, width=2)

        # 植物
        for (r, c), pl in self.plants.items():
            p = PLANTS[pl["key"]]
            x, y = pl["x"], pl["y"]
            # 本体
            cv.create_oval(x - 26, y - 20, x + 26, y + 28, fill=p["color"], outline="#2b2b2b", width=2)
            cv.create_text(x, y + 2, text=p["emoji"], font=("Segoe UI Emoji", 24))
            # 血条
            if pl["hp"] < pl["maxhp"] and pl["maxhp"] < 900:
                ratio = max(0, pl["hp"] / pl["maxhp"])
                cv.create_rectangle(x - 24, y - 30, x + 24, y - 24, fill="#333", outline="")
                col = "#4caf50" if ratio > 0.5 else "#ff9800" if ratio > 0.25 else "#f44336"
                cv.create_rectangle(x - 24, y - 30, x - 24 + 48 * ratio, y - 24, fill=col, outline="")

        # 豌豆
        for p in self.peas:
            if p.get("delay", 0) > 0:
                continue
            color = "#4fc3f7" if p["dmg"] < 20 and p["slow"] else "#66bb6a"
            cv.create_oval(p["x"] - 6, p["y"] - 6, p["x"] + 6, p["y"] + 6, fill=color, outline="#2b2b2b")

        # 僵尸
        for z in self.zombies:
            x, y = z["x"], z["y"]
            cv.create_oval(x - 22, y - 30, x + 22, y + 24, fill=z["color"], outline="#2b2b2b", width=2)
            cv.create_text(x, y - 2, text=z["emoji"], font=("Segoe UI Emoji", 22))
            # 眼睛
            cv.create_rectangle(x - 10, y - 14, x - 4, y - 8, fill="red")
            cv.create_rectangle(x + 4, y - 14, x + 10, y - 8, fill="red")
            # 护甲
            if z["armor"] > 0:
                acolor = ZOMBIES.get(z["type"], {}).get("acolor", "#90a4ae")
                ar = z["armor"] / max(1, z["maxarmor"])
                cv.create_rectangle(x - 18, y + 26, x + 18, y + 30, fill="#333", outline="")
                cv.create_rectangle(x - 18, y + 26, x - 18 + 36 * ar, y + 30, fill=acolor, outline="")
            # 减速标识
            if z["slow"] > 0:
                cv.create_text(x + 20, y - 24, text="❄", font=("Segoe UI Emoji", 12))
            # 血条
            ratio = max(0, z["hp"] / 100)
            cv.create_rectangle(x - 22, y - 40, x + 22, y - 35, fill="#333", outline="")
            cv.create_rectangle(x - 22, y - 40, x - 22 + 44 * ratio, y - 35, fill="#f44336", outline="")

        # 阳光掉落
        for s in self.suns:
            cv.create_oval(s["x"] - 16, s["y"] - 16, s["x"] + 16, s["y"] + 16, fill=SUN_COLOR, outline="#c9a000", width=2)
            cv.create_text(s["x"], s["y"], text="☀", font=("Segoe UI Emoji", 16))

        # 粒子
        for pt in self.particles:
            cv.create_oval(pt["x"] - 4, pt["y"] - 4, pt["x"] + 4, pt["y"] + 4, fill=pt["color"], outline="")

        # UI 文本
        cv.itemconfig(self.sun_text, text=f"☀ {self.sun}")
        cv.itemconfig(self.wave_text, text=f"波次 {self.wave}  击杀 {self.kills}")

        # 结束画面
        if self.game_over:
            cv.create_rectangle(0, HEIGHT // 2 - 70, WIDTH, HEIGHT // 2 + 70, fill="#000000", stipple="gray50", outline="")
            if self.win:
                txt, col = "🎉 胜利！你守住了花园！", "#ffeb3b"
            else:
                txt, col = "💀 僵尸吃掉了你的脑子…", "#ff5252"
            cv.create_text(WIDTH // 2, HEIGHT // 2 - 15, text=txt, font=("Microsoft YaHei", 26, "bold"), fill=col)
            cv.create_text(WIDTH // 2, HEIGHT // 2 + 30, text=f"坚持 {self.wave} 波 · 击杀 {self.kills} · 点击任意处重新开始", font=("Microsoft YaHei", 13), fill="#fff")


if __name__ == "__main__":
    root = tk.Tk()
    try:
        root.iconbitmap()  # noop
    except Exception:
        pass
    game = Game(root)
    root.mainloop()
