import tkinter as tk
import random
import math

# ---------- 植物基类 ----------
class Plant:
    def __init__(self, game, row, col, health=100):
        self.game = game
        self.row = row
        self.col = col
        self.health = health
        self.x = game.offset_x + col * game.cell_width + game.cell_width // 2
        self.y = game.offset_y + row * game.cell_height + game.cell_height // 2
        self.id = None

# ---------- 向日葵 ----------
class Sunflower(Plant):
    def __init__(self, game, row, col):
        super().__init__(game, row, col, health=100)
        # 绘制向日葵
        self.id = game.canvas.create_oval(self.x-20, self.y-20, self.x+20, self.y+20,
                                          fill="yellow", outline="orange", width=2)
        for angle in range(0, 360, 45):
            rad = math.radians(angle)
            px = self.x + 28 * math.cos(rad)
            py = self.y + 28 * math.sin(rad)
            game.canvas.create_oval(px-6, py-6, px+6, py+6, fill="yellow", outline="orange")
        self.produce_sun()

    def produce_sun(self):
        if self.game.game_over:
            return
        sun = Sun(self.game, self.x, self.y-20)
        self.game.suns.append(sun)
        delay = 5000 + random.randint(0, 3000)
        self.game.root.after(delay, self.produce_sun)

# ---------- 豌豆射手 ----------
class Peashooter(Plant):
    def __init__(self, game, row, col):
        super().__init__(game, row, col, health=100)
        self.id = game.canvas.create_oval(self.x-20, self.y-20, self.x+20, self.y+20,
                                          fill="green", outline="darkgreen", width=2)
        game.canvas.create_rectangle(self.x+10, self.y-10, self.x+30, self.y+10,
                                     fill="green", outline="darkgreen")
        self.shoot()

    def shoot(self):
        if self.game.game_over:
            return
        target = None
        for z in self.game.zombies:
            if z.row == self.row and z.x > self.x:
                target = z
                break
        if target:
            bullet = Bullet(self.game, self.x+30, self.y, self.row)
            self.game.bullets.append(bullet)
        delay = 1500 + random.randint(0, 1000)
        self.game.root.after(delay, self.shoot)

# ---------- 僵尸 ----------
class Zombie:
    def __init__(self, game, row):
        self.game = game
        self.row = row
        self.x = game.offset_x + game.cols * game.cell_width + 50
        self.y = game.offset_y + row * game.cell_height + game.cell_height // 2
        self.health = 100
        self.speed = 0.8
        self.attack_cooldown = 0
        self.id = game.canvas.create_rectangle(self.x-15, self.y-25, self.x+15, self.y+25,
                                               fill="purple", outline="black")
        game.canvas.create_oval(self.x-10, self.y-15, self.x-4, self.y-9, fill="white")
        game.canvas.create_oval(self.x+4, self.y-15, self.x+10, self.y-9, fill="white")

    def move(self):
        if self.game.game_over:
            return
        for plant in self.game.plants:
            if plant.row == self.row and abs(plant.x - self.x) < 30:
                if self.attack_cooldown <= 0:
                    plant.health -= 10
                    self.attack_cooldown = 20
                    if plant.health <= 0:
                        self.game.canvas.delete(plant.id)
                        self.game.plants.remove(plant)
                else:
                    self.attack_cooldown -= 1
                return
        self.x -= self.speed
        self.game.canvas.coords(self.id, self.x-15, self.y-25, self.x+15, self.y+25)
        if self.x < self.game.offset_x:
            self.game.game_over = True
            self.game.canvas.create_text(450, 300, text="💀 游戏结束", font=("Arial", 48, "bold"), fill="red")

# ---------- 子弹 ----------
class Bullet:
    def __init__(self, game, x, y, row):
        self.game = game
        self.x = x
        self.y = y
        self.row = row
        self.speed = 3
        self.id = game.canvas.create_oval(x-5, y-5, x+5, y+5, fill="lime", outline="darkgreen")

    def move(self):
        self.x += self.speed
        self.game.canvas.coords(self.id, self.x-5, self.y-5, self.x+5, self.y+5)
        for z in self.game.zombies:
            if z.row == self.row and abs(z.x - self.x) < 20 and abs(z.y - self.y) < 30:
                z.health -= 20
                self.game.canvas.delete(self.id)
                self.game.bullets.remove(self)
                if z.health <= 0:
                    self.game.canvas.delete(z.id)
                    self.game.zombies.remove(z)
                return
        if self.x > 950:
            self.game.canvas.delete(self.id)
            self.game.bullets.remove(self)

