import pygame
import random
import sys

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

# 颜色常量
WHITE = (255, 255, 255)
GREEN = (80, 180, 60)
DARK_GREEN = (40, 100, 30)
BROWN = (120, 80, 40)
SKY_BLUE = (140, 200, 255)
RED = (220, 40, 40)
YELLOW = (255, 220, 0)
GRAY = (100, 100, 100)

# 草地网格
GRID_COLS = 9
GRID_ROWS = 5
CELL_W = 80
CELL_H = 100
OFFSET_X = 80
OFFSET_Y = 80

# 阳光资源
sun = 150
try:
    sun_font = pygame.font.SysFont("simhei", 28)
    tip_font = pygame.font.SysFont("simhei", 22)
except:
    sun_font = pygame.font.SysFont("Arial", 28)
    tip_font = pygame.font.SysFont("Arial", 22)

# ===================== 游戏类 =====================
class Plant:
    def __init__(self, col, row):
        self.col = col
        self.row = row
        self.x = OFFSET_X + col * CELL_W + CELL_W // 2
        self.y = OFFSET_Y + row * CELL_H + CELL_H // 2
        self.hp = 100
        self.cd = 0
        self.cd_max = 90
        self.cost = 50

    def update(self):
        if self.cd > 0:
            self.cd -= 1

    def draw(self):
        pygame.draw.circle(screen, GREEN, (self.x, self.y - 15), 22)
        pygame.draw.rect(screen, DARK_GREEN, (self.x - 8, self.y, 16, 30))


class Peashooter(Plant):
    def __init__(self, col, row):
        super().__init__(col, row)
        self.cost = 100

    def shoot(self):
        if self.cd <= 0:
            self.cd = self.cd_max
            return Bullet(self.x + 25, self.y - 10, self.row)
        return None


class Bullet:
    def __init__(self, x, y, row):
        self.x = x
        self.y = y
        self.row = row
        self.speed = 6
        self.dmg = 25

    def update(self):
        self.x += self.speed

    def draw(self):
        pygame.draw.circle(screen, YELLOW, (int(self.x), int(self.y)), 6)


class Zombie:
    def __init__(self, row):
        self.row = row
        self.y = OFFSET_Y + row * CELL_H + CELL_H // 2
        self.x = WIDTH + 30
        self.hp = 100
        self.speed = 0.4
        self.attack_cd = 0

    def update(self, plants_in_row):
        hit_plant = None
        for p in plants_in_row:
            if p.row == self.row and abs(p.x - self.x) < 35:
                hit_plant = p
                break
        if hit_plant:
            self.attack_cd += 1
            if self.attack_cd > 60:
                hit_plant.hp -= 20
                self.attack_cd = 0
        else:
            self.x -= self.speed

    def draw(self):
        pygame.draw.circle(screen, GRAY, (int(self.x), int(self.y)-12), 20)
        pygame.draw.rect(screen, GRAY, (self.x-12, self.y+8, 24, 30))


class SunDrop:
    def __init__(self):
        self.x = random.randint(OFFSET_X, OFFSET_X + GRID_COLS * CELL_W)
        self.y = -20
        self.target_y = random.randint(OFFSET_Y, OFFSET_Y + GRID_ROWS * CELL_H)
        self.speed = 1.2
        self.life = 400

    def update(self):
        if self.y < self.target_y:
            self.y += self.speed
        self.life -= 1

    def draw(self):
        pygame.draw.circle(screen, YELLOW, (int(self.x), int(self.y)), 14)

# ===================== 全局变量 =====================
plants = []
bullets = []
zombies = []
sundrops = []
selected = None
spawn_timer = 0
sun_drop_timer = 0
game_over = False
game_win = False

# 工具函数
def get_grid(mx, my):
    c = (mx - OFFSET_X) // CELL_W
    r = (my - OFFSET_Y) // CELL_H
    if 0 <= c < GRID_COLS and 0 <= r < GRID_ROWS:
        return c, r
    return None

def has_plant(col, row):
    for p in plants:
        if p.col == col and p.row == row:
            return True
    return False

# ===================== 主循环 =====================
while True:
    screen.fill(SKY_BLUE)
    # 绘制草地格子
    for r in range(GRID_ROWS):
        for c in range(GRID_COLS):
            rect = (OFFSET_X + c*CELL_W, OFFSET_Y + r*CELL_H, CELL_W-2, CELL_H-2)
            if (r + c) % 2 == 0:
                pygame.draw.rect(screen, GREEN, rect)
            else:
                pygame.draw.rect(screen, (100, 200, 75), rect)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN and not game_over and not game_win:
            mx, my = pygame.mouse.get_pos()
            # 拾取阳光
            for s in sundrops[:]:
                dist = ((mx - s.x)**2 + (my - s.y)**2)**0.5
                if dist < 18:
                    sun += 25
                    sundrops.remove(s)
                    break
            # 选择豌豆射手卡片
            if 10 <= mx <= 110 and 10 <= my <= 60:
                selected = "peashooter"
            # 放置植物
            g = get_grid(mx, my)
            if g and selected == "peashooter":
                col, row = g
                if not has_plant(col, row) and sun >= 100:
                    plants.append(Peashooter(col, row))
                    sun -= 100
                    selected = None

    if not game_over and not game_win:
        # 生成掉落阳光
        sun_drop_timer += 1
        if sun_drop_timer > 220:
            sundrops.append(SunDrop())
            sun_drop_timer = 0
        # 生成僵尸
        spawn_timer += 1
        if spawn_timer > 350:
            zombies.append(Zombie(random.randint(0, GRID_ROWS-1)))
            spawn_timer = 0

        # 更新阳光
        for s in sundrops[:]:
            s.update()
            if s.life <= 0:
                sundrops.remove(s)
            else:
                s.draw()

        # 更新植物，发射子弹
        for p in plants[:]:
            p.update()
            b = p.shoot()
            if b:
                bullets.append(b)
            p.draw()
            if p.hp <= 0:
                plants.remove(p)

        # 更新子弹，碰撞僵尸
        for b in bullets[:]:
            b.update()
            hit = None
            for z in zombies:
                if z.row == b.row and abs(z.x - b.x) < 22:
                    hit = z
                    break
            if hit:
                hit.hp -= b.dmg
                bullets.remove(b)
                if hit.hp <= 0:
                    zombies.remove(hit)
            else:
                if b.x > WIDTH:
                    bullets.remove(b)
                else:
                    b.draw()

        # 更新僵尸移动、啃植物
        for z in zombies[:]:
            z.update(plants)
            z.draw()
            if z.x < 60:
                game_over = True

    # UI文字
    sun_text = sun_font.render(f"☀ 阳光：{sun}", True, WHITE)
    screen.blit(sun_text, (10, 10))
    # 植物卡片
    card_rect = pygame.Rect(10, 10, 100, 50)
    pygame.draw.rect(screen, BROWN, card_rect)
    card_text = tip_font.render("豌豆射手 100", True, WHITE)
    screen.blit(card_text, (15, 22))

    tip = tip_font.render("点击卡片选中，再点击草地放置；点击阳光收集", True, WHITE)
    screen.blit(tip, (130, 20))

    # 结束提示
    if game_over:
        over_text = sun_font.render("游戏结束！僵尸吃掉你的脑子！", True, RED)
        screen.blit(over_text, (WIDTH//2 - 180, HEIGHT//2))
    if game_win:
        win_text = sun_font.render("胜利！你守住了花园！", True, YELLOW)
        screen.blit(win_text, (WIDTH//2 - 140, HEIGHT//2))

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