import pygame
import random

# ===================== 基础配置 =====================
pygame.init()
WIDTH, HEIGHT = 480, 700
screen = 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, 150, 255)
GRAY = (120, 120, 120)

# 玩家参数
player_w = 30
player_h = 40
player_x = WIDTH // 2 - player_w // 2
player_y = HEIGHT - 100
speed_x = 6
gravity = 0.8
jump_power = -18
vel_y = 0
on_ground = False

# 平台设置
platform_list = []
platform_w = 70
platform_h = 15
max_level = 100  # 目标100层

# 游戏变量
scroll_y = 0
current_floor = 1
game_over = False
win = False

# 【修复字体】多字体兜底兼容所有Windows，不会找不到字体
try:
    font = pygame.font.SysFont(["msyh", "simhei", "arial"], 26)
except:
    font = pygame.font.Font(None, 26)


# 初始化所有平台
def init_platforms():
    global platform_list
    platform_list.clear()
    # 出生平台保底存在
    platform_list.append([WIDTH//2-platform_w//2, HEIGHT-60, platform_w, platform_h])
    y_pos = HEIGHT - 130
    # 生成多层平台
    for i in range(120):
        x = random.randint(10, WIDTH-platform_w-10)
        platform_list.append([x, y_pos, platform_w, platform_h])
        y_pos -= random.randint(60, 90)


init_platforms()


# 重置游戏
def reset_game():
    global player_x, player_y, vel_y, scroll_y, current_floor, game_over, win
    player_x = WIDTH // 2 - player_w // 2
    player_y = HEIGHT - 100
    vel_y = 0
    scroll_y = 0
    current_floor = 1
    game_over = False
    win = False
    init_platforms()


# ===================== 主循环 =====================
running = True
while running:
    clock.tick(FPS)
    screen.fill((20, 20, 30))

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 空格跳跃 / 重生
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and on_ground and not game_over and not win:
                vel_y = jump_power
            if event.key == pygame.K_r:
                reset_game()

    if not game_over and not win:
        # 左右移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player_x > 0:
            player_x -= speed_x
        if keys[pygame.K_RIGHT] and player_x < WIDTH - player_w:
            player_x += speed_x

        # 重力下落
        vel_y += gravity
        player_y += vel_y
        on_ground = False

        # 平台碰撞检测
        player_rect = pygame.Rect(player_x, player_y, player_w, player_h)
        for plat in platform_list:
            plat_rect = pygame.Rect(plat[0], plat[1]+scroll_y, plat[2], plat[3])
            # 下落踩平台，防止空中踩顶
            if vel_y > 0 and player_rect.colliderect(plat_rect):
                player_y = plat_rect.top - player_h - scroll_y
                vel_y = 0
                on_ground = True

        # 镜头上移：玩家跑到屏幕上1/3，画面上滚
        if player_y < HEIGHT / 3:
            offset = HEIGHT / 3 - player_y
            player_y = HEIGHT / 3
            scroll_y += offset
            current_floor = int((HEIGHT - player_y + abs(scroll_y)) // 70) + 1

        # ========== 修复min空列表报错 ==========
        new_plats = []
        for p in platform_list:
            real_y = p[1] + scroll_y
            if real_y < HEIGHT + 50:
                new_plats.append(p)
            else:
                # 安全取最小y，列表为空直接给默认值
                if new_plats:
                    lowest_y = min(pl[1] for pl in new_plats)
                else:
                    lowest_y = -1000
                new_y = lowest_y - random.randint(60, 90)
                new_x = random.randint(10, WIDTH-platform_w-10)
                new_plats.append([new_x, new_y, platform_w, platform_h])
        platform_list = new_plats

        # 掉落到屏幕底部=失败
        if player_y > HEIGHT:
            game_over = True

        # 爬够100层通关
        if current_floor >= max_level:
            win = True

    # ========== 绘制所有元素 ==========
    # 绘制平台
    for p in platform_list:
        draw_y = p[1] + scroll_y
        pygame.draw.rect(screen, GRAY, (p[0], draw_y, p[2], p[3]))
        pygame.draw.rect(screen, WHITE, (p[0], draw_y, p[2], 3))

    # 绘制玩家方块小人+脑袋
    draw_player_y = player_y + scroll_y
    pygame.draw.rect(screen, BLUE, (player_x, draw_player_y, player_w, player_h))
    pygame.draw.circle(screen, WHITE, (player_x+player_w//2, draw_player_y+8), 8)

    # UI文字
    floor_text = font.render(f"层数：{current_floor}/{max_level}", True, WHITE)
    screen.blit(floor_text, (10, 10))

    if game_over:
        tip1 = font.render("游戏失败！按 R 重新开始", True, RED)
        screen.blit(tip1, (WIDTH//2-140, HEIGHT//2))
    if win:
        tip2 = font.render("恭喜通关！是真男人！按R重玩", True, GREEN)
        screen.blit(tip2, (WIDTH//2-160, HEIGHT//2))

    pygame.display.flip()

pygame.quit()