# ---------- 阳光 ----------
class Sun:
    def __init__(self, game, x, y):
        self.game = game
        self.x = x
        self.y = y
        self.collected = False
        self.id = game.canvas.create_oval(x-15, y-15, x+15, y+15,
                                          fill="yellow", outline="orange", width=2)
        game.canvas.tag_bind(self.id, "<Button-1>", self.collect)
        self.fall()

    def fall(self):
        if self.collected or self.game.game_over:
            return
        if self.y < 500:
            self.y += 2
            self.game.canvas.coords(self.id, self.x-15, self.y-15, self.x+15, self.y+15)
            self.game.root.after(50, self.fall)
        else:
            self.game.root.after(8000, self.disappear)

    def collect(self, event):
        if not self.collected:
            self.collected = True
            self.game.sun_count += 25
            self.game.canvas.delete(self.id)
            self.game.suns.remove(self)
            self.game.update_ui()

    def disappear(self):
        if not self.collected:
            self.game.canvas.delete(self.id)
            self.game.suns.remove(self)

# ---------- 主游戏类 ----------
class Game:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("🌻 植物大战僵尸 - Tkinter 版")
        self.root.geometry("900x650")
        self.root.resizable(False, False)

        self.rows = 5
        self.cols = 9
        self.cell_width = 80
        self.cell_height = 100
        self.offset_x = 50
        self.offset_y = 70

        self.plants = []
        self.zombies = []
        self.bullets = []
        self.suns = []
        self.sun_count = 2000          # <--- 修改为 2000
        self.game_over = False
        self.selected_plant = None

        self.canvas = tk.Canvas(self.root, width=900, height=600, bg="lightgreen")
        self.canvas.place(x=0, y=50)

        self.create_toolbar()
        self.draw_grid()

        self.canvas.bind("<Button-1>", self.on_click)
        self.canvas.bind("<Button-3>", self.on_right_click)

        self.update()
        self.root.after(3000, self.spawn_zombie)

        self.root.mainloop()

    def create_toolbar(self):
        toolbar = tk.Frame(self.root, bg="saddlebrown", height=50)
        toolbar.pack(side=tk.TOP, fill=tk.X)

        btn_sun = tk.Button(toolbar, text="🌻 向日葵 (50)", font=("Arial", 12),
                            command=lambda: self.select_plant("sunflower"))
        btn_sun.pack(side=tk.LEFT, padx=10, pady=5)

        btn_pea = tk.Button(toolbar, text="🌱 豌豆射手 (100)", font=("Arial", 12),
                            command=lambda: self.select_plant("peashooter"))
        btn_pea.pack(side=tk.LEFT, padx=10, pady=5)

        self.sun_label = tk.Label(toolbar, text=f"☀️ 阳光: {self.sun_count}",
                                  font=("Arial", 14, "bold"), bg="saddlebrown", fg="white")
        self.sun_label.pack(side=tk.RIGHT, padx=20)

        self.status_label = tk.Label(toolbar, text="请选择植物", font=("Arial", 12),
                                     bg="saddlebrown", fg="white")
        self.status_label.pack(side=tk.RIGHT, padx=20)

    def draw_grid(self):
        for r in range(self.rows):
            for c in range(self.cols):
                x1 = self.offset_x + c * self.cell_width
                y1 = self.offset_y + r * self.cell_height
                x2 = x1 + self.cell_width
                y2 = y1 + self.cell_height
                self.canvas.create_rectangle(x1, y1, x2, y2, outline="gray", width=1)

    def select_plant(self, plant_type):
        self.selected_plant = plant_type
        name = "向日葵" if plant_type == "sunflower" else "豌豆射手"
        self.status_label.config(text=f"已选: {name}")

    def on_right_click(self, event):
        self.selected_plant = None
        self.status_label.config(text="已取消选择")

    def on_click(self, event):
        if self.game_over:
            return
        x, y = event.x, event.y
        if not (self.offset_x <= x <= self.offset_x + self.cols * self.cell_width and
                self.offset_y <= y <= self.offset_y + self.rows * self.cell_height):
            return
        if self.selected_plant is None:
            return

        col = (x - self.offset_x) // self.cell_width
        row = (y - self.offset_y) // self.cell_height
        if not (0 <= row < self.rows and 0 <= col < self.cols):
            return

        for p in self.plants:
            if p.row == row and p.col == col:
                return

        cost = 50 if self.selected_plant == "sunflower" else 100
        if self.sun_count < cost:
            self.status_label.config(text="阳光不足！")
            return

        self.sun_count -= cost
        self.update_ui()

        if self.selected_plant == "sunflower":
            plant = Sunflower(self, row, col)
        else:
            plant = Peashooter(self, row, col)
        self.plants.append(plant)
        self.status_label.config(text="种植成功！")

    def update_ui(self):
        self.sun_label.config(text=f"☀️ 阳光: {self.sun_count}")

    def spawn_zombie(self):
        if self.game_over:
            return
        count = random.randint(1, 2)
        for _ in range(count):
            row = random.randint(0, self.rows - 1)
            zombie = Zombie(self, row)
            self.zombies.append(zombie)
        delay = 5000 + random.randint(0, 5000)
        self.root.after(delay, self.spawn_zombie)

    def update(self):
        if not self.game_over:
            for z in self.zombies[:]:
                z.move()
            for b in self.bullets[:]:
                b.move()
        self.root.after(50, self.update)

# ---------- 程序入口 ----------
if __name__ == "__main__":
    game = Game()