import pygame
import random
import sys
import os

# 初始化
pygame.init()
WIDTH = 400
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("是男人就上一百层")
clock = pygame.time.Clock()
FPS = 60

# ========== 颜色 ==========
SKIN    = (255, 205, 148)
HAIR    = (60, 30, 10)
CLOTH   = (30, 144, 255)
PANTS   = (20, 20, 80)
WHITE   = (255, 255, 255)
GREEN   = (0, 220, 0)
YELLOW  = (255, 220, 0)
RED     = (255, 0, 0)
BLACK   = (0, 0, 0)
CLOUD_C = (230, 230, 230)
# 天空渐变
SKY_TOP  = (100, 180, 255)
SKY_BOT  = (180, 220, 255)

# ========== 角色参数 ==========
player_w = 28
player_h = 32
player_x = WIDTH // 2 - player_w // 2
player_y = HEIGHT - 80

speed_x = 5
gravity = 0.6
jump_power = -15
vy = 0

# 平台类型：normal / fragile
platforms = []

# 动画状态
state = "idle"
anim_frame = 0
anim_timer = 0
anim_speed = 6
on_ground = True
face_right = True

# 游戏变量
score = 0
high_score = 0
game_over = False
game_speed = 1.0

# 云朵
clouds = []
for _ in range(6):
    cx = random.randint(0, WIDTH)
    cy = random.randint(0, HEIGHT//2)
    cw = random.randint(40, 80)
    clouds.append([cx, cy, cw])

# 字体
font = pygame.font.SysFont(None, 30)
font_small = pygame.font.SysFont(None, 22)

# 加载音效（没有也不报错）
try:
    jump_snd = pygame.mixer.Sound("jump.wav")
    die_snd = pygame.mixer.Sound("die.wav")
except:
    jump_snd = None
    die_snd = None

# 读取最高分
def load_high():
    if os.path.exists("high.txt"):
        with open("high.txt","r") as f:
            return int(f.read())
    return 0

def save_high(s):
    with open("high.txt","w") as f:
        f.write(str(s))

high_score = load_high()

# ========== 平台类 ==========
class Platform:
    def __init__(self):
        self.w = random.randint(45,70)
        self.h = 12
        self.x = random.randint(0, WIDTH - self.w)
        self.y = 0
        self.type = "normal"
        # 30%概率易碎
        if random.random() < 0.3:
            self.type = "fragile"
            self.timer = 20

# 初始化平台
def init_platforms():
    plats = []
    p0 = Platform()
    p0.x = WIDTH//2 - p0.w//2
    p0.y = HEIGHT - 50
    p0.type = "normal"
    plats.append(p0)
    for i in range(10):
        p = Platform()
        p.y = HEIGHT - 50 - i * 55
        plats.append(p)
    return plats

platforms = init_platforms()

# 画渐变天空
def draw_sky():
    for y in range(HEIGHT):
        r = int(SKY_TOP[0] + (SKY_BOT[0]-SKY_TOP[0]) * y / HEIGHT)
        g = int(SKY_TOP[1] + (SKY_BOT[1]-SKY_TOP[1]) * y / HEIGHT)
        b = int(SKY_TOP[2] + (SKY_BOT[2]-SKY_TOP[2]) * y / HEIGHT)
        pygame.draw.line(screen, (r,g,b), (0,y), (WIDTH,y))

# 画云朵
def draw_clouds():
    for c in clouds:
        x, y, w = c
        pygame.draw.ellipse(screen, CLOUD_C, (x, y, w, w//2))

# 画卡通小人
def draw_cartoon_man(x, y, flip, frame, is_jump):
    cx = x + player_w // 2
    head_y = y + 10
    # 头发
    pygame.draw.arc(screen, HAIR, (cx-12, head_y-8, 24, 16), 3.14, 0, 6)
    # 脸
    pygame.draw.circle(screen, SKIN, (cx, head_y), 10)
    # 眼睛
    if flip:
        e1 = (cx-4, head_y-3)
        e2 = (cx+4, head_y-3)
    else:
        e1 = (cx+4, head_y-3)
        e2 = (cx-4, head_y-3)
    pygame.draw.circle(screen, BLACK, e1, 2)
    pygame.draw.circle(screen, BLACK, e2, 2)
    # 嘴巴
    if is_jump:
        pygame.draw.circle(screen, (180,60,60), (cx, head_y+5), 3, 1)
    else:
        pygame.draw.arc(screen, (180,60,60), (cx-5, head_y+2, 10, 6), 0, 3.14)
    # 身体
    pygame.draw.rect(screen, CLOTH, (x+6, y+18, 16, 10))
    # 腿摆动
    leg_off = 0
    if not is_jump and state == "run":
        leg_off = 3 if frame % 2 == 0 else -3
    pygame.draw.rect(screen, PANTS, (x+7, y+26, 5, 8 + leg_off))
    pygame.draw.rect(screen, PANTS, (x+16, y+26, 5, 8 - leg_off))
    # 手臂摆动
    arm_off = 0
    if not is_jump and state == "run":
        arm_off = 4 if frame % 2 == 0 else -4
    pygame.draw.rect(screen, SKIN, (x+2, y+20+arm_off, 4, 8))
    pygame.draw.rect(screen, SKIN, (x+22, y+20-arm_off, 4, 8))

# 主循环
while True:
    clock.tick(FPS)
    draw_sky()
    draw_clouds()

    # 云朵左移循环
    for c in clouds:
        c[0] -= 0.25
        if c[0] < -c[2]:
            c[0] = WIDTH
            c[1] = random.randint(0, HEIGHT//2)

    # 事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if game_over and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player_x = WIDTH // 2 - player_w // 2
                player_y = HEIGHT - 80
                vy = 0
                score = 0
                game_speed = 1.0
                platforms = init_platforms()
                game_over = False
                on_ground = True

    if not game_over:
        keys = pygame.key.get_pressed()
        move_left = keys[pygame.K_LEFT]
        move_right = keys[pygame.K_RIGHT]

        # 移动+朝向
        if move_left:
            face_right = False
            player_x -= speed_x
        if move_right:
            face_right = True
            player_x += speed_x

        # 边界
        if player_x < 0:
            player_x = 0
        if player_x > WIDTH - player_w:
            player_x = WIDTH - player_w

        # 重力
        vy += gravity
        player_y += vy
        on_ground = False

        # 平台碰撞 & 易碎计时
        for p in platforms:
            if (vy > 0 and
                player_x + player_w > p.x and
                player_x < p.x + p.w and
                player_y + player_h > p.y and
                player_y + player_h < p.y + p.h + 10):
                player_y = p.y - player_h
                vy = jump_power
                on_ground = True
                if jump_snd:
                    jump_snd.play()
                # 踩到易碎开始倒计时
                if p.type == "fragile":
                    p.timer -= 1

        # 移除倒计时结束的易碎平台
        platforms = [p for p in platforms if not (p.type=="fragile" and p.timer<=0)]

        # 镜头上移 + 难度加速
        if player_y < HEIGHT / 2:
            offset = (HEIGHT / 2 - player_y) * game_speed
            player_y = HEIGHT / 2
            for p in platforms:
                p.y += offset
            score += int(offset)
            # 难度随层数变快
            game_speed = 1.0 + score / 3000

            # 生成新平台
            new_p = Platform()
            new_p.y = min(pl.y for pl in platforms) - random.randint(50,65)
            platforms.append(new_p)

        # 移除跑出底部平台
        platforms = [p for p in platforms if p.y < HEIGHT]

        # 掉落游戏结束
        if player_y > HEIGHT:
            game_over = True
            if die_snd:
                die_snd.play()
            # 刷新最高分
            if score > high_score:
                high_score = score
                save_high(high_score)

    # 角色状态
    if not on_ground:
        state = "jump"
    elif move_left or move_right:
        state = "run"
    else:
        state = "idle"

    # 动画帧
    anim_timer += 1
    if anim_timer >= anim_speed:
        anim_frame += 1
        anim_timer = 0

    # 画平台
    for p in platforms:
        if p.type == "normal":
            col = GREEN
        else:
            col = YELLOW
        pygame.draw.rect(screen, col, (p.x, p.y, p.w, p.h))

    # 画小人
    draw_cartoon_man(player_x, player_y, face_right, anim_frame, state=="jump")

    # 文字显示
    score_text = font.render(f"层数: {score//100}", True, WHITE)
    high_text = font_small.render(f"最高: {high_score//100}", True, WHITE)
    screen.blit(score_text, (10, 10))
    screen.blit(high_text, (10, 35))

    # 结束提示
    if game_over:
        over_text = font.render("游戏结束 空格重启", True, WHITE)
        screen.blit(over_text, (30, HEIGHT//2))

    pygame.display.update()