import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 窗口设置
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("是男人上一百层")

# 颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
GRAY = (120, 120, 120)
BG_COLOR = (30, 30, 40)

# 玩家参数
player_w = 30
player_h = 30
player_x = SCREEN_WIDTH // 2 - player_w // 2
player_y = SCREEN_HEIGHT - 80
player_vx = 0
player_vy = 0
gravity = 0.4
jump_power = -12
move_speed = 6

# 平台参数
platform_w = 70
platform_h = 12
platform_list = []

# 游戏状态变量
score = 0
max_target = 100
game_state = "menu"  # menu / playing / win / gameover
clock = pygame.time.Clock()
FPS = 60

# ========== 修复字体部分！！ ==========
# 使用内置默认字体，避开SysFont报错
font = pygame.font.Font(None, 24)
font_big = pygame.font.Font(None, 48)


def create_start_platforms():
    """生成初始一批平台"""
    plats = []
    # 底部起始平台
    plats.append(pygame.Rect(SCREEN_WIDTH // 2 - platform_w // 2, SCREEN_HEIGHT - 50, platform_w, platform_h))
    y_pos = SCREEN_HEIGHT - 120
    for _ in range(12):
        x_pos = random.randint(0, SCREEN_WIDTH - platform_w)
        plats.append(pygame.Rect(x_pos, y_pos, platform_w, platform_h))
        y_pos -= random.randint(50, 80)
    return plats


def reset():
    """重置游戏所有数据"""
    global player_x, player_y, player_vx, player_vy, platform_list, score
    player_x = SCREEN_WIDTH // 2 - player_w // 2
    player_y = SCREEN_HEIGHT - 80
    player_vx = 0
    player_vy = 0
    score = 0
    platform_list = create_start_platforms()


reset()
run = True

while run:
    clock.tick(FPS)
    screen.fill(BG_COLOR)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if game_state == "menu":
                if event.key == pygame.K_SPACE:
                    reset()
                    game_state = "playing"
            elif game_state in ("gameover", "win"):
                if event.key == pygame.K_SPACE:
                    reset()
                    game_state = "playing"

    if game_state == "menu":
        title_surf = font_big.render("GO TO 100 FLOORS", True, WHITE)
        tip_surf = font.render("Press SPACE to start", True, GREEN)
        screen.blit(title_surf, (SCREEN_WIDTH//2 - title_surf.get_width()//2, 180))
        screen.blit(tip_surf, (SCREEN_WIDTH//2 - tip_surf.get_width()//2, 300))

    elif game_state == "playing":
        keys = pygame.key.get_pressed()
        # 左右移动
        if keys[pygame.K_LEFT]:
            player_vx = -move_speed
        elif keys[pygame.K_RIGHT]:
            player_vx = move_speed
        else:
            player_vx = 0

        # 重力
        player_vy += gravity
        player_x += player_vx
        player_y += player_vy

        # 左右循环穿墙
        if player_x < -player_w:
            player_x = SCREEN_WIDTH
        if player_x > SCREEN_WIDTH:
            player_x = -player_w

        player_rect = pygame.Rect(player_x, player_y, player_w, player_h)

        # 平台碰撞、踩平台跳跃
        for plat in platform_list:
            if player_vy > 0 and player_rect.colliderect(plat):
                if player_rect.bottom <= plat.top + 10:
                    player_y = plat.top - player_h
                    player_vy = jump_power

        # 镜头向上滚动（角色到屏幕上半区时）
        if player_y < SCREEN_HEIGHT * 0.35:
            shift = SCREEN_HEIGHT * 0.35 - player_y
            player_y = SCREEN_HEIGHT * 0.35
            for p in platform_list:
                p.y += shift
            score += int(shift)
            # 删除掉落到屏幕外下方的平台
            platform_list = [p for p in platform_list if p.y < SCREEN_HEIGHT + 20]
            # 在最上方持续生成新平台
            while min(p.y for p in platform_list) > -20:
                new_x = random.randint(0, SCREEN_WIDTH - platform_w)
                new_y = min(p.y for p in platform_list) - random.randint(50, 80)
                platform_list.append(pygame.Rect(new_x, new_y, platform_w, platform_h))

        # 掉下去 = 游戏结束
        if player_y > SCREEN_HEIGHT:
            game_state = "gameover"
        # 达到100层通关
        current_floor = score // 100
        if current_floor >= max_target:
            game_state = "win"

        # 绘制平台
        for p in platform_list:
            pygame.draw.rect(screen, GRAY, p)
        # 绘制玩家方块
        pygame.draw.rect(screen, RED, player_rect)
        # 绘制层数文字（英文避免方框乱码）
        floor_text = font.render(f"Floor: {min(current_floor, max_target)} / {max_target}", True, WHITE)
        screen.blit(floor_text, (10, 10))

    elif game_state == "gameover":
        over_surf = font_big.render("GAME OVER", True, RED)
        tip_surf = font.render("Press SPACE to retry", True, WHITE)
        screen.blit(over_surf, (SCREEN_WIDTH//2 - over_surf.get_width()//2, 200))
        screen.blit(tip_surf, (SCREEN_WIDTH//2 - tip_surf.get_width()//2, 320))

    elif game_state == "win":
        win_surf = font_big.render("YOU WIN!", True, GREEN)
        tip_surf = font.render("Reach 100 floors! SPACE replay", True, WHITE)
        screen.blit(win_surf, (SCREEN_WIDTH//2 - win_surf.get_width()//2, 200))
        screen.blit(tip_surf, (SCREEN_WIDTH//2 - tip_surf.get_width()//2, 320))

    pygame.display.update()

pygame.quit()
sys.exit()
