import pygame
import random

# 初始化pygame
pygame.init()

# 窗口尺寸
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("带边界贪吃蛇")

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

BLOCK_SIZE = 20
SPEED = 6

# ========== 修复字体报错！！这里改掉了 ==========
try:
    # 优先尝试加载系统默认字体
    font = pygame.font.Font("simhei.ttf", 35)
except:
    try:
        font = pygame.font.Font(None, 35)
    except:
        font = pygame.font.SysFont("arial", 35)

def show_score(score):
    text = font.render(f"分数: {score}", True, WHITE)
    screen.blit(text, [0, 0])

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 show_message(msg, color):
    mesg = font.render(msg, True, color)
    screen.blit(mesg, [WIDTH//6, HEIGHT//3])

def game_loop():
    game_over = False
    game_close = False

    # 蛇初始坐标
    x, y = WIDTH / 2, HEIGHT / 2
    dx, dy = 0, 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

    clock = pygame.time.Clock()

    while not game_over:
        # 死亡界面
        while game_close:
            screen.fill(BLACK)
            show_message("游戏结束！Q退出，C重开", RED)
            show_score(snake_len - 1)
            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 dx != BLOCK_SIZE:
                    dx = -BLOCK_SIZE
                    dy = 0
                elif event.key == pygame.K_RIGHT and dx != -BLOCK_SIZE:
                    dx = BLOCK_SIZE
                    dy = 0
                elif event.key == pygame.K_UP and dy != BLOCK_SIZE:
                    dy = -BLOCK_SIZE
                    dx = 0
                elif event.key == pygame.K_DOWN and dy != -BLOCK_SIZE:
                    dy = BLOCK_SIZE
                    dx = 0

        # 边界判定：碰到墙直接死亡
        if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
            game_close = True

        x += dx
        y += dy
        screen.fill(BLACK)

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

        # 蛇头入队
        head = [x, y]
        snake_body.append(head)
        if len(snake_body) > snake_len:
            del snake_body[0]

        # 撞到自己
        for seg in snake_body[:-1]:
            if seg == head:
                game_close = True

        draw_snake(BLOCK_SIZE, snake_body)
        show_score(snake_len - 1)
        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()
