import pygame
import random
import sys
import os

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("跑酷游戏 - 跳跃冒险")

# 颜色定义
SKY_BLUE = (135, 206, 235)
GROUND_COLOR = (101, 67, 33)
GRASS_COLOR = (76, 175, 80)
PLAYER_COLOR = (220, 20, 60)
OBSTACLE_COLOR = (50, 50, 50)
CLOUD_COLOR = (255, 255, 255)
TEXT_COLOR = (255, 255, 255)
BACKGROUND_COLOR = (135, 206, 235)

# 游戏参数
GRAVITY = 0.8
JUMP_STRENGTH = -15
BASE_GAME_SPEED = 5
GROUND_HEIGHT = 50

# 加载中文字体函数


def load_chinese_font():
    # 尝试多种字体路径
    font_paths = [
        # Windows 常见中文字体路径
        "C:/Windows/Fonts/simhei.ttf",  # 黑体
        "C:/Windows/Fonts/simsun.ttc",  # 宋体
        "C:/Windows/Fonts/msyh.ttc",    # 微软雅黑
        "C:/Windows/Fonts/msyhbd.ttc",  # 微软雅黑 Bold
        "C:/Windows/Fonts/simfang.ttf",  # 仿宋
        "C:/Windows/Fonts/simkai.ttf",  # 楷体

        # macOS 常见中文字体路径
        "/System/Library/Fonts/PingFang.ttc",
        "/System/Library/Fonts/STHeiti Light.ttc",
        "/System/Library/Fonts/STHeiti Medium.ttc",

        # Linux 常见中文字体路径
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",

        # 如果以上都没有，尝试使用默认字体
        None
    ]

    for font_path in font_paths:
        try:
            if font_path is None:
                # 使用Pygame默认字体
                return pygame.font.Font(None, 36)
            elif os.path.exists(font_path):
                # 尝试加载字体文件
                return pygame.font.Font(font_path, 36)
        except Exception as e:
            print(f"无法加载字体 {font_path}: {e}")
            continue

    # 如果所有字体都失败，返回None
    print("警告: 无法加载中文字体，将使用默认字体")
    return pygame.font.Font(None, 36)

# 玩家类


class Player:
    def __init__(self):
        self.width = 40
        self.height = 60
        self.x = 100
        self.y = HEIGHT - GROUND_HEIGHT - self.height
        self.vel_y = 0
        self.jumping = False
        self.jump_count = 0

    def jump(self):
        if self.jump_count < 2:  # 允许二段跳
            self.vel_y = JUMP_STRENGTH
            self.jumping = True
            self.jump_count += 1

    def update(self):
        # 应用重力
        self.vel_y += GRAVITY
        self.y += self.vel_y

        # 地面碰撞检测
        ground_level = HEIGHT - GROUND_HEIGHT - self.height
        if self.y > ground_level:
            self.y = ground_level
            self.vel_y = 0
            self.jumping = False
            self.jump_count = 0

    def draw(self, surface):
        # 绘制角色身体
        pygame.draw.rect(surface, PLAYER_COLOR,
                         (self.x, self.y, self.width, self.height), 0, 10)

        # 绘制角色眼睛
        eye_radius = 4
        pygame.draw.circle(surface, (255, 255, 255),
                           (self.x + 10, self.y + 15), eye_radius)
        pygame.draw.circle(surface, (255, 255, 255),
                           (self.x + 30, self.y + 15), eye_radius)

        # 绘制角色腿
        leg_height = 10
        pygame.draw.rect(surface, PLAYER_COLOR, (self.x + 5,
                         self.y + self.height, 10, leg_height))
        pygame.draw.rect(surface, PLAYER_COLOR, (self.x + 25,
                         self.y + self.height, 10, leg_height))

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

# 障碍物类


class Obstacle:
    def __init__(self, x):
        self.width = random.randint(20, 40)
        self.height = random.randint(30, 60)
        self.x = x
        self.y = HEIGHT - GROUND_HEIGHT - self.height
        self.passed = False

    def update(self, game_speed):
        self.x -= game_speed

    def draw(self, surface):
        pygame.draw.rect(surface, OBSTACLE_COLOR,
                         (self.x, self.y, self.width, self.height), 0, 5)

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

# 云朵类（装饰元素）


