import pygame
import random
import sys

# 初始化Pygame
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("植物大战僵尸 Pygame版")
clock = pygame.time.Clock()
FPS = 60

# 颜色常量
WHITE = (255, 255, 255)
GREEN = (34, 139, 34)
YELLOW = (255, 215, 0)
BROWN = (101, 67, 33)
RED = (200, 0, 0)
BLUE = (0, 150, 255)
ICE_BLUE = (120, 200, 255)
BLACK = (0, 0, 0)
GRASS_COLOR = (120, 180, 90)
WALLNUT_COLOR = (140, 90, 40)
BARRIER_COLOR = (80, 50, 20)
BUCKET_COLOR = (70, 70, 70)

# 植物类型常量
PLANT_SUNFLOWER = 1
PLANT_PEASHOOTER = 2
PLANT_WALLNUT = 3
PLANT_ICEPEA = 4

# 全局变量
sun = 50
grid_size = 80
rows = 5
cols = 9
plants = []
zombies = []
bullets = []
sun_sources = []
spawn_zombie_timer = 0
sun_spawn_timer = 0
selected_plant = None

# 植物类
class Plant:
    def __init__(self, x, y, plant_type):
        self.x = x
        self.y = y
        self.type = plant_type
        if plant_type == PLANT_WALLNUT:
            self.hp = 800
        else:
            self.hp = 100
        self.sun_timer = 0
        self.shoot_timer = 0

    def draw(self):
        if self.type == PLANT_SUNFLOWER:
            pygame.draw.circle(screen, YELLOW, (self.x+40, self.y+40), 35)
            pygame.draw.circle(screen, BROWN, (self.x+40, self.y+40), 15)
        elif self.type == PLANT_PEASHOOTER:
            pygame.draw.rect(screen, GREEN, (self.x+10, self.y+20, 60, 60))
            pygame.draw.circle(screen, GREEN, (self.x+70, self.y+40), 20)
        elif self.type == PLANT_WALLNUT:
            pygame.draw.circle(screen, WALLNUT_COLOR, (self.x+40, self.y+40), 38)
            pygame.draw.circle(screen, BLACK, (self.x+30, self.y+35), 8)
            pygame.draw.circle(screen, BLACK, (self.x+50, self.y+35), 8)
        elif self.type == PLANT_ICEPEA:
            pygame.draw.rect(screen, ICE_BLUE, (self.x+10, self.y+20, 60, 60))
            pygame.draw.circle(screen, ICE_BLUE, (self.x+70, self.y+40), 20)

    def update(self):
        global sun_sources
        if self.type == PLANT_SUNFLOWER:
            self.sun_timer += 1
            if self.sun_timer >= 180:
                self.sun_timer = 0
                sun_sources.append({"x": self.x+40, "y": self.y, "timer": 120})
        elif self.type == PLANT_PEASHOOTER:
            self.shoot_timer += 1
            if self.shoot_timer >= 90:
                self.shoot_timer = 0
                for z in zombies:
                    if z.y == self.y:
                        bullets.append({"x": self.x+80, "y": self.y+40, "speed": 6, "ice": False})
                        break
        elif self.type == PLANT_ICEPEA:
            self.shoot_timer += 1
            if self.shoot_timer >= 90:
                self.shoot_timer = 0
                for z in zombies:
                    if z.y == self.y:
                        bullets.append({"x": self.x+80, "y": self.y+40, "speed": 6, "ice": True})
                        break
        elif self.type == PLANT_WALLNUT:
            pass

# 僵尸类（支持普通/路障/铁桶）
class Zombie:
    def __init__(self, row, z_type=1):
        self.y = row * grid_size
        self.x = WIDTH
        self.z_type = z_type
        if self.z_type == 1:
            self.hp = 150
            self.speed = 0.5
            self.body_color = RED
        elif self.z_type == 2:
            self.hp = 300
            self.speed = 0.4
            self.body_color = BROWN
        elif self.z_type == 3:
            self.hp = 600
            self.speed = 0.3
            self.body_color = BUCKET_COLOR

    def draw(self):
        pygame.draw.rect(screen, self.body_color, (self.x, self.y+10, 60, 60))
        pygame.draw.circle(screen, WHITE, (self.x+20, self.y+25), 8)
        pygame.draw.circle(screen, WHITE, (self.x+40, self.y+25), 8)
        if self.z_type == 2:
            pygame.draw.rect(screen, BARRIER_COLOR, (self.x+10, self.y, 40, 25))
        elif self.z_type == 3:
            pygame.draw.ellipse(screen, BUCKET_COLOR, (self.x+5, self.y-5, 50, 22))

    def update(self):
        self.x -= self.speed
        for p in plants:
            if abs(p.x - self.x) < 50 and abs(p.y - self.y) < 50:
                self.x += self.speed
                p.hp -= 0.2
                if p.hp <= 0:
                    plants.remove(p)

