import pygame
import random
import sys

# 初始化
pygame.init()
pygame.font.init()

# 窗口配置
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")

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

BLOCK_SIZE = 20
# 原先12，修改为7，速度明显变慢；想要更慢改成5、6就行
SPEED = 7

# 字体（规避系统字体报错）
try:
    font = pygame.font.Font(None, 30)
    tip_font = pygame.font.Font(None, 22)
except:
    font = pygame.font.SysFont("arial", 30, bold=False)
    tip_font = pygame.font.SysFont("arial", 22, bold=False)

clock = pygame.time.Clock()

def draw_text(text, color, x, y, font_obj):
    surf = font_obj.render(text, True, color)
    screen.blit(surf, (x, y))

def draw_snake(block_size, snake_body):
    for pos in snake_body:
        pygame.draw.rect(screen, GREEN, [pos[0], pos[1], block_size, block_size])
        pygame.draw.rect(screen, (0, 180, 0), [pos[0]+2, pos[1]+2, block_size-4, block_size-4])

def game_loop():
    game_over = False
    game_close = False

    x, y = WIDTH / 2, HEIGHT / 2
    x_change, y_change = 0, 0

    snake_body = []
    snake_length = 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("GAME OVER! Q=Quit  C=Restart", RED, 60, HEIGHT/2 - 30, font)
            draw_text(f"Score: {snake_length - 1}", WHITE, 220, HEIGHT/2 + 10, font)
            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 < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
            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_length:
            del snake_body[0]

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

        draw_snake(BLOCK_SIZE, snake_body)
        draw_text(f"Score: {snake_length - 1}", WHITE, 10, 10, tip_font)
        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_length += 1

        clock.tick(SPEED)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    game_loop()