import pygame
import random

# --- 配置 ---
WIDTH, HEIGHT = 900, 600
GRID_SIZE = 100
FPS = 60

# 颜色
WHITE = (255, 255, 255)
GRASS_GREEN = (34, 139, 34)
DIRT_BROWN = (139, 69, 19)
SUN_YELLOW = (255, 255, 0)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python 植物大战僵尸简易版")
clock = pygame.time.Clock()
font = pygame.font.SysFont("simhei", 24)

# --- 类定义 ---

class Sun(pygame.sprite.Sprite):
    """阳光类"""
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((30, 30))
        self.image.fill(SUN_YELLOW)
        self.rect = self.image.get_rect(center=(x, y))
        self.lifetime = 300 # 存在时间

    def update(self):
        self.lifetime -= 1
        if self.lifetime <= 0: self.kill()

class Bullet(pygame.sprite.Sprite):
    """豌豆子弹"""
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((15, 15))
        pygame.draw.circle(self.image, (0, 255, 0), (7, 7), 7)
        self.rect = self.image.get_rect(center=(x, y))
        self.speed = 7

    def update(self):
        self.rect.x += self.speed
        if self.rect.left > WIDTH: self.kill()

class Plant(pygame.sprite.Sprite):
    """植物类 (豌豆射手)"""
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((60, 60))
        self.image.fill((0, 200, 0)) # 绿色方块代表植物
        self.rect = self.image.get_rect(center=(x, y))
        self.shoot_delay = 60
        self.timer = 0

    def update(self, bullets):
        self.timer += 1
        if self.timer >= self.shoot_delay:
            bullets.add(Bullet(self.rect.right, self.rect.centery))
            self.timer = 0

class Zombie(pygame.sprite.Sprite):
    """僵尸类"""
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((50, 80))
        self.image.fill((100, 100, 100)) # 灰色方块代表僵尸
        self.rect = self.image.get_rect(center=(x, y))
        self.hp = 3
        self.speed = 1

    def update(self):
        self.rect.x -= self.speed

# --- 主游戏类 ---

class Game:
    def __init__(self):
        self.plants = pygame.sprite.Group()
        self.zombies = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.suns = pygame.sprite.Group()
        self.money = 200
        self.zombie_timer = 0

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = pygame.mouse.get_pos()
                # 1. 收集阳光
                for sun in self.suns:
                    if sun.rect.collidepoint(mx, my):
                        self.money += 25
                        sun.kill()
                        return True
                # 2. 种植植物 (点击草地)
                if self.money >= 50:
                    grid_x = (mx // GRID_SIZE) * GRID_SIZE + GRID_SIZE // 2
                    grid_y = (my // GRID_SIZE) * GRID_SIZE + GRID_SIZE // 2
                    # 检查是否已种过
                    if not any(p.rect.center == (grid_x, grid_y) for p in self.plants):
                        self.plants.add(Plant(grid_x, grid_y))
                        self.money -= 50
        return True

    def run(self):
        running = True
        while running:
            # A. 逻辑更新
            running = self.handle_events()
            
            # 生成僵尸
            self.zombie_timer += 1
            if self.zombie_timer >= 120:
                row = random.randint(0, 5)
                self.zombies.add(Zombie(WIDTH, row * GRID_SIZE + GRID_SIZE // 2))
                self.zombie_timer = 0

            # 随机掉落阳光
            if random.random() < 0.01:
                self.suns.add(Sun(random.randint(100, WIDTH-100), random.randint(100, HEIGHT-100)))

            self.plants.update(self.bullets)
            self.zombies.update()
            self.bullets.update()
            self.suns.update()

            # 碰撞检测：子弹打中僵尸
            for b in self.bullets:
                hit_zombies = pygame.sprite.spritecollide(b, self.zombies, False)
                for z in hit_zombies:
                    z.hp -= 1
                    b.kill()
                    if z.hp <= 0: z.kill()

            # 碰撞检测：僵尸吃植物
            for z in self.zombies:
                hit_plants = pygame.sprite.spritecollide(z, self.plants, True)
                if hit_plants:
                    z.speed = 0 # 模拟停下来吃
                else:
                    z.speed = 1

            # B. 绘制
            screen.fill(GRASS_GREEN)
            # 画网格线
            for x in range(0, WIDTH, GRID_SIZE):
                pygame.draw.line(screen, WHITE, (x, 0), (x, HEIGHT))
            for y in range(0, HEIGHT, GRID_SIZE):
                pygame.draw.line(screen, WHITE, (0, y), (WIDTH, y))

            self.plants.draw(screen)
            self.zombies.draw(screen)
            self.bullets.draw(screen)
            self.suns.draw(screen)

            # UI
            money_txt = font.render(f"阳光: {self.money} (50种一个)", True, WHITE)
            screen.blit(money_txt, (10, 10))

            pygame.display.flip()
            clock.tick(FPS)

        pygame.quit()

if __name__ == "__main__":
    Game().run()