import tkinter as tk
import random
import time

class Player:
    """玩家类"""
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 30
        self.height = 40
        self.vx = 0
        self.vy = 0
        self.jump_power = 12
        self.gravity = 0.5
        self.on_ground = False
        self.lives = 3
        self.color = "#3498db"
        self.face_right = True
        self.invincible = False
        self.invincible_timer = 0
            
    def jump(self):
        if self.on_ground:
            self.vy = -self.jump_power
            self.on_ground = False
            
    def move_left(self):
        self.vx = -5
        self.face_right = False
        
    def move_right(self):
        self.vx = 5
        self.face_right = True
        
    def stop(self):
        self.vx = 0
        
    def update(self, platforms, screen_width, screen_height):
        # 应用重力
        self.vy += self.gravity
        
        # 更新位置
        self.x += self.vx
        self.y += self.vy
        
        # 边界检查
        if self.x < 0:
            self.x = 0
        elif self.x + self.width > screen_width:
            self.x = screen_width - self.width
            
        # 检查是否掉落
        if self.y > screen_height:
            return True, False
            
        # 检查胜利（到达顶部）
        if self.y < 0:
            return False, True
            
        # 重置地面状态
        self.on_ground = False
        
        # 检查平台碰撞
        for platform in platforms:
            if (self.x < platform.x + platform.width and
                self.x + self.width > platform.x and
                self.y + self.height > platform.y and
                self.y < platform.y + 10 and
                self.vy >= 0):  # 从上往下掉落
                
                self.y = platform.y - self.height
                self.vy = 0
                self.on_ground = True
                
                # 处理特殊平台
                if platform.type == "breakable":
                    platform.active = False
                elif platform.type == "disappearing":
                    platform.timer = 30
                    
        # 更新无敌时间
        if self.invincible:
            self.invincible_timer -= 1
            if self.invincible_timer <= 0:
                self.invincible = False
                
        return False, False
        
    def take_damage(self):
        if not self.invincible:
            self.lives -= 1
            self.invincible = True
            self.invincible_timer = 60
            return True
        return False

class Platform:
    """平台类"""
    def __init__(self, x, y, width, platform_type="normal"):
        self.x = x
        self.y = y
        self.width = width
        self.type = platform_type
        self.vx = 0
        self.active = True
        self.timer = 0
        
        # 设置平台属性
        if platform_type == "normal":
            self.color = "#2ecc71"  # 绿色
            self.vx = 0
        elif platform_type == "moving":
            self.color = "#3498db"  # 蓝色
            self.vx = random.choice([-2, 2])
        elif platform_type == "breakable":
            self.color = "#e74c3c"  # 红色
            self.vx = 0
        elif platform_type == "disappearing":
            self.color = "#f39c12"  # 橙色
            self.vx = 0
            
    def update(self, screen_width):
        if self.type == "moving" and self.active:
            self.x += self.vx
            if self.x <= 0 or self.x + self.width >= screen_width:
                self.vx = -self.vx
                
        if self.type == "disappearing" and self.timer > 0:
            self.timer -= 1
            if self.timer <= 0:
                self.active = False

