import pygame
import random
import sys

# 初始化pygame
pygame.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)
BLUE = (0, 0, 255)

# 字体（支持中文）
try:
    font = pygame.font.Font("simhei.ttf", 35)
except:
    font = pygame.font.SysFont("Microsoft YaHei", 35)
small_font = pygame.font.SysFont("Microsoft YaHei", 25)

# 蛇方块大小、速度
BLOCK_SIZE = 20
SPEED = 12

clock = pygame.time.Clock()

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

def draw_snake(block_size, snake_list):
    """绘制蛇身体"""
    for x in snake_list:
        pygame.draw.rect(screen, GREEN, [x[0], x[1], block_size, block_size])

def game_message(msg, color, y_offset=0):
    """屏幕中央显示提示文字"""
    mesg = font.render(msg, True, color)
    screen.blit(mesg, [WIDTH/6, HEIGHT/3 + y_offset])

def game_loop():
    game_over = False
    game_close = False

    # 蛇初始坐标
    x1, y1 = WIDTH / 2, HEIGHT / 2
    x1_change, y1_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)
            game_message("游戏结束！按Q退出，按C重新开始", RED)
            show_score(snake_length - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:  # Q退出
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:  # 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 x1_change != BLOCK_SIZE:
                    x1_change = -BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_RIGHT and x1_change != -BLOCK_SIZE:
                    x1_change = BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_UP and y1_change != BLOCK_SIZE:
                    y1_change = -BLOCK_SIZE
                    x1_change = 0
                elif event.key == pygame.K_DOWN and y1_change != -BLOCK_SIZE:
                    y1_change = BLOCK_SIZE
                    x1_change = 0

        # 撞墙判定
        if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
            game_close = True

        x1 += x1_change
        y1 += y1_change
        screen.fill(BLACK)

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

        # 更新蛇头
        snake_head = [x1, y1]
        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)
        show_score(snake_length - 1)

        pygame.display.update()

        # 吃到食物，加长身体+新食物
        if x1 == food_x and y1 == 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()