import pygame
import random
import sys

# --- 初始化 ---
pygame.init()

# --- 常量 ---
WIDTH, HEIGHT = 600, 800
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 50, 50)
GREEN = (50, 200, 50)
BLUE = (50, 50, 200)
PLATFORM_COLOR = (100, 100, 100)
PLAYER_COLOR = (255, 215, 0) # 金色

# 物理参数
GRAVITY = 0.5
JUMP_STRENGTH = -12
MOVE_SPEED = 7
PLATFORM_SPEED = 2 # 平台整体下降的速度
MAX_PLATFORMS = 10 # 屏幕上最多保留的平台数量

# 设置屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上100层 - Pygame版")
clock = pygame.time.Clock()

# --- 类定义 ---

class Player:
    def __init__(self):
        self.width = 30
        self.height = 30
        self.x = WIDTH // 2 - self.width // 2
        self.y = HEIGHT - 150
        self.vx = 0
        self.vy = 0
        self.on_ground = False
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def move(self, keys):
        # 左右移动
        if keys[pygame.K_LEFT]:
            self.vx = -MOVE_SPEED
        elif keys[pygame.K_RIGHT]:
            self.vx = MOVE_SPEED
        else:
            self.vx = 0

        # 应用重力
        self.vy += GRAVITY
        
        # 更新位置
        self.x += self.vx
        self.y += self.vy

        # 边界检查 (左右墙壁)
        if self.x < 0:
            self.x = 0
        if self.x > WIDTH - self.width:
            self.x = WIDTH - self.width

        # 更新矩形用于碰撞检测
        self.rect.topleft = (self.x, self.y)

    def jump(self):
        if self.on_ground:
            self.vy = JUMP_STRENGTH
            self.on_ground = False

    def draw(self, surface):
        pygame.draw.rect(surface, PLAYER_COLOR, self.rect)
        # 画个简单的眼睛，让它看起来像个角色
        pygame.draw.circle(surface, BLACK, (int(self.x + 8), int(self.y + 10)), 3)
        pygame.draw.circle(surface, BLACK, (int(self.x + 22), int(self.y + 10)), 3)

class Platform:
    def __init__(self, x, y, width):
        self.x = x
        self.y = y
        self.width = width
        self.height = 10
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def update(self):
        # 平台向下移动
        self.y += PLATFORM_SPEED
        self.rect.y = self.y

    def draw(self, surface):
        pygame.draw.rect(surface, PLATFORM_COLOR, self.rect)

# --- 辅助函数 ---
def check_collision(player, platforms):
    player.on_ground = False # 默认不在地面上
    
    # 只有当玩家向下落的时候才检测碰撞（防止跳到天花板卡住）
    if player.vy > 0:
        for plat in platforms:
            # 简单的矩形碰撞检测
            # 我们主要检测脚底和平台顶部的接触
            if (player.rect.bottom >= plat.rect.top and 
                player.rect.bottom <= plat.rect.top + 15 and # 允许一点容错
                player.rect.left < plat.rect.right and 
                player.rect.right > plat.rect.left):
                
                # 碰撞发生！
                player.y = plat.rect.top - player.height
                player.vy = 0
                player.on_ground = True
                player.jump() # 自动跳跃！
                break

def generate_platforms(platforms, score):
    # 如果平台数量不足，或者最上面的平台已经下降到一定位置，生成新平台
    last_platform_y = platforms[-1].y if platforms else HEIGHT - 50
    
    # 随着分数增加，平台间距可以稍微变大，增加难度
    gap = random.randint(80, 120) 
    
    if last_platform_y > gap:
        p_width = random.randint(100, 250)
        p_x = random.randint(0, WIDTH - p_width)
        p_y = last_platform_y - gap
        platforms.append(Platform(p_x, p_y, p_width))

# --- 主程序 ---
def main():
    running = True
    game_over = False
    
    player = Player()
    platforms = []
    
    # 初始化生成几个平台
    for i in range(5):
        p_width = random.randint(100, 250)
        p_x = random.randint(0, WIDTH - p_width)
        p_y = HEIGHT - 100 - i * 100
        platforms.append(Platform(p_x, p_y, p_width))

    score = 0
    high_score = 0

    while running:
        # 1. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and game_over:
                    # 重置游戏
                    main()
                    return

        if not game_over:
            # 2. 逻辑更新
            keys = pygame.key.get_pressed()
            player.move(keys)
            
            # 生成新平台
            generate_platforms(platforms, score)
            
            # 更新平台位置
            for plat in platforms:
                plat.update()
            
            # 移除掉出屏幕底部的平台
            platforms = [p for p in platforms if p.y < HEIGHT]
            
            # 碰撞检测
            check_collision(player, platforms)
            
            # 计算分数 (基于高度，越往上分越高)
            # 这里的逻辑是：如果玩家Y坐标小于屏幕高度的1/3，就开始计分
            if player.y < HEIGHT / 3:
                score += 1
                # 稍微加快下降速度增加难度
                if score % 500 == 0:
                    global PLATFORM_SPEED
                    PLATFORM_SPEED += 0.5

            # 死亡判定：掉出屏幕底部
            if player.y > HEIGHT:
                game_over = True
                if score > high_score:
                    high_score = score

        # 3. 绘图渲染
        screen.fill(WHITE)
        
        # 绘制平台
        for plat in platforms:
            plat.draw(screen)
            
        # 绘制玩家
        player.draw(screen)
        
        # 绘制UI
        score_text = pygame.font.Font(None, 36).render(f"分数: {score}", True, BLACK)
        screen.blit(score_text, (10, 10))
        
        if game_over:
            # 游戏结束遮罩
            overlay = pygame.Surface((WIDTH, HEIGHT))
            overlay.set_alpha(128)
            overlay.fill(BLACK)
            screen.blit(overlay, (0, 0))
            
            go_text = pygame.font.Font(None, 74).render("游戏结束", True, RED)
            score_final = pygame.font.Font(None, 48).render(f"最终得分: {score}", True, WHITE)
            restart_text = pygame.font.Font(None, 36).render("按 'R' 重新开始", True, GREEN)
            
            screen.blit(go_text, (WIDTH//2 - go_text.get_width()//2, HEIGHT//2 - 100))
            screen.blit(score_final, (WIDTH//2 - score_final.get_width()//2, HEIGHT//2))
            screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 80))

        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()