import tkinter as tk
import random
import time

CELL = 80
ROWS, COLS = 5, 9
WIDTH = COLS * CELL + 200
HEIGHT = ROWS * CELL + 100

PLANT_NONE = 0
PLANT_PEASHOOTER = 1
PLANT_SUNFLOWER = 2


class Plant:
    def __init__(self, kind, row, col, x, y):
        self.kind = kind
        self.row = row
        self.col = col
        self.x = x
        self.y = y
        self.hp = 100
        self.timer = 0


class Zombie:
    def __init__(self, row, y):
        self.row = row
        self.x = WIDTH - 200
        self.y = y
        self.hp = 60
        self.speed = 0.6
        self.alive = True


class Bullet:
    def __init__(ai, x, y):
        ai.x = x
        ai.y = y
        ai.speed = 6
        ai.alive = True


class PVZGame:
    def __init__(self, root):
        self.root = root
        self.root.title("018. 植物大战僵尸（简化版）")
        self.root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#87CEEB")
        self.canvas.pack()

        # 草坪
        self.grid = [[PLANT_NONE for _ in range(COLS)] for _ in range(ROWS)]
        self.plants = []
        self.zombies = []
        self.bullets = []
        self.sun = 150

        self.selected_plant = PLANT_PEASHOOTER
        self.last_zombie_time = time.time()

        self.draw_lawn()
        self.sun_text = self.canvas.create_text(
            30, HEIGHT - 40, anchor="w",
            text="", fill="#333", font=("微软雅黑", 12, "bold")
        )
        self.hint = self.canvas.create_text(
            WIDTH // 2, HEIGHT - 40,
            text="1=豌豆射手(100)  2=向日葵(50)  点击草坪种植",
            fill="#666", font=("微软雅黑", 10)
        )

        self.canvas.bind("<Button-1>", self.on_click)
        self.root.bind("1", lambda e: self.select(PLANT_PEASHOOTER))
        self.root.bind("2", lambda e: self.select(PLANT_SUNFLOWER))

        self.game_over = False
        self.update_ui()
        self.spawn_sun()
        self.game_loop()

    def draw_lawn(self):
        for r in range(ROWS):
            for c in range(COLS):
                x = c * CELL + 100
                y = r * CELL + 20
                color = "#aed581" if (r + c) % 2 == 0 else "#9ccc65"
                self.canvas.create_rectangle(
                    x, y, x + CELL, y + CELL,
                    fill=color, outline="#689f38"
                )

    def select(self, kind):
        self.selected_plant = kind

    def on_click(self, e):
        if self.game_over:
            return
        x, y = e.x, e.y
        col = (x - 100) // CELL
        row = (y - 20) // CELL

        if not (0 <= row < ROWS and 0 <= col < COLS):
            return
        if self.grid[row][col] != PLANT_NONE:
            return

        cost = 100 if self.selected_plant == PLANT_PEASHOOTER else 50
        if self.sun < cost:
            return

        self.sun -= cost
        gx = col * CELL + 100 + CELL // 2
        gy = row * CELL + 20 + CELL // 2
        self.grid[row][col] = self.selected_plant
        self.plants.append(Plant(self.selected_plant, row, col, gx, gy))

    def spawn_sun(self):
        if not self.game_over:
            self.sun += 25
            self.root.after(3000, self.spawn_sun)

    def draw_objects(self):
        self.canvas.delete("obj")

        # 植物
        for p in self.plants:
            if p.kind == PLANT_PEASHOOTER:
                self.canvas.create_rectangle(
                    p.x - 15, p.y - 25, p.x + 15, p.y + 25,
                    fill="#388e3c", outline="#1b5e20", width=2, tags="obj"
                )
                self.canvas.create_oval(
                    p.x - 8, p.y - 10, p.x + 8, p.y + 10,
                    fill="#66bb6a", tags="obj"
                )
            else:
                self.canvas.create_oval(
                    p.x - 18, p.y - 18, p.x + 18, p.y + 18,
                    fill="#fbc02d", outline="#f57f17", width=2, tags="obj"
                )
                self.canvas.create_oval(
                    p.x - 6, p.y - 6, p.x + 6, p.y + 6,
                    fill="#fff176", tags="obj"
                )

        # 僵尸
        for z in self.zombies:
            self.canvas.create_rectangle(
                z.x - 20, z.y - 30, z.x + 20, z.y + 30,
                fill="#795548", outline="#4e342e", width=2, tags="obj"
            )
            self.canvas.create_oval(
                z.x - 8, z.y - 15, z.x + 8, z.y - 7,
                fill="#a1887f", tags="obj"
            )

        # 子弹
        for b in self.bullets:
            self.canvas.create_oval(
                b.x - 5, b.y - 5, b.x + 5, b.y + 5,
                fill="#ffeb3b", outline="#fbc02d", tags="obj"
            )

    def update_ui(self):
        self.canvas.itemconfig(self.sun_text, text=f"☀ 阳光: {self.sun}")

    def game_loop(self):
        if self.game_over:
            return

        now = time.time()

        # 生成僵尸
        if now - self.last_zombie_time > 3:
            row = random.randint(0, ROWS - 1)
            y = row * CELL + 20 + CELL // 2
            self.zombies.append(Zombie(row, y))
            self.last_zombie_time = now

        # 植物逻辑
        for p in self.plants:
            p.timer += 1
            if p.kind == PLANT_PEASHOOTER and p.timer % 40 == 0:
                self.bullets.append(Bullet(p.x + 20, p.y))
            if p.kind == PLANT_SUNFLOWER and p.timer % 120 == 0:
                self.sun += 10

        # 子弹移动 & 碰撞
        for b in self.bullets[:]:
            b.x += b.speed
            if b.x > WIDTH:
                b.alive = False
                continue
            for z in self.zombies:
                if z.alive and abs(b.x - z.x) < 25 and z.row == z.row:
                    z.hp -= 20
                    b.alive = False
                    break
        self.bullets = [b for b in self.bullets if b.alive]

        # 僵尸移动 & 吃植物
        for z in self.zombies[:]:
            blocked = False
            for p in self.plants:
                if p.row == z.row and abs(p.x - z.x) < 30:
                    p.hp -= 0.3
                    blocked = True
                    break
            if not blocked:
                z.x -= z.speed

            if z.x < 100:
                self.game_over = True
                self.canvas.create_text(
                    WIDTH // 2, HEIGHT // 2,
                    text="💀 僵尸进家了！游戏结束\n按 R 重新开始",
                    fill="red", font=("微软雅黑", 20, "bold"),
                    justify=tk.CENTER
                )
                self.root.bind("r", lambda e: self.restart())
                return

            if z.hp <= 0:
                z.alive = False
        self.zombies = [z for z in self.zombies if z.alive]

        # 移除死亡植物
        self.plants = [p for p in self.plants if p.hp > 0]

        self.draw_objects()
        self.update_ui()
        self.root.after(30, self.game_loop)

    def restart(self):
        self.canvas.delete("all")
        self.__init__(self.root)


if __name__ == "__main__":
    root = tk.Tk()
    PVZGame(root)
    root.mainloop()