import tkinter as tk
import random

# 游戏参数
WIDTH = 400
HEIGHT = 500
GRAVITY = 0.4
JUMP_STRENGTH = -10
PLAYER_SPEED = 5
PLATFORM_WIDTH = 60
PLATFORM_HEIGHT = 10
GAME_SPEED = 2 # 平台下移的基础速度

class Game:
    def __init__(self, root):
        self.root = root
        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='#87CEEB')
        self.canvas.pack()
        
        self.score = 0
        self.max_height = 0
        
        # 玩家
        self.player = self.canvas.create_rectangle(0, 0, 20, 20, fill='red')
        self.px = WIDTH // 2
        self.py = HEIGHT - 50
        self.vy = 0
        self.on_ground = False
        self.canvas.move(self.player, self.px, self.py)
        
        # 平台列表
        self.platforms = []
        self.create_initial_platforms()
        
        # 按键状态
        self.keys = {'Left': False, 'Right': False}
        self.root.bind('<KeyPress>', self.key_press)
        self.root.bind('<KeyRelease>', self.key_release)
        
        # 分数显示
        self.score_text = self.canvas.create_text(10, 10, anchor='nw', text='层数: 0', font=('Arial', 14), fill='black')
        
        self.game_over = False
        self.update()
    
    def create_initial_platforms(self):
        # 底部一个固定平台
        p = self.canvas.create_rectangle(WIDTH//2 - PLATFORM_WIDTH//2, HEIGHT - 30, WIDTH//2 + PLATFORM_WIDTH//2, HEIGHT - 20, fill='green')
        self.platforms.append({'id': p, 'x': WIDTH//2 - PLATFORM_WIDTH//2, 'y': HEIGHT - 30, 'vx': 0})
        
        # 随机生成其他平台
        for i in range(1, 15):
            py = HEIGHT - 30 - i * 35
            px = random.randint(0, WIDTH - PLATFORM_WIDTH)
            vx = random.choice([-2, -1, 0, 1, 2]) if i > 5 else 0 # 上面的平台开始移动
            p = self.canvas.create_rectangle(px, py, px + PLATFORM_WIDTH, py + PLATFORM_HEIGHT, fill='green')
            self.platforms.append({'id': p, 'x': px, 'y': py, 'vx': vx})
    
    def key_press(self, event):
        if event.keysym in self.keys:
            self.keys[event.keysym] = True
    
    def key_release(self, event):
        if event.keysym in self.keys:
            self.keys[event.keysym] = False
            
    def update(self):
        if self.game_over:
            return
            
        # 玩家左右移动
        if self.keys['Left']:
            self.canvas.move(self.player, -PLAYER_SPEED, 0)
            self.px -= PLAYER_SPEED
        if self.keys['Right']:
            self.canvas.move(self.player, PLAYER_SPEED, 0)
            self.px += PLAYER_SPEED
            
        # 边界检查
        if self.px < 0:
            self.canvas.move(self.player, -self.px, 0)
            self.px = 0
        elif self.px > WIDTH - 20:
            dx = WIDTH - 20 - self.px
            self.canvas.move(self.player, dx, 0)
            self.px = WIDTH - 20
            
        # 重力
        self.vy += GRAVITY
        self.canvas.move(self.player, 0, self.vy)
        self.py += self.vy
        
        # 碰撞检测
        self.on_ground = False
        player_coords = self.canvas.coords(self.player)
        for plat in self.platforms:
            plat_coords = self.canvas.coords(plat['id'])
            # 简单AABB碰撞，只在下落时检测顶部
            if (player_coords[2] > plat_coords[0] and player_coords[0] < plat_coords[2] and
                player_coords[3] >= plat_coords[1] and player_coords[3] <= plat_coords[1] + 10 and
                self.vy > 0):
                self.vy = JUMP_STRENGTH
                self.on_ground = True
                # 更新最大高度/分数
                current_height = HEIGHT - player_coords[3]
                if current_height > self.max_height:
                    self.max_height = current_height
                    self.score = self.max_height // 30 # 每30像素算一层
                    self.canvas.itemconfig(self.score_text, text=f'层数: {self.score}')
        
        # 平台移动和回收
        for plat in self.platforms[:]:
            # 移动平台
            if plat['vx'] != 0:
                self.canvas.move(plat['id'], plat['vx'], 0)
                plat['x'] += plat['vx']
                # 碰壁反弹
                coords = self.canvas.coords(plat['id'])
                if coords[0] <= 0 or coords[2] >= WIDTH:
                    plat['vx'] = -plat['vx']
            
            # 平台下移（模拟摄像机上移）
            self.canvas.move(plat['id'], 0, GAME_SPEED)
            plat['y'] += GAME_SPEED
            
            # 如果平台移出底部，删除并在顶部生成新的
            if plat['y'] > HEIGHT:
                self.canvas.delete(plat['id'])
                self.platforms.remove(plat)
                new_y = -10
                new_x = random.randint(0, WIDTH - PLATFORM_WIDTH)
                vx = random.choice([-2, -1, 0, 1, 2])
                new_id = self.canvas.create_rectangle(new_x, new_y, new_x + PLATFORM_WIDTH, new_y + PLATFORM_HEIGHT, fill='green')
                self.platforms.append({'id': new_id, 'x': new_x, 'y': new_y, 'vx': vx})
        
        # 游戏结束判定：玩家掉出屏幕底部
        if self.py > HEIGHT:
            self.game_over = True
            self.canvas.create_text(WIDTH//2, HEIGHT//2, text='游戏结束!', font=('Arial', 30), fill='red')
            self.canvas.create_text(WIDTH//2, HEIGHT//2 + 40, text=f'你到达了 {self.score} 层', font=('Arial', 20), fill='black')
            return
            
        self.root.after(20, self.update)

root = tk.Tk()
root.title("是男人上一百层")
game = Game(root)
root.mainloop()