import pygame
import random

# ===================== 初始化设置 =====================
pygame.init()
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("趣味吃豆人")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# 玩家（吃豆人）参数
pac_radius = 16
pac_x, pac_y = WIDTH // 2, HEIGHT // 2
pac_speed = 4
dx, dy = 0, 0
mouth_angle = 0
mouth_dir = 1  # 嘴巴开合动画方向

# 豆子列表
dots = []
dot_radius = 4
for _ in range(60):
    dot_x = random.randint(30, WIDTH - 30)
    dot_y = random.randint(30, HEIGHT - 30)
    dots.append([dot_x, dot_y])

# 幽灵敌人
ghosts = []
ghost_size = 22
for _ in range(3):
    gx = random.randint(50, WIDTH - 50)
    gy = random.randint(50, HEIGHT - 50)
    gdx = random.choice([-1.5, 1.5])
    gdy = random.choice([-1.5, 1.5])
    ghosts.append([gx, gy, gdx, gdy])

score = 0
font = pygame.font.SysFont(None, 36)
game_over = False

# ===================== 游戏主循环 =====================
running = True
while running:
    clock.tick(FPS)
    screen.fill(BLACK)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if game_over and event.key == pygame.K_SPACE:
                # 重新开局
                pac_x, pac_y = WIDTH // 2, HEIGHT // 2
                dx, dy = 0, 0
                score = 0
                game_over = False
                dots.clear()
                for _ in range(60):
                    dot_x = random.randint(30, WIDTH - 30)
                    dot_y = random.randint(30, HEIGHT - 30)
                    dots.append([dot_x, dot_y])
                ghosts.clear()
                for _ in range(3):
                    gx = random.randint(50, WIDTH - 50)
                    gy = random.randint(50, HEIGHT - 50)
                    gdx = random.choice([-1.5, 1.5])
                    gdy = random.choice([-1.5, 1.5])
                    ghosts.append([gx, gy, gdx, gdy])

    if not game_over:
        # 方向控制
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            dx = -pac_speed
            dy = 0
        elif keys[pygame.K_RIGHT]:
            dx = pac_speed
            dy = 0
        elif keys[pygame.K_UP]:
            dy = -pac_speed
            dx = 0
        elif keys[pygame.K_DOWN]:
            dy = pac_speed
            dx = 0
        else:
            # 松开按键保持惯性（注释下面一行可以改成松开立刻停下）
            pass

        # 更新吃豆人位置 + 穿墙逻辑
        pac_x += dx
        pac_y += dy
        if pac_x < 0:
            pac_x = WIDTH
        if pac_x > WIDTH:
            pac_x = 0
        if pac_y < 0:
            pac_y = HEIGHT
        if pac_y > HEIGHT:
            pac_y = 0

        # 嘴巴开合动画
        mouth_angle += mouth_dir * 2
        if mouth_angle > 35 or mouth_angle < 0:
            mouth_dir *= -1

        # 绘制豆子 & 吃豆子碰撞
        for i in range(len(dots)-1, -1, -1):
            x, y = dots[i]
            pygame.draw.circle(screen, WHITE, (int(x), int(y)), dot_radius)
            dist = ((pac_x - x)**2 + (pac_y - y)**2)**0.5
            if dist < pac_radius + dot_radius:
                dots.pop(i)
                score += 10

        # 更新幽灵
        for ghost in ghosts:
            gx, gy, gdx, gdy = ghost
            gx += gdx
            gy += gdy
            # 边界反弹
            if gx < 0 or gx > WIDTH - ghost_size:
                ghost[2] *= -1
            if gy < 0 or gy > HEIGHT - ghost_size:
                ghost[3] *= -1
            ghost[0] = gx
            ghost[1] = gy
            # 绘制幽灵
            pygame.draw.rect(screen, RED, (gx, gy, ghost_size, ghost_size))
            # 幽灵碰撞 = 游戏结束
            dist_ghost = ((pac_x - (gx+ghost_size/2))**2 + (pac_y - (gy+ghost_size/2))**2)**0.5
            if dist_ghost < pac_radius + ghost_size/2:
                game_over = True

        # 绘制吃豆人（扇形实现张嘴效果）
        if dx > 0:
            start_angle = mouth_angle
            end_angle = 360 - mouth_angle
        elif dx < 0:
            start_angle = 180 + mouth_angle
            end_angle = 180 - mouth_angle
        elif dy < 0:
            start_angle = 90 + mouth_angle
            end_angle = 90 - mouth_angle
        else:
            start_angle = 270 + mouth_angle
            end_angle = 270 - mouth_angle

        rect = (pac_x - pac_radius, pac_y - pac_radius, pac_radius*2, pac_radius*2)
        pygame.draw.arc(screen, YELLOW, rect, start_angle * 3.1415 / 180, end_angle * 3.1415 / 180, pac_radius)

        # 绘制分数
        score_text = font.render(f"分数: {score}", True, WHITE)
        screen.blit(score_text, (10, 10))

        # 吃完所有豆子胜利
        if len(dots) == 0:
            win_text = font.render("恭喜通关！按空格重开", True, YELLOW)
            screen.blit(win_text, (WIDTH//2 - 130, HEIGHT//2))
            game_over = True
    else:
        # 游戏结束画面
        if len(dots) == 0:
            text = font.render("通关成功！按空格重新开始", True, YELLOW)
        else:
            text = font.render("被幽灵抓到！按空格重开", True, RED)
        screen.blit(text, (WIDTH//2 - 160, HEIGHT//2))

    pygame.display.flip()

pygame.quit()