# 绘制草坪格子
def draw_grass():
    for r in range(rows):
        for c in range(cols):
            rect = (c*grid_size, r*grid_size, grid_size-2, grid_size-2)
            pygame.draw.rect(screen, GRASS_COLOR, rect)

# 主循环
running = True
while running:
    dt = clock.tick(FPS) / 1000
    screen.fill(BLACK)
    draw_grass()

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = pygame.mouse.get_pos()
            c = mx // grid_size
            r = my // grid_size
            gx = c * grid_size
            gy = r * grid_size
            if event.button == 1:
                exist = False
                for p in plants:
                    if p.x == gx and p.y == gy:
                        exist = True
                        break
                if not exist:
                    if selected_plant == PLANT_SUNFLOWER and sun >= 50:
                        plants.append(Plant(gx, gy, PLANT_SUNFLOWER))
                        sun -= 50
                    elif selected_plant == PLANT_PEASHOOTER and sun >= 100:
                        plants.append(Plant(gx, gy, PLANT_PEASHOOTER))
                        sun -= 100
                    elif selected_plant == PLANT_WALLNUT and sun >= 50:
                        plants.append(Plant(gx, gy, PLANT_WALLNUT))
                        sun -= 50
                    elif selected_plant == PLANT_ICEPEA and sun >= 175:
                        plants.append(Plant(gx, gy, PLANT_ICEPEA))
                        sun -= 175

    # 键盘切换植物
    keys = pygame.key.get_pressed()
    if keys[pygame.K_1]:
        selected_plant = PLANT_SUNFLOWER
    if keys[pygame.K_2]:
        selected_plant = PLANT_PEASHOOTER
    if keys[pygame.K_3]:
        selected_plant = PLANT_WALLNUT
    if keys[pygame.K_4]:
        selected_plant = PLANT_ICEPEA

    # 阳光掉落与拾取
    for s in sun_sources[:]:
        s["timer"] -= 1
        s["y"] += 1
        pygame.draw.circle(screen, YELLOW, (s["x"], s["y"]), 12)
        mx, my = pygame.mouse.get_pos()
        if (mx - s["x"]) ** 2 + (my - s["y"]) ** 2 < 400:
            sun += 25
            sun_sources.remove(s)
        if s["timer"] <= 0:
            sun_sources.remove(s)

    # 生成僵尸
    spawn_zombie_timer += 1
    if spawn_zombie_timer >= 400:
        spawn_zombie_timer = 0
        row_rand = random.randint(0, rows-1)
        z_type_rand = random.choice([1,1,1,2,2,3])
        zombies.append(Zombie(row_rand * grid_size, z_type_rand))

    # 更新绘制僵尸
    for z in zombies[:]:
        z.update()
        z.draw()
        if z.x < -60 or z.hp <= 0:
            zombies.remove(z)

    # 更新子弹 + 冰冻减速逻辑
    for b in bullets[:]:
        b["x"] += b["speed"]
        draw_color = ICE_BLUE if b["ice"] else BLUE
        pygame.draw.circle(screen, draw_color, (b["x"], b["y"]), 6)
        hit = False
        for z in zombies:
            if abs(b["x"] - z.x - 30) < 30 and abs(b["y"] - z.y - 30) < 30:
                z.hp -= 25
                if b["ice"]:
                    z.speed = 0.15
                else:
                    z.speed = 0.5
                hit = True
                break
        if hit:
            bullets.remove(b)
        elif b["x"] > WIDTH:
            bullets.remove(b)

    # 更新绘制所有植物
    for p in plants:
        p.update()
        p.draw()

    # 文字UI
    font = pygame.font.SysFont(None, 40)
    sun_text = font.render(f"阳光：{int(sun)}", True, YELLOW)
    screen.blit(sun_text, (10, HEIGHT - 40))
    tip_text = font.render("1向日葵 2豌豆 3坚果 4寒冰 | 左键放置", True, WHITE)
    screen.blit(tip_text, (10, 10))

    pygame.display.flip()

pygame.quit()
sys.exit()