import pygame
import random

# 初始化
pygame.init()
WIDTH, HEIGHT = 400, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")
clock = pygame.time.Clock()
FPS = 60

# 颜色
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)

# 玩家
player_size = 30
player_x = WIDTH//2 - player_size//2
player_y = HEIGHT - 100
player_vel = 5
jump_vel = -15
gravity = 0.8
is_jump = False
vel_y = 0

# 台阶
platforms = []
plat_w = 70
plat_h = 15

# 生成初始台阶
def init_plat():
    platforms.clear()
    platforms.append([WIDTH//2-plat_w//2, HEIGHT-70, plat_w, plat_h])
    for i in range(10):
        x = random.randint(0, WIDTH-plat_w)
        y = HEIGHT - i*60 - 120
        platforms.append([x, y, plat_w, plat_h])

init_plat()
score = 0

# 游戏主循环
run = True
while run:
    clock.tick(FPS)
    win.fill((30,30,50))

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and not is_jump:
                is_jump = True
                vel_y = jump_vel

    # 左右移动
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x>0:
        player_x -= player_vel
    if keys[pygame.K_RIGHT] and player_x<WIDTH-player_size:
        player_x += player_vel

    # 跳跃重力
    if is_jump:
        vel_y += gravity
        player_y += vel_y
        # 落地判断
        for p in platforms:
            px, py, pw, ph = p
            if vel_y>0:
                if (player_y+player_size >= py) and (player_y+player_size <= py+ph):
                    if player_x+player_size > px and player_x < px+pw:
                        player_y = py - player_size
                        is_jump = False
                        vel_y = 0
                        break

    # 视角上移（往上爬）
    if player_y < HEIGHT//2:
        offset = HEIGHT//2 - player_y
        player_y = HEIGHT//2
        score += offset
        for p in platforms:
            p[1] += offset
        # 删除出屏台阶
        for i in range(len(platforms)-1, -1, -1):
            if platforms[i][1] > HEIGHT:
                platforms.pop(i)
        # 生成新台阶
        while len(platforms) < 12:
            new_x = random.randint(0, WIDTH-plat_w)
            new_y = random.randint(-50, 0)
            platforms.append([new_x, new_y, plat_w, plat_h])

    # 掉下去游戏重置
    if player_y > HEIGHT:
        player_x = WIDTH//2-player_size//2
        player_y = HEIGHT-100
        is_jump = False
        vel_y = 0
        score = 0
        init_plat()

    # 绘制台阶
    for p in platforms:
        pygame.draw.rect(win, GREEN, p)
    # 绘制玩家
    pygame.draw.rect(win, RED, (player_x, player_y, player_size, player_size))

    # 绘制分数
    font = pygame.font.SysFont(None, 30)
    text = font.render(f"层数: {score//100}", True, WHITE)
    win.blit(text, (10,10))

    pygame.display.update()

pygame.quit()