class Game:
    def __init__(self, root):
        self.root = root
        self.root.title("是男人就上一百层")
        
        # 游戏设置
        self.width = 800
        self.height = 600
        self.canvas = tk.Canvas(root, width=self.width, height=self.height, bg='#87CEEB')
        self.canvas.pack()
        
        # 游戏状态
        self.state = "menu"  # menu, playing, paused, gameover, win
        self.score = 0
        self.high_score = 0
        self.floor = 1
        self.target_floor = 100
        self.start_time = 0
        self.game_time = 0
        
        # 游戏对象
        self.player = None
        self.platforms = []
        
        # 按键状态
        self.keys = set()
        
        # 初始化
        self.reset_game()
        
        # 绑定事件
        self.root.bind('<KeyPress>', self.on_key_press)
        self.root.bind('<KeyRelease>', self.on_key_release)
        
        # 开始游戏循环
        self.last_time = time.time()
        self.update()
        
    def reset_game(self):
        """重置游戏"""
        self.state = "menu"
        self.score = 0
        self.floor = 1
        self.player = Player(self.width//2, self.height-100)
        self.platforms = []
        self.generate_platforms()
        
    def generate_platforms(self):
        """生成平台"""
        self.platforms.clear()
        
        # 生成初始平台
        for i in range(20):
            y = self.height - 50 - i * 50
            x = random.randint(0, self.width - 100)
            
            # 随机选择平台类型
            r = random.random()
            if r < 0.5:
                plat_type = "normal"
            elif r < 0.8:
                plat_type = "moving"
            elif r < 0.9:
                plat_type = "breakable"
            else:
                plat_type = "disappearing"
                
            platform = Platform(x, y, 100, plat_type)
            self.platforms.append(platform)
            
    def add_platforms(self):
        """添加新平台"""
        # 找到最高平台
        if not self.platforms:
            return
            
        min_y = min(p.y for p in self.platforms)
        
        if min_y > 100:
            for _ in range(3):
                y = min_y - 150
                x = random.randint(0, self.width - 100)
                
                r = random.random()
                if r < 0.5:
                    plat_type = "normal"
                elif r < 0.8:
                    plat_type = "moving"
                elif r < 0.9:
                    plat_type = "breakable"
                else:
                    plat_type = "disappearing"
                    
                platform = Platform(x, y, 100, plat_type)
                self.platforms.append(platform)
                
    def remove_platforms(self):
        """移除屏幕外的平台"""
        self.platforms = [p for p in self.platforms if p.y < self.height + 50 and p.active]
        
    def on_key_press(self, event):
        """按键按下"""
        if self.state == "menu" and event.keysym:
            self.start_game()
            
        elif self.state == "playing":
            if event.keysym == 'space':
                self.player.jump()
            elif event.keysym in ['Left', 'a']:
                self.player.move_left()
            elif event.keysym in ['Right', 'd']:
                self.player.move_right()
            elif event.keysym == 'Escape':
                self.state = "paused"
                
        elif self.state == "paused" and event.keysym == 'Escape':
            self.state = "playing"
            
        elif self.state in ["gameover", "win"] and event.keysym:
            self.reset_game()
            
        self.keys.add(event.keysym)
        
    def on_key_release(self, event):
        """按键释放"""
        if event.keysym in self.keys:
            self.keys.remove(event.keysym)
            
        if event.keysym in ['Left', 'Right', 'a', 'd']:
            self.player.stop()
            
    def start_game(self):
        """开始游戏"""
        self.state = "playing"
        self.start_time = time.time()
        
    def update_playing(self):
        """更新游戏逻辑"""
        current_time = time.time()
        delta = min(current_time - self.last_time, 0.033)
        
        # 更新平台
        for platform in self.platforms:
            platform.update(self.width)
            
        # 更新玩家
        fall, win = self.player.update(self.platforms, self.width, self.height)
        
        # 检查掉落
        if fall:
            if self.player.take_damage():
                if self.player.lives <= 0:
                    self.state = "gameover"
                    if self.score > self.high_score:
                        self.high_score = self.score
                else:
                    # 重生
                    self.player.x = self.width // 2
                    self.player.y = 200
                    self.player.vy = 0
                    
        # 检查胜利
        if win:
            self.floor += 1
            self.score += 100
            if self.floor >= self.target_floor:
                self.state = "win"
                if self.score > self.high_score:
                    self.high_score = self.score
            else:
                # 移动到下一层
                self.move_up()
                
        # 屏幕滚动
        if self.player.y < self.height * 0.3:
            scroll = self.height * 0.3 - self.player.y
            self.player.y += scroll
            for platform in self.platforms:
                platform.y += scroll
            self.score += int(scroll * 0.1)
            
        # 更新楼层
        self.floor = max(self.floor, int((self.height - self.player.y) / 50) + 1)
        
        # 添加新平台
        self.add_platforms()
        
        # 移除旧平台
        self.remove_platforms()
        
        # 更新游戏时间
        if self.start_time:
            self.game_time = time.time() - self.start_time
            
        self.last_time = current_time
        
    def move_up(self):
        """向上移动一层"""
        for platform in self.platforms:
            platform.y += 100
        self.player.x = self.width // 2
        self.player.y = self.height - 200
        self.player.vy = 0
        
    def draw_menu(self):
        """绘制菜单"""
        self.canvas.delete("all")
        
        # 绘制背景
        self.canvas.create_rectangle(0, 0, self.width, self.height, fill='#87CEEB')
        
        # 绘制云朵
        self.draw_clouds()
        
        # 标题
        self.canvas.create_text(
            self.width//2, 100,
            text="是男人就上一百层",
            font=("Microsoft YaHei", 48, "bold"),
            fill="#e74c3c"
        )
        
        # 说明
        instructions = [
            "目标：到达第100层！",
            "控制：",
            "  ← → 或 A D - 左右移动",
            "  空格键 - 跳跃",
            "  ESC - 暂停/继续",
            "",
            "平台类型：",
            "  🟩 普通平台 - 安全",
            "  🟦 移动平台 - 会移动",
            "  🟥 可破坏平台 - 踩后会消失",
            "  🟧 消失平台 - 踩后短暂消失",
            "",
            f"最高分: {self.high_score}",
            "",
            "按任意键开始游戏"
        ]
        
        for i, text in enumerate(instructions):
            self.canvas.create_text(
                self.width//2, 200 + i * 25,
                text=text,
                font=("Microsoft YaHei", 16 if i < 2 else 12),
                fill="#2c3e50"
            )
            
    def draw_playing(self):
        """绘制游戏画面"""
        self.canvas.delete("all")
        
        # 绘制背景
        self.canvas.create_rectangle(0, 0, self.width, self.height, fill='#87CEEB')
        
        # 绘制云朵
        self.draw_clouds()
        
        # 绘制平台
        for platform in self.platforms:
            if platform.active:
                # 主平台
                self.canvas.create_rectangle(
                    platform.x, platform.y,
                    platform.x + platform.width, platform.y + 10,
                    fill=platform.color,
                    outline="#2c3e50",
                    width=2
                )
                
                # 平台效果
                if platform.type == "moving":
                    # 移动箭头
                    if platform.vx > 0:
                        self.canvas.create_polygon(
                            platform.x + platform.width - 10, platform.y + 5,
                            platform.x + platform.width - 20, platform.y + 2,
                            platform.x + platform.width - 20, platform.y + 8,
                            fill="#2c3e50"
                        )
                    else:
                        self.canvas.create_polygon(
                            platform.x + 10, platform.y + 5,
                            platform.x + 20, platform.y + 2,
                            platform.x + 20, platform.y + 8,
                            fill="#2c3e50"
                        )
                        
                elif platform.type == "breakable":
                    # 裂纹效果
                    self.canvas.create_line(
                        platform.x + 20, platform.y + 2,
                        platform.x + 30, platform.y + 8,
                        fill="#2c3e50", width=2
                    )
                    self.canvas.create_line(
                        platform.x + 60, platform.y + 3,
                        platform.x + 70, platform.y + 7,
                        fill="#2c3e50", width=2
                    )
                    
                elif platform.type == "disappearing" and platform.timer > 0:
                    # 闪烁效果
                    if platform.timer % 10 < 5:
                        self.canvas.create_rectangle(
                            platform.x, platform.y,
                            platform.x + platform.width, platform.y + 10,
                            fill="#95a5a6",
                            outline="#2c3e50",
                            width=2
                        )
                        
        # 绘制玩家
        player_color = "#e74c3c" if self.player.invincible else "#3498db"
        
        # 身体
        self.canvas.create_rectangle(
            self.player.x, self.player.y,
            self.player.x + self.player.width, self.player.y + self.player.height,
            fill=player_color,
            outline="#2c3e50",
            width=2
        )
        
        # 脸部
        face_x = self.player.x + self.player.width // 2
        face_y = self.player.y + 15
        
        # 眼睛
        eye_offset = 8 if self.player.face_right else -8
        self.canvas.create_oval(
            face_x - 5 + eye_offset, face_y - 5,
            face_x - 2 + eye_offset, face_y - 2,
            fill="white"
        )
        
        # 嘴巴
        self.canvas.create_line(
            face_x - 3 + eye_offset, face_y + 5,
            face_x + 3 + eye_offset, face_y + 5,
            fill="white", width=2
        )
        
        # 绘制UI
        self.draw_ui()
        
    def draw_paused(self):
        """绘制暂停画面"""
        self.draw_playing()
        
        # 半透明遮罩
        self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black",
            stipple="gray50"
        )
        
        # 暂停文字
        self.canvas.create_text(
            self.width//2, self.height//2,
            text="游戏暂停",
            font=("Microsoft YaHei", 48, "bold"),
            fill="white"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2 + 60,
            text="按ESC键继续",
            font=("Microsoft YaHei", 24),
            fill="white"
        )
        
    def draw_gameover(self):
        """绘制游戏结束画面"""
        self.draw_playing()
        
        # 半透明遮罩
        self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black",
            stipple="gray50"
        )
        
        # 游戏结束文字
        self.canvas.create_text(
            self.width//2, self.height//2 - 60,
            text="游戏结束",
            font=("Microsoft YaHei", 48, "bold"),
            fill="#e74c3c"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2,
            text=f"分数: {self.score}",
            font=("Microsoft YaHei", 36, "bold"),
            fill="white"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2 + 60,
            text=f"到达楼层: {self.floor}",
            font=("Microsoft YaHei", 24),
            fill="white"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2 + 120,
            text="按任意键重新开始",
            font=("Microsoft YaHei", 20),
            fill="#2ecc71"
        )
        
    def draw_win(self):
        """绘制胜利画面"""
        self.draw_playing()
        
        # 半透明遮罩
        self.canvas.create_rectangle(
            0, 0, self.width, self.height,
            fill="black",
            stipple="gray50"
        )
        
        # 胜利文字
        self.canvas.create_text(
            self.width//2, self.height//2 - 60,
            text="🎉 恭喜通关！ 🎉",
            font=("Microsoft YaHei", 48, "bold"),
            fill="#f1c40f"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2,
            text=f"分数: {self.score}",
            font=("Microsoft YaHei", 36, "bold"),
            fill="white"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2 + 60,
            text=f"用时: {int(self.game_time)}秒",
            font=("Microsoft YaHei", 24),
            fill="white"
        )
        
        self.canvas.create_text(
            self.width//2, self.height//2 + 120,
            text="你是个真男人！",
            font=("Microsoft YaHei", 32, "bold"),
            fill="#2ecc71"
        )
        
    def draw_ui(self):
        """绘制用户界面"""
        # 分数
        self.canvas.create_text(
            10, 10,
            text=f"分数: {self.score}",
            font=("Microsoft YaHei", 16, "bold"),
            fill="#2c3e50",
            anchor="nw"
        )
        
        # 楼层
        self.canvas.create_text(
            self.width - 10, 10,
            text=f"楼层: {min(self.floor, self.target_floor)}/{self.target_floor}",
            font=("Microsoft YaHei", 16, "bold"),
            fill="#2c3e50",
            anchor="ne"
        )
        
        # 时间
        self.canvas.create_text(
            self.width - 10, 40,
            text=f"时间: {int(self.game_time)}秒",
            font=("Microsoft YaHei", 16, "bold"),
            fill="#2c3e50",
            anchor="ne"
        )
        
        # 最高分
        self.canvas.create_text(
            self.width//2, 10,
            text=f"最高分: {self.high_score}",
            font=("Microsoft YaHei", 16, "bold"),
            fill="#e74c3c",
            anchor="n"
        )
        
        # 生命
        for i in range(self.player.lives):
            x = 10 + i * 40
            y = 50
            # 绘制心形
            self.canvas.create_oval(x, y, x + 12, y + 12, fill="#e74c3c", outline="")
            self.canvas.create_oval(x + 12, y, x + 24, y + 12, fill="#e74c3c", outline="")
            self.canvas.create_polygon(
                x, y + 6,
                x + 12, y + 20,
                x + 24, y + 6,
                fill="#e74c3c",
                outline=""
            )
            
        # 控制提示
        controls = [
            "←→/AD: 左右移动",
            "空格: 跳跃",
            "ESC: 暂停"
        ]
        
        for i, control in enumerate(controls):
            self.canvas.create_text(
                10, self.height - 60 + i * 20,
                text=control,
                font=("Microsoft YaHei", 10),
                fill="#7f8c8d",
                anchor="nw"
            )
            
    def draw_clouds(self):
        """绘制云朵"""
        # 云朵位置
        clouds = [
            (100, 100, 0.5),
            (300, 150, 0.7),
            (500, 80, 0.6),
            (700, 120, 0.8),
        ]
        
        for x, y, size in clouds:
            cloud_size = int(50 * size)
            self.canvas.create_oval(
                x, y,
                x + cloud_size, y + cloud_size * 0.6,
                fill="white", outline="", width=0
            )
            self.canvas.create_oval(
                x + cloud_size * 0.3, y - cloud_size * 0.2,
                x + cloud_size * 0.7, y + cloud_size * 0.4,
                fill="white", outline="", width=0
            )
            self.canvas.create_oval(
                x + cloud_size * 0.6, y,
                x + cloud_size, y + cloud_size * 0.6,
                fill="white", outline="", width=0
            )
            
    def update(self):
        """游戏主循环"""
        if self.state == "playing":
            self.update_playing()
            self.draw_playing()
        elif self.state == "menu":
            self.draw_menu()
        elif self.state == "paused":
            self.draw_paused()
        elif self.state == "gameover":
            self.draw_gameover()
        elif self.state == "win":
            self.draw_win()
            
        # 下一帧
        self.root.after(16, self.update)  # 约60fps

def main():
    """主函数"""
    root = tk.Tk()
    root.title("是男人就上一百层")
    root.geometry("800x600")
    
    # 居中显示
    root.update_idletasks()
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width - 800) // 2
    y = (screen_height - 600) // 2
    root.geometry(f"800x600+{x}+{y}")
    
    game = Game(root)
    root.mainloop()

if __name__ == "__main__":
    main()