import pygame
import sys
import random
import time

# 初始化pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
clock = pygame.time.Clock()
FPS = 10

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 120, 255)
DARK_GREEN = (0, 180, 0)
GRAY = (100, 100, 100)
YELLOW = (255, 255, 0)
ORANGE = (255, 165, 0)

# 游戏配置
GRID_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE

# 方向
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

# 创建字体
try:
    # 修复字体加载，使用None或系统字体
    font_large = pygame.font.Font(None, 48)
    font_medium = pygame.font.Font(None, 36)
    font_small = pygame.font.Font(None, 24)
except:
    # 如果上面的方法失败，使用系统字体
    font_large = pygame.font.SysFont(None, 48)
    font_medium = pygame.font.SysFont(None, 36)
    font_small = pygame.font.SysFont(None, 24)

# 蛇类
class Snake:
    def __init__(self):
        self.reset()
        
    def reset(self):
        self.length = 3
        self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
        self.direction = RIGHT
        self.score = 0
        self.grow_to = 3
        
    def get_head_position(self):
        return self.positions[0]
    
    def turn(self, point):
        if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
            return
        else:
            self.direction = point
    
    def move(self):
        head = self.get_head_position()
        x, y = self.direction
        new_x = (head[0] + x) % GRID_WIDTH
        new_y = (head[1] + y) % GRID_HEIGHT
        new_position = (new_x, new_y)
        
        # 检查是否撞到自己
        if new_position in self.positions[1:]:
            return False
            
        self.positions.insert(0, new_position)
        
        if len(self.positions) > self.grow_to:
            self.positions.pop()
            
        return True
    
    def grow(self):
        self.grow_to += 1
        self.score += 10
        
    def draw(self, surface):
        for i, p in enumerate(self.positions):
            rect = pygame.Rect((p[0] * GRID_SIZE, p[1] * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
            
            if i == 0:  # 蛇头
                pygame.draw.rect(surface, GREEN, rect)
                pygame.draw.rect(surface, DARK_GREEN, rect, 1)
                
                # 绘制眼睛
                if self.direction == RIGHT:
                    eye_rect1 = pygame.Rect((p[0] * GRID_SIZE + GRID_SIZE - 6, p[1] * GRID_SIZE + 5), (3, 3))
                    eye_rect2 = pygame.Rect((p[0] * GRID_SIZE + GRID_SIZE - 6, p[1] * GRID_SIZE + GRID_SIZE - 8), (3, 3))
                elif self.direction == LEFT:
                    eye_rect1 = pygame.Rect((p[0] * GRID_SIZE + 3, p[1] * GRID_SIZE + 5), (3, 3))
                    eye_rect2 = pygame.Rect((p[0] * GRID_SIZE + 3, p[1] * GRID_SIZE + GRID_SIZE - 8), (3, 3))
                elif self.direction == UP:
                    eye_rect1 = pygame.Rect((p[0] * GRID_SIZE + 5, p[1] * GRID_SIZE + 3), (3, 3))
                    eye_rect2 = pygame.Rect((p[0] * GRID_SIZE + GRID_SIZE - 8, p[1] * GRID_SIZE + 3), (3, 3))
                else:  # DOWN
                    eye_rect1 = pygame.Rect((p[0] * GRID_SIZE + 5, p[1] * GRID_SIZE + GRID_SIZE - 6), (3, 3))
                    eye_rect2 = pygame.Rect((p[0] * GRID_SIZE + GRID_SIZE - 8, p[1] * GRID_SIZE + GRID_SIZE - 6), (3, 3))
                    
                pygame.draw.rect(surface, BLACK, eye_rect1)
                pygame.draw.rect(surface, BLACK, eye_rect2)
            else:  # 蛇身
                color_factor = 1.0 - (i / len(self.positions) * 0.3)
                body_color = (
                    int(GREEN[0] * color_factor),
                    int(GREEN[1] * color_factor),
                    int(GREEN[2] * color_factor)
                )
                pygame.draw.rect(surface, body_color, rect)
                pygame.draw.rect(surface, DARK_GREEN, rect, 1)

# 食物类
class Food:
    def __init__(self):
        self.position = (0, 0)
        self.color = RED
        self.randomize_position()
        
    def randomize_position(self):
        self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
        
    def draw(self, surface):
        rect = pygame.Rect((self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
        pygame.draw.rect(surface, self.color, rect)
        pygame.draw.rect(surface, WHITE, rect, 1)
        
        # 绘制食物内部的装饰
        inner_rect = pygame.Rect(
            self.position[0] * GRID_SIZE + 4,
            self.position[1] * GRID_SIZE + 4,
            GRID_SIZE - 8,
            GRID_SIZE - 8
        )
        pygame.draw.rect(surface, (255, 200, 200), inner_rect)

# 游戏主类
class Game:
    def __init__(self):
        self.snake = Snake()
        self.food = Food()
        self.game_over = False
        self.paused = False
        self.high_score = 0
        
    def update(self):
        if self.game_over or self.paused:
            return
            
        if not self.snake.move():
            self.game_over = True
            if self.snake.score > self.high_score:
                self.high_score = self.snake.score
            return
            
        # 检查是否吃到食物
        if self.snake.get_head_position() == self.food.position:
            self.snake.grow()
            self.food.randomize_position()
            
            # 确保食物不出现在蛇身上
            while self.food.position in self.snake.positions:
                self.food.randomize_position()
    
    def draw(self, surface):
        surface.fill(BLACK)
        
        # 绘制网格
        for x in range(0, SCREEN_WIDTH, GRID_SIZE):
            pygame.draw.line(surface, GRAY, (x, 0), (x, SCREEN_HEIGHT))
        for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
            pygame.draw.line(surface, GRAY, (0, y), (SCREEN_WIDTH, y))
        
        # 绘制食物
        self.food.draw(surface)
        
        # 绘制蛇
        self.snake.draw(surface)
        
        # 绘制分数
        score_text = font_medium.render(f"分数: {self.snake.score}", True, WHITE)
        high_score_text = font_small.render(f"最高分: {self.high_score}", True, GRAY)
        length_text = font_small.render(f"长度: {len(self.snake.positions)}", True, GREEN)
        
        surface.blit(score_text, (10, 10))
        surface.blit(high_score_text, (10, 50))
        surface.blit(length_text, (SCREEN_WIDTH - 100, 10))
        
        # 绘制控制提示
        if self.paused:
            pause_text = font_small.render("游戏已暂停 (P键继续)", True, YELLOW)
            surface.blit(pause_text, (SCREEN_WIDTH // 2 - pause_text.get_width() // 2, 10))
        else:
            pause_text = font_small.render("P键暂停", True, GRAY)
            surface.blit(pause_text, (SCREEN_WIDTH // 2 - pause_text.get_width() // 2, 10))
        
        # 绘制游戏结束信息
        if self.game_over:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.set_alpha(128)
            overlay.fill(BLACK)
            surface.blit(overlay, (0, 0))
            
            game_over_text = font_large.render("游戏结束!", True, RED)
            final_score_text = font_medium.render(f"最终分数: {self.snake.score}", True, YELLOW)
            restart_text = font_small.render("按R键重新开始，ESC键退出", True, WHITE)
            
            surface.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 2 - 60))
            surface.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2))
            surface.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, SCREEN_HEIGHT // 2 + 50))
    
    def handle_keys(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                    
                elif event.key == pygame.K_p:
                    self.paused = not self.paused
                    
                elif event.key == pygame.K_r and self.game_over:
                    self.__init__()  # 重置游戏
                    
                elif not self.paused and not self.game_over:
                    if event.key == pygame.K_UP:
                        self.snake.turn(UP)
                    elif event.key == pygame.K_DOWN:
                        self.snake.turn(DOWN)
                    elif event.key == pygame.K_LEFT:
                        self.snake.turn(LEFT)
                    elif event.key == pygame.K_RIGHT:
                        self.snake.turn(RIGHT)

# 主函数
def main():
    game = Game()
    
    while True:
        game.handle_keys()
        game.update()
        game.draw(screen)
        pygame.display.update()
        
        if game.paused or game.game_over:
            clock.tick(5)  # 暂停或游戏结束时降低帧率
        else:
            clock.tick(FPS)

if __name__ == "__main__":
    main()