import pygame
import random

# 初始化pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 640, 480
BLOCK_SIZE = 20
SPEED = 10

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

# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")

# 时钟控制帧率
clock = pygame.time.Clock()

# 字体
font = pygame.font.SysFont(None, 36)


# 绘制文字
def draw_text(text, color, x, y):
    txt_surface = font.render(text, True, color)
    screen.blit(txt_surface, (x, y))


# 绘制蛇
def draw_snake(block_size, snake_list):
    for pos in snake_list:
        pygame.draw.rect(screen, GREEN, [pos[0], pos[1], block_size, block_size])


# 主游戏函数
def game_loop():
    game_over = False
    game_close = False

    # 蛇初始位置
    x = WIDTH / 2
    y = HEIGHT / 2

    # 移动偏移
    x_change = 0
    y_change = 0

    # 蛇身体列表
    snake_body = []
    snake_len = 1

    # 随机生成食物
    food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
    food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE

    while not game_over:
        # 游戏结束界面
        while game_close:
            screen.fill(BLACK)
            draw_text("游戏结束! 按 Q 退出 或 C 重新开始", RED, 80, HEIGHT / 2)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()
                if event.type == pygame.QUIT:
                    game_over = True
                    game_close = False

        # 监听退出、按键事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and x_change != BLOCK_SIZE:
                    x_change = -BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_RIGHT and x_change != -BLOCK_SIZE:
                    x_change = BLOCK_SIZE
                    y_change = 0
                elif event.key == pygame.K_UP and y_change != BLOCK_SIZE:
                    y_change = -BLOCK_SIZE
                    x_change = 0
                elif event.key == pygame.K_DOWN and y_change != -BLOCK_SIZE:
                    y_change = BLOCK_SIZE
                    x_change = 0

        # 撞边界判定
        if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
            game_close = True

        # 更新位置
        x += x_change
        y += y_change
        screen.fill(BLACK)

        # 绘制食物
        pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])

        # 更新蛇头
        snake_head = [x, y]
        snake_body.append(snake_head)

        # 控制蛇长度
        if len(snake_body) > snake_len:
            del snake_body[0]

        # 撞到自身判定
        for segment in snake_body[:-1]:
            if segment == snake_head:
                game_close = True

        # 绘制蛇
        draw_snake(BLOCK_SIZE, snake_body)
        # 绘制分数
        draw_text(f"分数: {snake_len - 1}", WHITE, 10, 10)

        pygame.display.update()

        # 吃到食物
        if x == food_x and y == food_y:
            food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
            snake_len += 1

        clock.tick(SPEED)

    pygame.quit()
    quit()


# 启动游戏
if __name__ == "__main__":
    game_loop()