import pygame
import random

# ====================
# 初始化
# ====================
pygame.init()
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")

font = pygame.font.SysFont("simhei", 28)
clock = pygame.time.Clock()

# ====================
# 颜色
# ====================
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (50, 100, 255)
GREEN = (0, 200, 100)

# ====================
# 玩家
# ====================
player = pygame.Rect(180, 500, 40, 40)
player_speed = 0
gravity = 0.5

# ====================
# 平台
# ====================
platforms = []
for i in range(20):
    platforms.append(pygame.Rect(
        random.randint(0, WIDTH - 80),
        i * 30,
        80,
        10
    ))

floor = 0  # 当前层数

# ====================
# 游戏状态
# ====================
game_over = False

# ====================
# 主循环
# ====================
running = True
while running:
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()

    if not game_over:
        # 左右移动
        if keys[pygame.K_LEFT]:
            player.x -= 5
        if keys[pygame.K_RIGHT]:
            player.x += 5

        # 重力
        player_speed += gravity
        player.y += player_speed

        # 碰壁反弹
        if player.left < 0:
            player.left = 0
        if player.right > WIDTH:
            player.right = WIDTH

        # 踩平台
        for plat in platforms:
            if player.colliderect(plat) and player_speed > 0:
                player_speed = -10
                floor += 1

        # 平台向下移动
        for plat in platforms:
            plat.y += 2
            if plat.top > HEIGHT:
                plat.y = -10
                plat.x = random.randint(0, WIDTH - 80)

        # 掉下去
        if player.top > HEIGHT:
            game_over = True

    # ====================
    # 绘制
    # ====================
    pygame.draw.rect(screen, BLUE, player)

    for plat in platforms:
        pygame.draw.rect(screen, GREEN, plat)

    text = font.render(f"层数: {floor}", True, WHITE)
    screen.blit(text, (10, 10))

    if game_over:
        over = font.render("Game Over! 按 R 重开", True, (255, 50, 50))
        screen.blit(over, (80, 250))
        if keys[pygame.K_r]:
            # 重置
            player.y = 500
            player_speed = 0
            floor = 0
            game_over = False

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