class Cloud:
    def __init__(self):
        self.x = WIDTH + random.randint(0, 300)
        self.y = random.randint(20, 150)
        self.speed = random.uniform(0.5, 1.5)
        self.size = random.randint(30, 60)

    def update(self, game_speed):
        self.x -= self.speed + game_speed * 0.1
        if self.x < -100:
            self.x = WIDTH + random.randint(0, 100)
            self.y = random.randint(20, 150)

    def draw(self, surface):
        # 绘制云朵
        pygame.draw.circle(surface, CLOUD_COLOR,
                           (int(self.x), int(self.y)), self.size//2)
        pygame.draw.circle(surface, CLOUD_COLOR, (int(
            self.x) + self.size//2, int(self.y)), self.size//2)
        pygame.draw.circle(surface, CLOUD_COLOR, (int(
            self.x) - self.size//2, int(self.y)), self.size//2)
        pygame.draw.rect(surface, CLOUD_COLOR, (int(
            self.x) - self.size//2, int(self.y) - self.size//4, self.size, self.size//2))

# 游戏类


class Game:
    def __init__(self):
        self.player = Player()
        self.obstacles = []
        self.clouds = [Cloud() for _ in range(5)]
        self.score = 0
        self.game_over = False
        self.obstacle_timer = 0
        self.obstacle_frequency = 60  # 帧数，控制障碍物生成频率

        # 加载中文字体
        self.font = load_chinese_font()
        if self.font is None:
            # 如果无法加载中文字体，使用默认字体
            self.font = pygame.font.Font(None, 36)
            self.big_font = pygame.font.Font(None, 72)
        else:
            # 使用相同字体但不同大小
            self.big_font = self.font
            self.big_font = pygame.font.Font(self.font.font.get_font_name(), 72) if hasattr(
                self.font, 'font') else pygame.font.Font(None, 72)

    def get_game_speed(self):
        return BASE_GAME_SPEED + self.score // 20

    def update(self):
        if self.game_over:
            return

        # 获取当前游戏速度
        current_game_speed = self.get_game_speed()

        # 更新玩家
        self.player.update()

        # 更新云朵
        for cloud in self.clouds:
            cloud.update(current_game_speed)

        # 生成障碍物
        self.obstacle_timer += 1
        if self.obstacle_timer > self.obstacle_frequency:
            self.obstacles.append(Obstacle(WIDTH))
            self.obstacle_timer = 0
            # 随着分数增加，加快障碍物生成速度
            self.obstacle_frequency = max(30, 60 - self.score // 10)

        # 更新障碍物
        for obstacle in self.obstacles[:]:
            obstacle.update(current_game_speed)

            # 移除屏幕外的障碍物
            if obstacle.x < -obstacle.width:
                self.obstacles.remove(obstacle)

            # 检查是否通过障碍物
            if not obstacle.passed and obstacle.x < self.player.x:
                obstacle.passed = True
                self.score += 1

            # 碰撞检测
            if self.player.get_rect().colliderect(obstacle.get_rect()):
                self.game_over = True

    def draw(self, surface):
        # 绘制天空背景
        surface.fill(BACKGROUND_COLOR)

        # 绘制云朵
        for cloud in self.clouds:
            cloud.draw(surface)

        # 绘制地面
        pygame.draw.rect(surface, GROUND_COLOR, (0, HEIGHT -
                         GROUND_HEIGHT, WIDTH, GROUND_HEIGHT))
        pygame.draw.rect(surface, GRASS_COLOR,
                         (0, HEIGHT - GROUND_HEIGHT, WIDTH, 10))

        # 绘制障碍物
        for obstacle in self.obstacles:
            obstacle.draw(surface)

        # 绘制玩家
        self.player.draw(surface)

        # 绘制分数
        score_text = self.font.render(f"分数: {self.score}", True, TEXT_COLOR)
        surface.blit(score_text, (20, 20))

        # 绘制游戏速度
        speed_text = self.font.render(
            f"速度: {self.get_game_speed()}", True, TEXT_COLOR)
        surface.blit(speed_text, (20, 60))

        # 绘制操作说明
        controls_text = self.font.render(
            "空格键/上箭头: 跳跃 (可二段跳)", True, TEXT_COLOR)
        surface.blit(controls_text, (WIDTH - 400, 20))

        restart_text = self.font.render("R键: 重新开始", True, TEXT_COLOR)
        surface.blit(restart_text, (WIDTH - 400, 60))

        # 游戏结束画面
        if self.game_over:
            # 半透明覆盖层
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 150))
            surface.blit(overlay, (0, 0))

            # 游戏结束文本
            game_over_text = self.big_font.render("游戏结束!", True, (255, 50, 50))
            surface.blit(game_over_text, (WIDTH//2 -
                         game_over_text.get_width()//2, HEIGHT//2 - 100))

            score_text = self.font.render(
                f"最终分数: {self.score}", True, TEXT_COLOR)
            surface.blit(
                score_text, (WIDTH//2 - score_text.get_width()//2, HEIGHT//2))

            restart_text = self.font.render("按R键重新开始游戏", True, TEXT_COLOR)
            surface.blit(restart_text, (WIDTH//2 -
                         restart_text.get_width()//2, HEIGHT//2 + 60))

            quit_text = self.font.render("按ESC键退出游戏", True, TEXT_COLOR)
            surface.blit(
                quit_text, (WIDTH//2 - quit_text.get_width()//2, HEIGHT//2 + 100))

    def restart(self):
        self.__init__()


# 创建游戏实例
game = Game()
clock = pygame.time.Clock()

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_r:  # 统一重新开始逻辑
                game.restart()
            elif event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                if not game.game_over:
                    game.player.jump()

    # 更新游戏状态
    game.update()

    # 绘制游戏
    game.draw(screen)

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(60)

# 退出游戏
pygame.quit()
sys.exit()
