import pygame
import random
import sys
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 400
GROUND_HEIGHT = 60
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BROWN = (139, 69, 19)
GRAY = (100, 100, 100)
YELLOW = (255, 255, 0)

# 设置窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("神庙逃亡 - 简易版")
clock = pygame.time.Clock()

# ---------- 字体设置（修复中文显示） ----------
def get_font(size, bold=False):
    """获取支持中文的字体，按优先级尝试"""
    font_paths = [
        "C:/Windows/Fonts/msyh.ttc",          # 微软雅黑 (Windows)
        "C:/Windows/Fonts/simhei.ttf",        # 黑体 (Windows)
        "C:/Windows/Fonts/simsun.ttc",        # 宋体 (Windows)
        "/System/Library/Fonts/PingFang.ttc", # 苹方 (macOS)
        "/System/Library/Fonts/STHeiti Light.ttc", # 华文黑体 (macOS)
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", # 文泉驿 (Linux)
        "/usr/share/fonts/truetype/arphic/uming.ttc", # AR PL UMing (Linux)
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # 备选西文字体
    ]
    
    for path in font_paths:
        if os.path.exists(path):
            try:
                if bold:
                    return pygame.font.Font(path, size)
                else:
                    return pygame.font.Font(path, size)
            except:
                continue
    
    # 如果所有字体都加载失败，使用系统默认字体（可能不支持中文）
    try:
        if bold:
            return pygame.font.SysFont("simhei,arial", size, bold=True)
        else:
            return pygame.font.SysFont("simhei,arial", size)
    except:
        return pygame.font.Font(None, size)

# 创建各种大小和样式的字体
font_small = get_font(30)
font_medium = get_font(40)
font_large = get_font(60)
font_title = get_font(70)

def show_text(text, color, x, y, font=None):
    """显示文本的辅助函数"""
    if font is None:
        font = font_small
    surface = font.render(text, True, color)
    screen.blit(surface, (x, y))

# 加载游戏图片（用绘图代替，无外部文件）
def create_player():
    """创建玩家角色（一个带眼睛的小人）"""
    surf = pygame.Surface((40, 60), pygame.SRCALPHA)
    # 身体
    pygame.draw.rect(surf, BLUE, (5, 20, 30, 40))
    # 头
    pygame.draw.circle(surf, (255, 200, 150), (20, 15), 15)
    # 眼睛
    pygame.draw.circle(surf, BLACK, (15, 12), 3)
    pygame.draw.circle(surf, BLACK, (25, 12), 3)
    # 嘴
    pygame.draw.arc(surf, BLACK, (10, 15, 20, 10), 0, 3.14, 2)
    # 腿
    pygame.draw.rect(surf, BLACK, (10, 55, 6, 10))
    pygame.draw.rect(surf, BLACK, (24, 55, 6, 10))
    return surf

def create_obstacle():
    """创建障碍物（尖刺或箱子）"""
    surf = pygame.Surface((30, 30), pygame.SRCALPHA)
    # 尖刺形状
    points = [(15, 0), (0, 30), (30, 30)]
    pygame.draw.polygon(surf, RED, points)
    pygame.draw.polygon(surf, (200, 0, 0), points, 2)
    return surf

def create_coin():
    """创建金币"""
    surf = pygame.Surface((20, 20), pygame.SRCALPHA)
    pygame.draw.circle(surf, YELLOW, (10, 10), 10)
    pygame.draw.circle(surf, (255, 215, 0), (10, 10), 8)
    pygame.draw.circle(surf, (255, 255, 150), (7, 7), 3)
    return surf

class Player:
    def __init__(self):
        self.image = create_player()
        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = WINDOW_HEIGHT - GROUND_HEIGHT - self.rect.height
        self.gravity = 0.6
        self.jump_power = -12
        self.velocity_y = 0
        self.is_jumping = False
        self.is_ducking = False  # 本版本未使用，保留扩展

    def jump(self):
        if not self.is_jumping:
            self.velocity_y = self.jump_power
            self.is_jumping = True

    def update(self):
        # 重力
        self.velocity_y += self.gravity
        self.rect.y += self.velocity_y

        # 地面碰撞
        ground_y = WINDOW_HEIGHT - GROUND_HEIGHT - self.rect.height
        if self.rect.y > ground_y:
            self.rect.y = ground_y
            self.velocity_y = 0
            self.is_jumping = False

    def draw(self, surface):
        surface.blit(self.image, self.rect)

    def get_rect(self):
        return self.rect

class Obstacle:
    def __init__(self, x):
        self.image = create_obstacle()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = WINDOW_HEIGHT - GROUND_HEIGHT - self.rect.height

    def update(self, speed):
        self.rect.x -= speed

    def draw(self, surface):
        surface.blit(self.image, self.rect)

    def get_rect(self):
        return self.rect

class Coin:
    def __init__(self, x, y):
        self.image = create_coin()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.collected = False

    def update(self, speed):
        self.rect.x -= speed

    def draw(self, surface):
        if not self.collected:
            surface.blit(self.image, self.rect)

    def get_rect(self):
        return self.rect

