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()
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 200, 0)
BLUE = (30, 144, 255)
GRAY = (80, 80, 80)
SKY = (135, 206, 235)

# 【修复字体报错】容错加载字体，找不到黑体自动使用默认字体
def get_font(size):
    try:
        # 优先黑体
        return pygame.font.SysFont("simhei", size)
    except:
        try:
            # 备选Arial
            return pygame.font.SysFont("Arial", size)
        except:
            # 兜底系统默认字体
            return pygame.font.Font(None, size)

font_small = get_font(22)
font_big = get_font(40)
font_end = get_font(50)

# 玩家类
class Player:
    def __init__(self):
        self.w = 30
        self.h = 40
        self.x = WIDTH // 2 - self.w // 2
        self.y = HEIGHT - 100
        self.speed_x = 6
        self.vy = 0
        self.gravity = 0.35
        self.jump_power = -12
        self.on_ground = False

    def update(self, platforms):
        # 左右移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.x -= self.speed_x
        if keys[pygame.K_RIGHT]:
            self.x += self.speed_x
        # 左右穿墙
        if self.x < -self.w:
            self.x = WIDTH
        if self.x > WIDTH:
            self.x = -self.w

        # 重力
        self.vy += self.gravity
        self.y += self.vy
        self.on_ground = False

        # 平台碰撞
        for p in platforms:
            if self.vy > 0:
                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 + 12):
                    self.y = p.y - self.h
                    self.vy = self.jump_power
                    self.on_ground = True

    def draw(self):
        # 绘制小人（头部+身体）
        pygame.draw.rect(screen, BLUE, (self.x, self.y, self.w, self.h))
        pygame.draw.circle(screen, RED, (int(self.x + self.w/2), int(self.y - 10)), 12)

# 平台类
class Platform:
    def __init__(self, x, y, w=80):
        self.x = x
        self.y = y
        self.w = w
        self.h = 12

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

# 生成初始平台
def create_platforms():
    plats = []
    # 底部起始平台
    plats.append(Platform(WIDTH//2 - 50, HEIGHT - 60, 100))
    # 随机生成向上平台
    y_pos = HEIGHT - 130
    for _ in range(15):
        x = random.randint(0, WIDTH - 80)
        plats.append(Platform(x, y_pos))
        y_pos -= random.randint(60, 100)
    return plats

# 主游戏函数
def game_loop():
    player = Player()
    platforms = create_platforms()
    score = 0
    max_height = player.y
    game_over = False

    while True:
        clock.tick(FPS)
        screen.fill(SKY)

        # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # 游戏结束按空格重新开始
            if event.type == pygame.KEYDOWN and game_over:
                if event.key == pygame.K_SPACE:
                    game_loop()

        if not game_over:
            player.update(platforms)

            # 相机上移：玩家超过屏幕一半，所有平台向下移动，模拟向上爬
            if player.y < HEIGHT // 2:
                offset = HEIGHT // 2 - player.y
                player.y = HEIGHT // 2
                max_height -= offset
                score = int((HEIGHT - max_height) // 8)
                # 所有平台下移
                for p in platforms:
                    p.y += offset

                # 生成新上层平台
                top_y = min(p.y for p in platforms)
                while top_y > -50:
                    new_x = random.randint(0, WIDTH - 80)
                    new_y = top_y - random.randint(60, 100)
                    platforms.append(Platform(new_x, new_y))
                    top_y = new_y

            # 删除屏幕下方看不见的平台
            for i in range(len(platforms)-1, -1, -1):
                if platforms[i].y > HEIGHT + 20:
                    platforms.pop(i)

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

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

            # 绘制UI文字界面
            text_score = font_small.render(f"Score：{score}", True, BLACK)
            text_floor = font_small.render(f"Target:100 Floor Now:{score//10}", True, BLACK)
            screen.blit(text_score, (10, 10))
            screen.blit(text_floor, (10, 35))

            # 到达100层通关提示
            if score >= 1000:
                win_text = font_big.render("You Win! 100 Floors Cleared", True, RED)
                screen.blit(win_text, (WIDTH//2 - 200, HEIGHT//2))

        else:
            # 游戏结束界面弹窗
            end_bg = pygame.Rect(WIDTH//2 - 180, HEIGHT//2 - 120, 360, 240)
            pygame.draw.rect(screen, WHITE, end_bg)
            pygame.draw.rect(screen, GRAY, end_bg, 4)
            text_end = font_end.render("Game Over", True, RED)
            text_final = font_big.render(f"Final Score：{score}", True, BLACK)
            text_restart = font_small.render("Press SPACE to Restart", True, GREEN)
            screen.blit(text_end, (WIDTH//2 - 120, HEIGHT//2 - 80))
            screen.blit(text_final, (WIDTH//2 - 110, HEIGHT//2 - 10))
            screen.blit(text_restart, (WIDTH//2 - 140, HEIGHT//2 + 60))

        pygame.display.flip()

if __name__ == "__main__":
    game_loop()
