import pygame
import random

# 初始化
pygame.init()
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("简易植物大战僵尸")
clock = pygame.time.Clock()

# 颜色定义
GREEN = (34, 139, 34)
GRASS = (90, 160, 60)
BROWN = (101, 67, 33)
WHITE = (255, 255, 255)
YELLOW = (255, 220, 0)
RED = (220, 30, 30)

# 格子设置
CELL_W = 90
CELL_H = 100
ROW_COUNT = 5
COL_COUNT = 8

# 阳光数值
sun = 150
# ==========修复字体报错 重点改动==========
try:
    font = pygame.font.SysFont("SimHei", 30)
except:
    font = pygame.font.Font(None, 30)

# 类定义
class Plant(pygame.sprite.Sprite):
    def __init__(self, x, y, ptype):
        super().__init__()
        self.type = ptype
        self.rect = pygame.Rect(x, y, CELL_W-5, CELL_H-5)
        self.hp = 100
        self.cd = 0
        if self.type == "sunflower":
            self.cost = 50
            self.color = YELLOW
        elif self.type == "peashooter":
            self.cost = 100
            self.color = (60, 180, 80)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.rect = pygame.Rect(x, y, 12, 12)
        self.speed = 6
        self.dmg = 25

class Zombie(pygame.sprite.Sprite):
    def __init__(self, row):
        super().__init__()
        self.y = row * CELL_H + 10
        self.x = WIDTH
        self.rect = pygame.Rect(self.x, self.y, 60, 80)
        self.hp = 100
        self.speed = 0.4
        self.eat_cd = 0

# 精灵组
plants = pygame.sprite.Group()
bullets = pygame.sprite.Group()
zombies = pygame.sprite.Group()

# 选中植物
select_plant = None
spawn_zombie_timer = 0

running = True
while running:
    dt = clock.tick(60) / 1000.0

    # 事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = pygame.mouse.get_pos()
            # 选择向日葵
            if 20 <= mx <= 110 and HEIGHT-90 <= my <= HEIGHT-10:
                select_plant = "sunflower"
            # 选择豌豆射手
            elif 130 <= mx <= 220 and HEIGHT-90 <= my <= HEIGHT-10:
                select_plant = "peashooter"
            # 种植植物
            elif select_plant:
                col = mx // CELL_W
                row = my // CELL_H
                if 0 <= row < ROW_COUNT and 0 <= col < COL_COUNT:
                    px = col * CELL_W
                    py = row * CELL_H
                    # 判断格子是否已有植物
                    exist = False
                    for p in plants:
                        if p.rect.colliderect((px, py, CELL_W, CELL_H)):
                            exist = True
                            break
                    if not exist:
                        temp = Plant(px, py, select_plant)
                        if sun >= temp.cost:
                            sun -= temp.cost
                            plants.add(temp)

    # 生成僵尸
    spawn_zombie_timer += dt
    if spawn_zombie_timer > 8:
        spawn_zombie_timer = 0
        r = random.randint(0, ROW_COUNT-1)
        zombies.add(Zombie(r))

    # 更新植物
    for p in plants:
        p.cd -= dt
        if p.type == "sunflower":
            if p.cd <= 0:
                sun += 25
                p.cd = 12
        elif p.type == "peashooter":
            if p.cd <= 0:
                # 同行是否存在僵尸
                has_zombie = False
                for z in zombies:
                    if abs(z.rect.y - p.rect.y) < CELL_H//2 and z.rect.x > p.rect.x:
                        has_zombie = True
                        break
                if has_zombie:
                    bullets.add(Bullet(p.rect.right, p.rect.centery))
                    p.cd = 1.4

    # 更新子弹
    for b in bullets:
        b.rect.x += b.speed
        if b.rect.x > WIDTH:
            b.kill()

    # 更新僵尸
    for z in zombies:
        collision_plant = None
        for p in plants:
            if z.rect.colliderect(p.rect):
                collision_plant = p
                break
        if collision_plant:
            z.eat_cd += dt
            if z.eat_cd > 1:
                collision_plant.hp -= 10
                z.eat_cd = 0
                if collision_plant.hp <= 0:
                    collision_plant.kill()
        else:
            z.rect.x -= z.speed
        if z.rect.x < -60:
            z.kill()

    # 子弹击中僵尸
    hits = pygame.sprite.groupcollide(zombies, bullets, False, True)
    for z, blist in hits.items():
        for b in blist:
            z.hp -= b.dmg
            if z.hp <= 0:
                z.kill()

    # ====== 绘制 ======
    screen.fill(BROWN)
    # 绘制草坪网格
    for r in range(ROW_COUNT):
        for c in range(COL_COUNT):
            rect = pygame.Rect(c*CELL_W, r*CELL_H, CELL_W, CELL_H)
            if (r+c) % 2 == 0:
                pygame.draw.rect(screen, GRASS, rect)
            else:
                pygame.draw.rect(screen, GREEN, rect)
            pygame.draw.rect(screen, (20,80,20), rect, 1)

    # 底部植物选择栏
    pygame.draw.rect(screen, (50,50,50), (0, HEIGHT-100, WIDTH, 100))
    pygame.draw.rect(screen, YELLOW, (20, HEIGHT-90, 90, 80))
    pygame.draw.rect(screen, (60,180,80), (130, HEIGHT-90, 90, 80))
    screen.blit(font.render("SunFlower 50", True, (0,0,0)), (25, HEIGHT-70))
    screen.blit(font.render("Peashooter 100", True, (0,0,0)), (135, HEIGHT-70))

    # 阳光文字
    sun_text = font.render(f"Sun: {sun}", True, YELLOW)
    screen.blit(sun_text, (WIDTH - 160, 10))

    # 绘制植物
    for p in plants:
        pygame.draw.ellipse(screen, p.color, p.rect)
    # 绘制子弹
    for b in bullets:
        pygame.draw.circle(screen, (180,220,40), b.rect.center, 6)
    # 绘制僵尸
    for z in zombies:
        pygame.draw.rect(screen, (90,90,90), z.rect)
        pygame.draw.circle(screen, RED, (z.rect.x+15, z.rect.y+20), 8)

    pygame.display.flip()

pygame.quit()