import pygame
import random
import sys

# 初始化pygame
pygame.init()
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")

# 字体（中文）
try:
    font = pygame.font.Font("simhei.ttf", 28)
    small_font = pygame.font.Font("simhei.ttf", 22)
except:
    font = pygame.font.SysFont("Microsoft YaHei", 28)
    small_font = pygame.font.SysFont("Microsoft YaHei", 22)

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (220, 30, 30)
GREEN = (40, 180, 40)
BLUE = (30, 120, 220)

# 玩家类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.width = 30
        self.height = 40
        self.image = pygame.Surface((self.width, self.height))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH // 2
        self.rect.bottom = HEIGHT - 80
        self.vx = 0
        self.vy = 0
        self.speed = 6
        self.gravity = 0.6
        self.jump_power = -16
        self.on_ground = False

    def update(self):
        # 左右移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.vx = -self.speed
        elif keys[pygame.K_RIGHT]:
            self.vx = self.speed
        else:
            self.vx = 0
        # 跳跃
        if keys[pygame.K_SPACE] and self.on_ground:
            self.vy = self.jump_power
            self.on_ground = False

        # 重力
        self.vy += self.gravity
        self.rect.x += self.vx
        self.rect.y += self.vy

        # 左右穿墙
        if self.rect.right < 0:
            self.rect.left = WIDTH
        if self.rect.left > WIDTH:
            self.rect.right = 0

        self.on_ground = False

# 平台类
class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        super().__init__()
        self.width = w
        self.height = h
        self.image = pygame.Surface((self.width, self.height))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

# 创建初始平台
def create_platforms():
    plats = pygame.sprite.Group()
    p1 = Platform(WIDTH//2 - 50, HEIGHT - 40, 100, 16)
    plats.add(p1)
    y = HEIGHT - 120
    for _ in range(10):
        w = random.randint(60, 110)
        x = random.randint(0, WIDTH - w)
        plat = Platform(x, y, w, 16)
        plats.add(plat)
        y -= random.randint(65, 110)
    return plats

# 游戏重置
def reset_game():
    player = Player()
    platforms = create_platforms()
    score = 0
    game_over = False
    return player, platforms, score, game_over

def main():
    clock = pygame.time.Clock()
    player, platforms, score, game_over = reset_game()

    while True:
        clock.tick(60)
        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_r:
                    player, platforms, score, game_over = reset_game()

        if not game_over:
            player.update()

            # 碰撞检测
            if player.vy > 0:
                hits = pygame.sprite.spritecollide(player, platforms, False)
                if hits:
                    player.rect.bottom = hits[0].rect.top + 2
                    player.vy = 0
                    player.on_ground = True

            # 镜头上移（玩家到达屏幕上半部分，平台向下移动）
            if player.rect.top < HEIGHT // 3:
                offset = max(abs(player.vy), 4)
                player.rect.y += offset
                score += offset
                for plat in platforms:
                    plat.rect.y += offset
                    if plat.rect.top >= HEIGHT:
                        plat.kill()
                        w = random.randint(60, 110)
                        x = random.randint(0, WIDTH - w)
                        new_plat = Platform(random.randint(0, WIDTH - w), plat.rect.y - random.randint(70,120), w,16)
                        platforms.add(new_plat)

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

            # 绘制
            platforms.draw(screen)
            screen.blit(player.image, player.rect)
            text = font.render(f"高度: {int(score)}", True, WHITE)
            screen.blit(text, (10, 10))
        else:
            # 游戏结束界面
            over_text = font.render("游戏结束！", True, RED)
            score_text = font.render(f"最终高度: {int(score)}", True, WHITE)
            tip_text = small_font.render("按 R 重新开始", True, WHITE)
            screen.blit(over_text, (WIDTH//2 - 70, HEIGHT//2 - 80))
            screen.blit(score_text, (WIDTH//2 - 85, HEIGHT//2 - 30))
            screen.blit(tip_text, (WIDTH//2 - 95, HEIGHT//2 + 20))

        pygame.display.flip()

if __name__ == "__main__":
    main()
