import pygame
import random
import sys

# ===================== 国风颜色配置 =====================
BG_COLOR = (28, 33, 38)         # 深色古底色
BOARD_COLOR = (85, 65, 45)      # 木色边框
SNAKE_COLOR = (180, 150, 90)     # 鎏金蛇身
SNAKE_HEAD = (220, 180, 100)     # 蛇头亮色
FOOD_COLOR = (225, 185, 0)       #铜钱黄色
TEXT_COLOR = (230, 220, 200)    #宣纸白
RED_COLOR = (190, 30, 30)        #朱砂红

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

# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()

# =========【修复字体部分】多重兜底，解决海龟编辑器报错 =========
def get_font(size):
    try:
        # 优先微软雅黑（Windows默认自带）
        return pygame.font.SysFont("msyh", size)
    except:
        try:
            return pygame.font.SysFont("Microsoft YaHei", size)
        except:
            # 终极兜底：默认字体，虽然中文可能方框，但不会崩溃
            return pygame.font.Font(None, size)

font = get_font(24)
game_over_font = get_font(48)


class SnakeGame:
    def __init__(self):
        self.reset()

    def reset(self):
        # 蛇初始位置
        self.snake = [
            [WIDTH//2, HEIGHT//2],
            [WIDTH//2 - BLOCK_SIZE, HEIGHT//2],
            [WIDTH//2 - BLOCK_SIZE*2, HEIGHT//2]
        ]
        self.dir = [BLOCK_SIZE, 0]
        self.next_dir = [BLOCK_SIZE, 0]
        self.food = self.create_food()
        self.score = 0
        self.game_over = False

    def create_food(self):
        # 随机生成食物，对齐格子
        while True:
            x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
            y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
            food_pos = [x, y]
            if food_pos not in self.snake:
                return food_pos

    def draw(self):
        # 背景
        screen.fill(BG_COLOR)
        # 古风边框
        pygame.draw.rect(screen, BOARD_COLOR, (5, 5, WIDTH-10, HEIGHT-10), 4)

        # 绘制蛇
        for index, seg in enumerate(self.snake):
            x, y = seg
            if index == 0:
                # 蛇头
                pygame.draw.rect(screen, SNAKE_HEAD, (x, y, BLOCK_SIZE-1, BLOCK_SIZE-1), border_radius=6)
            else:
                pygame.draw.rect(screen, SNAKE_COLOR, (x, y, BLOCK_SIZE-1, BLOCK_SIZE-1), border_radius=4)

        # 绘制铜钱食物（外圈+圆心模拟铜钱）
        fx, fy = self.food
        pygame.draw.circle(screen, FOOD_COLOR, (fx + BLOCK_SIZE//2, fy + BLOCK_SIZE//2), BLOCK_SIZE//2 - 2)
        pygame.draw.circle(screen, BG_COLOR, (fx + BLOCK_SIZE//2, fy + BLOCK_SIZE//2), 4)

        # 绘制分数
        score_text = font.render(f"分数：{self.score}", True, TEXT_COLOR)
        screen.blit(score_text, (15, 10))

        # 游戏结束界面
        if self.game_over:
            over_text = game_over_font.render("游戏结束", True, RED_COLOR)
            tip_text = font.render("按空格键重新开始 | ESC退出", True, TEXT_COLOR)
            screen.blit(over_text, (WIDTH//2 - 100, HEIGHT//2 - 60))
            screen.blit(tip_text, (WIDTH//2 - 160, HEIGHT//2 + 10))

        pygame.display.update()

    def update(self):
        if self.game_over:
            return

        # 更新方向，禁止直接反向
        self.dir = self.next_dir
        head_x, head_y = self.snake[0]
        new_head = [head_x + self.dir[0], head_y + self.dir[1]]

        # 撞墙判定
        if new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT:
            self.game_over = True
            return
        # 撞到自己
        if new_head in self.snake:
            self.game_over = True
            return

        self.snake.insert(0, new_head)

        # 吃到食物
        if new_head == self.food:
            self.score += 10
            self.food = self.create_food()
        else:
            self.snake.pop()

    def handle_key(self, key):
        if self.game_over:
            if key == pygame.K_SPACE:
                self.reset()
            return

        # 方向控制，不能反向
        if key == pygame.K_UP and self.dir != [0, BLOCK_SIZE]:
            self.next_dir = [0, -BLOCK_SIZE]
        elif key == pygame.K_DOWN and self.dir != [0, -BLOCK_SIZE]:
            self.next_dir = [0, BLOCK_SIZE]
        elif key == pygame.K_LEFT and self.dir != [BLOCK_SIZE, 0]:
            self.next_dir = [-BLOCK_SIZE, 0]
        elif key == pygame.K_RIGHT and self.dir != [-BLOCK_SIZE, 0]:
            self.next_dir = [BLOCK_SIZE, 0]


def main():
    game = SnakeGame()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                game.handle_key(event.key)

        game.update()
        game.draw()
        clock.tick(SPEED)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()