import pygame
import random
import sys

# 初始化Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
GREEN = (50, 200, 50)
BLUE = (50, 100, 255)
YELLOW = (255, 255, 0)
PURPLE = (180, 70, 220)
GRAY = (100, 100, 100)
BACKGROUND = (20, 20, 40)

# 游戏参数
FPS = 60
GRAVITY = 0.5
PLAYER_SPEED = 5
JUMP_FORCE = -12
PLATFORM_WIDTH = 100
PLATFORM_HEIGHT = 20
MIN_PLATFORM_DISTANCE = 50
MAX_PLATFORM_DISTANCE = 150
SCROLL_THRESHOLD = HEIGHT // 3

# 字体
font = pygame.font.SysFont(None, 36)
small_font = pygame.font.SysFont(None, 24)

class Player:
    def __init__(self):
        self.width = 40
        self.height = 60
        self.x = WIDTH // 2 - self.width // 2
        self.y = HEIGHT - 200
        self.vel_x = 0
        self.vel_y = 0
        self.on_ground = False
        self.color = BLUE
        self.lives = 3
        self.score = 0
        self.highest_platform = HEIGHT
        
    def update(self, platforms):
        # 应用重力
        self.vel_y += GRAVITY
        
        # 横向移动
        self.x += self.vel_x
        
        # 边界检查
        if self.x < 0:
            self.x = 0
        elif self.x + self.width > WIDTH:
            self.x = WIDTH - self.width
            
        # 纵向移动
        self.y += self.vel_y
        
        # 与平台碰撞检测
        self.on_ground = False
        for platform in platforms:
            if (self.vel_y > 0 and
                self.y + self.height >= platform.y and
                self.y + self.height <= platform.y + 10 and
                self.x + self.width > platform.x and
                self.x < platform.x + platform.width):
                
                self.y = platform.y - self.height
                self.vel_y = 0
                self.on_ground = True
                
                # 如果踩到弹簧平台，跳得更高
                if platform.type == "spring":
                    self.vel_y = JUMP_FORCE * 1.5
                # 如果踩到普通平台，正常跳跃
                elif self.on_ground and pygame.key.get_pressed()[pygame.K_SPACE]:
                    self.vel_y = JUMP_FORCE
                    
                # 如果踩到移动平台，跟着平台移动
                if platform.type == "moving":
                    self.x += platform.vel_x
                    
                # 更新最高平台记录
                if platform.y < self.highest_platform:
                    self.highest_platform = platform.y
                    
                # 计算得分
                platform_height_score = HEIGHT - platform.y
                if not platform.stepped:
                    self.score += platform_height_score // 10
                    platform.stepped = True
        
        # 防止玩家掉出屏幕底部
        if self.y > HEIGHT:
            self.y = 0
            self.lives -= 1
            self.vel_y = 0
            
    def draw(self, surface):
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))
        # 画眼睛
        pygame.draw.circle(surface, WHITE, (int(self.x + 10), int(self.y + 15)), 5)
        pygame.draw.circle(surface, WHITE, (int(self.x + self.width - 10), int(self.y + 15)), 5)
        pygame.draw.circle(surface, BLACK, (int(self.x + 10), int(self.y + 15)), 2)
        pygame.draw.circle(surface, BLACK, (int(self.x + self.width - 10), int(self.y + 15)), 2)
        
    def jump(self):
        if self.on_ground:
            self.vel_y = JUMP_FORCE
            
    def move_left(self):
        self.vel_x = -PLAYER_SPEED
        
    def move_right(self):
        self.vel_x = PLAYER_SPEED
        
    def stop(self):
        self.vel_x = 0

