import pygame
import random
import sys

# 初始化pygame
pygame.init()
# 窗口尺寸
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("男人上一百层")
clock = pygame.time.Clock()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 150, 255)
GRAY = (100, 100, 100)

# 玩家类
class Player:
    def __init__(self):
        self.w = 30
        self.h = 40
        self.x = WIDTH // 2 - self.w // 2
        self.y = HEIGHT - 100
        self.vx = 0
        self.vy = 0
        self.speed = 6
        self.jump_power = -18
        self.gravity = 0.8

    def update(self, platforms):
        # 左右移动
        self.x += self.vx
        # 边界穿墙
        if self.x > WIDTH:
            self.x = -self.w
        if self.x < -self.w:
            self.x = WIDTH
        # 重力
        self.vy += self.gravity
        self.y += self.vy

        # 平台碰撞检测（下落时才踩平台）
        on_plat = False
        if self.vy > 0:
            for p in platforms:
                if (self.x + self.w > p.x and self.x < p.x + p.w and
                    self.y + self.h > p.y and self.y + self.h < p.y + p.h + 10):
                    self.y = p.y - self.h
                    self.vy = self.jump_power
                    on_plat = True
                    break
        return on_plat

    def draw(self):
        pygame.draw.rect(screen, BLUE, (self.x, self.y, self.w, self.h))

# 平台类
class Platform:
    def __init__(self, y, level):
        self.w = random.randint(60, 120)
        self.h = 16
        self.x = random.randint(0, WIDTH - self.w)
        self.y = y
        # 高层平台移动
        self.move_speed = random.choice([-1, 1]) if level > 10 else 0

    def update(self):
        self.x += self.move_speed
        if self.x <= 0 or self.x + self.w >= WIDTH:
            self.move_speed *= -1

    def draw(self):
        pygame.draw.rect(screen, GRAY, (self.x, self.y, self.w, self.h))

# 游戏初始化
def reset_game():
    player = Player()
    plats = []
    # 初始底层平台
    plats.append(Platform(HEIGHT - 60, 0))
    for i in range(1, 12):
        plats.append(Platform(HEIGHT - i * 60, i))
    max_layer = 0
    scroll_y = 0
    return player, plats, max_layer, scroll_y

player, platforms, max_layer, scroll = reset_game()
font = pygame.font.SysFont(None, 36)
game_over = False

# 主循环
while True:
    screen.fill(BLACK)
    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if game_over and event.key == pygame.K_SPACE:
                player, platforms, max_layer, scroll = reset_game()
                game_over = False

    if not game_over:
        # 玩家左右控制
        keys = pygame.key.get_pressed()
        player.vx = 0
        if keys[pygame.K_LEFT]:
            player.vx = -player.speed
        if keys[pygame.K_RIGHT]:
            player.vx = player.speed

        # 更新玩家
        player.update(platforms)

        # 镜头上移（玩家超过屏幕上半部分）
        if player.y < HEIGHT // 3:
            offset = HEIGHT // 3 - player.y
            scroll += offset
            player.y = HEIGHT // 3
            # 所有平台下移
            for p in platforms:
                p.y += offset
            # 删除超出屏幕底部平台
            new_plats = []
            for p in platforms:
                if p.y < HEIGHT + 20:
                    new_plats.append(p)
            platforms = new_plats
            # 生成新平台
            top_y = min(p.y for p in platforms)
            new_level = int(scroll // 60)
            platforms.append(Platform(top_y - 60, new_level))

        # 更新移动平台
        for p in platforms:
            p.update()

        # 掉落判定
        if player.y > HEIGHT:
            game_over = True

        # 计算当前层数
        current_layer = int(scroll // 60)
        if current_layer > max_layer:
            max_layer = current_layer

        # 绘制所有平台
        for p in platforms:
            p.draw()
        # 绘制玩家
        player.draw()

        # 显示层数文字
        text = font.render(f"层数: {current_layer} 最高: {max_layer}", True, WHITE)
        screen.blit(text, (10, 10))
    else:
        # 游戏结束界面
        over_text = font.render(f"游戏结束！最高层数 {max_layer}", True, RED)
        tip_text = font.render("按空格重新开始", True, WHITE)
        screen.blit(over_text, (WIDTH//2 - over_text.get_width()//2, HEIGHT//2 - 40))
        screen.blit(tip_text, (WIDTH//2 - tip_text.get_width()//2, HEIGHT//2 + 10))

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