def main():
    # 游戏对象
    player = Player()
    obstacles = []
    coins = []
    
    # 游戏状态
    score = 0
    high_score = 0
    game_over = False
    game_start = False
    frame_count = 0
    
    # 障碍物生成参数
    obstacle_timer = 0
    coin_timer = 0
    speed = 6
    max_speed = 15
    
    # 背景地面
    ground_rect = pygame.Rect(0, WINDOW_HEIGHT - GROUND_HEIGHT, WINDOW_WIDTH, GROUND_HEIGHT)
    
    # 主循环
    running = True
    while running:
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if game_over:
                        # 重新开始
                        game_over = False
                        game_start = True
                        player = Player()
                        obstacles.clear()
                        coins.clear()
                        score = 0
                        speed = 6
                        obstacle_timer = 0
                        coin_timer = 0
                    else:
                        if not game_start:
                            game_start = True
                        player.jump()
                if event.key == pygame.K_r and game_over:
                    # 按R键重新开始（备用）
                    game_over = False
                    game_start = True
                    player = Player()
                    obstacles.clear()
                    coins.clear()
                    score = 0
                    speed = 6
                    obstacle_timer = 0
                    coin_timer = 0

        # 游戏更新
        if game_start and not game_over:
            frame_count += 1
            
            # 增加难度
            if frame_count % 300 == 0 and speed < max_speed:
                speed += 0.5
            
            # 生成障碍物（每60帧左右生成一个，随机）
            obstacle_timer += 1
            if obstacle_timer > random.randint(30, 80):
                obstacle_timer = 0
                # 随机决定是否生成障碍物
                if random.random() < 0.4:
                    obs = Obstacle(WINDOW_WIDTH + random.randint(0, 50))
                    obstacles.append(obs)
            
            # 生成金币（在障碍物附近或随机位置）
            coin_timer += 1
            if coin_timer > random.randint(20, 60):
                coin_timer = 0
                if random.random() < 0.3:
                    y_offset = random.choice([-40, -80, -120])
                    coin_y = WINDOW_HEIGHT - GROUND_HEIGHT - 30 + y_offset
                    # 确保金币在可见区域
                    if coin_y < 20:
                        coin_y = 20
                    coin = Coin(WINDOW_WIDTH + random.randint(0, 100), coin_y)
                    coins.append(coin)
            
            # 更新玩家
            player.update()
            
            # 更新障碍物
            for obs in obstacles[:]:
                obs.update(speed)
                if obs.rect.x < -50:
                    obstacles.remove(obs)
                    # 越过障碍物加分
                    score += 5
            
            # 更新金币
            for coin in coins[:]:
                coin.update(speed)
                if coin.rect.x < -30:
                    coins.remove(coin)
                # 金币收集检测
                if not coin.collected and player.get_rect().colliderect(coin.get_rect()):
                    coin.collected = True
                    coins.remove(coin)
                    score += 10
            
            # 碰撞检测（玩家与障碍物）
            for obs in obstacles:
                if player.get_rect().colliderect(obs.get_rect()):
                    game_over = True
                    if score > high_score:
                        high_score = score
                    break
            
            # 掉入深渊（如果玩家掉到地面以下，实际不会发生，因为地面碰撞）
            if player.rect.y > WINDOW_HEIGHT:
                game_over = True
                if score > high_score:
                    high_score = score
        
        # 绘制画面
        screen.fill(WHITE)
        
        # 绘制天空（渐变色效果）
        for i in range(WINDOW_HEIGHT - GROUND_HEIGHT):
            color = (135, 206, 235 - i // 10)
            if color[2] < 50:
                color = (135, 206, 50)
            pygame.draw.line(screen, color, (0, i), (WINDOW_WIDTH, i))
        
        # 绘制地面
        pygame.draw.rect(screen, BROWN, ground_rect)
        pygame.draw.rect(screen, (100, 50, 0), ground_rect, 3)
        # 地面纹理
        for i in range(0, WINDOW_WIDTH, 40):
            x = (i - frame_count * 2) % (WINDOW_WIDTH + 40) - 20
            pygame.draw.rect(screen, (120, 60, 10), (x, WINDOW_HEIGHT - GROUND_HEIGHT + 10, 20, 5))
        
        # 绘制玩家
        player.draw(screen)
        
        # 绘制障碍物
        for obs in obstacles:
            obs.draw(screen)
        
        # 绘制金币
        for coin in coins:
            coin.draw(screen)
        
        # ---------- 绘制文字（使用支持中文的字体） ----------
        show_text("分数: " + str(score), BLACK, 20, 20, font_small)
        show_text("最高分: " + str(high_score), BLACK, 20, 60, font_small)
        show_text("速度: " + f"{speed:.1f}", BLACK, 20, 100, font_small)
        
        # 游戏开始提示
        if not game_start and not game_over:
            show_text("按 空格键 开始", BLUE, WINDOW_WIDTH//2 - 150, WINDOW_HEIGHT//2 - 30, font_medium)
            show_text("按 空格键 跳跃", BLUE, WINDOW_WIDTH//2 - 130, WINDOW_HEIGHT//2 + 30, font_medium)
        
        # 游戏结束画面
        if game_over:
            # 半透明遮罩
            s = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 128))
            screen.blit(s, (0, 0))
            
            show_text("游戏结束", RED, WINDOW_WIDTH//2 - 140, WINDOW_HEIGHT//2 - 80, font_title)
            show_text("得分: " + str(score), WHITE, WINDOW_WIDTH//2 - 80, WINDOW_HEIGHT//2, font_medium)
            show_text("最高分: " + str(high_score), YELLOW, WINDOW_WIDTH//2 - 100, WINDOW_HEIGHT//2 + 50, font_medium)
            show_text("按 空格键 重新开始", WHITE, WINDOW_WIDTH//2 - 170, WINDOW_HEIGHT//2 + 110, font_medium)
        
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()