class Platform:
    def __init__(self, x, y, width, platform_type="normal"):
        self.x = x
        self.y = y
        self.width = width
        self.height = PLATFORM_HEIGHT
        self.type = platform_type
        self.stepped = False
        
        # 移动平台参数
        if self.type == "moving":
            self.vel_x = random.choice([-2, -1, 1, 2])
            self.direction_change_timer = 0
        else:
            self.vel_x = 0
            
        # 根据平台类型设置颜色
        if self.type == "normal":
            self.color = GREEN
        elif self.type == "spring":
            self.color = YELLOW
        elif self.type == "moving":
            self.color = PURPLE
        elif self.type == "fragile":
            self.color = GRAY
            
    def update(self):
        if self.type == "moving":
            self.x += self.vel_x
            
            # 边界检查
            if self.x < 0 or self.x + self.width > WIDTH:
                self.vel_x *= -1
                
    def draw(self, surface):
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))
        
        # 特殊平台装饰
        if self.type == "spring":
            # 画弹簧
            for i in range(5):
                spring_y = self.y + 5 + i * 3
                pygame.draw.rect(surface, (150, 150, 0), 
                                (self.x + 5, spring_y, self.width - 10, 2))
        elif self.type == "moving":
            # 画箭头
            arrow_direction = 1 if self.vel_x > 0 else -1
            arrow_x = self.x + self.width // 2
            pygame.draw.polygon(surface, WHITE, [
                (arrow_x, self.y + 5),
                (arrow_x + 5 * arrow_direction, self.y + 10),
                (arrow_x, self.y + 15)
            ])
        elif self.type == "fragile":
            # 画裂缝
            for i in range(3):
                crack_x = self.x + 10 + i * 25
                pygame.draw.line(surface, BLACK, 
                                (crack_x, self.y + 5), 
                                (crack_x + 10, self.y + 15), 2)

def generate_platforms(start_y, count=15):
    platforms = []
    current_y = start_y
    
    for _ in range(count):
        # 随机生成平台类型
        platform_type_roll = random.random()
        if platform_type_roll < 0.6:
            platform_type = "normal"
        elif platform_type_roll < 0.75:
            platform_type = "spring"
        elif platform_type_roll < 0.9:
            platform_type = "moving"
        else:
            platform_type = "fragile"
            
        # 随机生成平台宽度
        width = random.randint(80, 150)
        
        # 随机生成平台X位置
        x = random.randint(0, WIDTH - width)
        
        # 创建平台
        platform = Platform(x, current_y, width, platform_type)
        platforms.append(platform)
        
        # 更新下一个平台的Y位置
        current_y -= random.randint(MIN_PLATFORM_DISTANCE, MAX_PLATFORM_DISTANCE)
        
    return platforms

def draw_background(surface, scroll_offset):
    # 画星空背景
    surface.fill(BACKGROUND)
    
    # 画一些星星
    for _ in range(50):
        x = random.randint(0, WIDTH)
        y = random.randint(0, HEIGHT)
        size = random.randint(1, 3)
        brightness = random.randint(150, 255)
        pygame.draw.circle(surface, (brightness, brightness, brightness), (x, y), size)
    
    # 画渐变地面效果
    for i in range(20):
        alpha = 255 - i * 10
        if alpha < 0:
            alpha = 0
        color = (10, 30, 60, alpha)
        s = pygame.Surface((WIDTH, 5), pygame.SRCALPHA)
        s.fill(color)
        surface.blit(s, (0, HEIGHT - i * 3 + scroll_offset % 3))

def main():
    clock = pygame.time.Clock()
    player = Player()
    
    # 初始生成平台
    platforms = generate_platforms(HEIGHT - 50, 20)
    
    # 游戏状态
    game_over = False
    game_win = False
    scroll_offset = 0
    
    # 主游戏循环
    while True:
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                    
                if not game_over and not game_win:
                    if event.key == pygame.K_SPACE:
                        player.jump()
                    elif event.key == pygame.K_r:
                        # 重新开始游戏
                        player = Player()
                        platforms = generate_platforms(HEIGHT - 50, 20)
                        game_over = False
                        game_win = False
                        scroll_offset = 0
                        
        if not game_over and not game_win:
            # 玩家移动控制
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT] or keys[pygame.K_a]:
                player.move_left()
            elif keys[pygame.K_RIGHT] or keys[pygame.K_d]:
                player.move_right()
            else:
                player.stop()
                
            # 更新玩家
            player.update(platforms)
            
            # 更新平台
            for platform in platforms:
                platform.update()
                
            # 屏幕滚动
            if player.y < SCROLL_THRESHOLD:
                scroll_amount = SCROLL_THRESHOLD - player.y
                player.y = SCROLL_THRESHOLD
                scroll_offset += scroll_amount
                
                # 移动所有平台
                for platform in platforms:
                    platform.y += scroll_amount
                    
            # 移除屏幕底部的平台并生成新的
            platforms = [p for p in platforms if p.y < HEIGHT + 100]
            
            if len(platforms) < 20:
                new_platforms = generate_platforms(platforms[-1].y - MAX_PLATFORM_DISTANCE, 10)
                platforms.extend(new_platforms)
                
            # 检查游戏结束条件
            if player.lives <= 0:
                game_over = True
                
            # 检查游戏胜利条件（达到100层）
            if player.highest_platform <= HEIGHT - 100 * 50:
                game_win = True
                
        # 绘制
        draw_background(screen, scroll_offset)
        
        # 绘制所有平台
        for platform in platforms:
            platform.draw(screen)
            
        # 绘制玩家
        player.draw(screen)
        
        # 绘制UI
        # 分数和生命值
        score_text = font.render(f"分数: {player.score}", True, WHITE)
        lives_text = font.render(f"生命: {player.lives}", True, WHITE)
        height_text = font.render(f"高度: {int((HEIGHT - player.highest_platform) / 5)}", True, WHITE)
        
        screen.blit(score_text, (10, 10))
        screen.blit(lives_text, (10, 50))
        screen.blit(height_text, (10, 90))
        
        # 平台类型说明
        type_text1 = small_font.render("绿色: 普通平台", True, GREEN)
        type_text2 = small_font.render("黄色: 弹簧平台", True, YELLOW)
        type_text3 = small_font.render("紫色: 移动平台", True, PURPLE)
        type_text4 = small_font.render("灰色: 易碎平台", True, GRAY)
        
        screen.blit(type_text1, (WIDTH - 150, 10))
        screen.blit(type_text2, (WIDTH - 150, 35))
        screen.blit(type_text3, (WIDTH - 150, 60))
        screen.blit(type_text4, (WIDTH - 150, 85))
        
        # 控制说明
        controls_text = small_font.render("控制: ←→移动, 空格跳跃, R重新开始, ESC退出", True, WHITE)
        screen.blit(controls_text, (WIDTH // 2 - 180, HEIGHT - 30))
        
        # 游戏结束/胜利画面
        if game_over:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 200))
            screen.blit(overlay, (0, 0))
            
            game_over_text = font.render("游戏结束!", True, RED)
            final_score_text = font.render(f"最终分数: {player.score}", True, WHITE)
            restart_text = font.render("按R键重新开始", True, YELLOW)
            
            screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 60))
            screen.blit(final_score_text, (WIDTH // 2 - final_score_text.get_width() // 2, HEIGHT // 2))
            screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 60))
            
        if game_win:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 200))
            screen.blit(overlay, (0, 0))
            
            win_text = font.render("恭喜通关! 你是真男人!", True, YELLOW)
            final_score_text = font.render(f"最终分数: {player.score}", True, WHITE)
            restart_text = font.render("按R键重新开始", True, GREEN)
            
            screen.blit(win_text, (WIDTH // 2 - win_text.get_width() // 2, HEIGHT // 2 - 60))
            screen.blit(final_score_text, (WIDTH // 2 - final_score_text.get_width() // 2, HEIGHT // 2))
            screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 60))
            
        # 更新屏幕
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()