import pygame, sys

pygame.init()
screen = pygame.display.set_mode((800, 450))
pygame.display.set_caption("机甲马里奥")
clock = pygame.time.Clock()

# ---------- 常量 ----------
TILE = 36
GRAVITY = 0.5
SPEED = 4
JUMP = -10

# ---------- 颜色 ----------
SKY = (20, 24, 42)
GROUND = (120, 128, 150)
RED = (230, 70, 70)
GOLD = (255, 210, 80)
ENEMY_C = (180, 60, 200)
WHITE = (235, 240, 255)
GREEN = (80, 200, 100)
BLUE = (70, 150, 240)

# ---------- 像素字 ----------
FONT = {
    "关":[[0,1,0,1,0],[0,1,0,1,0],[1,1,1,1,1],[1,0,1,0,0],[1,0,1,0,0],[1,0,1,0,0],[1,0,1,0,0]],
    "卡":[[0,1,1,1,0],[0,1,0,1,0],[0,1,0,1,0],[0,1,1,1,0],[0,1,0,1,0],[0,1,0,1,0],[0,1,1,1,0]],
    "金":[[0,1,1,1,0],[1,0,1,0,1],[0,1,1,1,0],[1,0,1,0,0],[1,0,1,0,0],[1,0,1,0,0],[1,1,1,1,1]],
    "币":[[1,1,1,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,1,1,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,1,1,1,1]],
    "生":[[0,1,0,0,0],[0,1,0,0,0],[1,1,1,1,1],[0,1,0,0,0],[0,1,0,0,0],[0,1,0,0,0],[1,1,1,1,1]],
    "命":[[0,1,0,0,0],[0,1,0,0,0],[1,1,1,1,1],[0,1,0,0,0],[0,1,0,0,0],[0,1,1,0,0],[1,1,1,1,1]],
    "分":[[1,1,1,1,0],[1,0,0,0,0],[1,1,1,1,0],[0,0,0,1,0],[0,0,0,1,0],[0,0,0,1,0],[1,1,1,1,1]],
    "通":[[1,0,1,0,1],[1,0,1,0,1],[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1]],
    "完":[[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]],
    "死":[[1,1,1,1,1],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1],[0,0,1,0,0],[0,0,1,0,0]],
    "亡":[[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,0],[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,1]],
    "按":[[0,1,0,0,0],[0,1,0,0,0],[1,1,1,1,0],[0,1,0,1,0],[0,1,0,1,0],[0,1,0,1,0],[1,1,1,1,1]],
    "重":[[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1]],
    "来":[[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1]],
    "左":[[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[1,0,0,0,0]],
    "右":[[1,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[0,0,0,0,1]],
    "跳":[[0,1,0,0,0],[1,1,1,1,0],[0,1,0,0,0],[1,1,1,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,1,1,1,1]],
    "空":[[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1]],
    "格":[[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]],
    "移":[[0,1,0,0,0],[1,1,0,0,0],[0,1,1,0,0],[0,0,1,1,0],[0,0,0,1,1],[0,0,0,1,0],[0,0,0,1,0]],
    "动":[[1,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,1,0],[1,0,0,1,0],[1,0,0,1,0]],
    "操":[[1,1,1,1,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1]],
    "作":[[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,0,0,1,0],[1,1,1,1,1]],
    "总":[[1,1,1,1,1],[1,0,1,0,1],[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[1,1,1,1,1]],
    " ":[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]],
}
for n in "0123456789/":
    if n == "/": continue
    FONT[n] = [
        [1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]
    ] if n in "08" else (
    [[0,0,1,0,0],[0,1,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,1,1,1,0]] if n=="1" else
    [[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,1]] if n=="2" else
    [[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[1,1,1,1,1]] if n=="3" else
    [[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[0,0,0,0,1]] if n=="4" else
    [[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[1,1,1,1,1]] if n=="5" else
    [[1,1,1,1,1],[1,0,0,0,0],[1,0,0,0,0],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]] if n=="6" else
    [[1,1,1,1,1],[0,0,0,0,1],[0,0,0,0,1],[0,0,0,1,0],[0,0,1,0,0],[0,1,0,0,0],[1,0,0,0,0]] if n=="7" else
    [[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]] if n=="9" else
    [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[1,1,1,1,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])

def draw_text(surface, txt, x, y, color, scale=2):
    cx = x
    for ch in txt:
        if ch in FONT:
            for ry, row in enumerate(FONT[ch]):
                for cxi, bit in enumerate(row):
                    if bit:
                        pygame.draw.rect(surface, color,
                            (cx+cxi*scale, y+ry*scale, scale, scale))
        cx += 6*scale

# ---------- 关卡 ----------
# 1=地面 2=金币 3=敌人 4=管道 D=传送门(终点) X=出生
levels = [
    # 关卡1
    [
        "                                                                        ",
        "                                                                        ",
        "                      2                                                 ",
        "       2      3                            3                             ",
        "                                              2                         ",
        "    1                   3                     4                           ",
        "  1111111         11111111111111      1111111111111111                   ",
        "1111111111111111111111111111111111111111111111111111111111D1111X         ",
    ],
    # 关卡2
    [
        "                                                                      ",
        "                                                                      ",
        " 2    2      2             3                    2                      ",
        "111  111  1111           111       3      111111                      ",
        "    1   1  1            1111             111                            ",
        "    11111 1            1   4           111                     D       ",
        "111111111111111111111111111111111111111111111111111111111111111111111111X",
    ],
    # 关卡3
    [
        "                                                                        ",
        "                        2                                               ",
        "  2      ?             2     ?     2                                     ",
        " 111   11111   B     111   11111  1111    ?                              ",
        "      1   1           1  3          1                                     ",
        "      1   1         111 1           111                                   ",
        "111111111111111111111111111111111111111111111111111111111111111111111111111X",
    ],
]

# ---------- 加载 ----------
def load_level(idx):
    global platforms, coins, enemies, door_rect, WORLD_W
    platforms = []
    coins = []
    enemies = []
    door_rect = None

    rows = levels[idx]
    WORLD_W = len(rows[0]) * TILE

    for row_i, row in enumerate(rows):
        for col_i, ch in enumerate(row):
            x = col_i * TILE
            y = row_i * TILE
            if ch == "1":
                platforms.append(pygame.Rect(x, y, TILE, TILE))
            elif ch == "2":
                coins.append({"x": x+9, "y": y+9, "alive": True})
            elif ch == "3":
                enemies.append({"x": x, "y": y, "dx": 1.5, "alive": True})
            elif ch == "4":
                platforms.append(pygame.Rect(x, y, TILE, TILE*2))
            elif ch == "D":
                # 传送门：2格宽 x 3格高，放在地面上
                door_rect = pygame.Rect(x, y - TILE*2, TILE*2, TILE*3)
            elif ch == "X":
                global player_x, player_y
                player_x, player_y = x, y - 4

# ---------- 玩家 ----------
player_x, player_y = 80, 300
vel_x = vel_y = 0
jumps = 0
score = 0
hp = 3
max_hp = 3
dead = False
cam = 0
current_level = 0
transition = 0

load_level(0)

# ---------- 主循环 ----------
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if transition > 0:
        transition -= 1

    elif not dead:
        keys = pygame.key.get_pressed()

        vel_x = 0
        if keys[pygame.K_LEFT]: vel_x = -SPEED
        if keys[pygame.K_RIGHT]: vel_x = SPEED

        if keys[pygame.K_SPACE] and jumps < 2:
            vel_y = JUMP
            jumps += 1

        vel_y += GRAVITY
        if vel_y > 12: vel_y = 12

        # 横向
        player_x += vel_x
        pb = pygame.Rect(int(player_x), int(player_y), 30, 42)
        for p in platforms:
            if pb.colliderect(p):
                if vel_x > 0: player_x = p.left - 30
                elif vel_x < 0: player_x = p.right
                pb.x = int(player_x)

        # 纵向
        player_y += vel_y
        pb.y = int(player_y)
        on_g = False
        for p in platforms:
            if pb.colliderect(p):
                if vel_y > 0:
                    player_y = p.top - 42
                    vel_y = 0
                    on_g = True
                    jumps = 0
                elif vel_y < 0:
                    player_y = p.bottom
                    vel_y = 0
                pb.y = int(player_y)

        # 金币
        pb.x = int(player_x)
        for c in coins:
            if c["alive"]:
                if pb.colliderect(pygame.Rect(c["x"],c["y"],18,18)):
                    c["alive"] = False
                    score += 10

        # 敌人
        for e in enemies:
            if not e["alive"]: continue
            e["x"] += e["dx"]
            er = pygame.Rect(e["x"], e["y"], 30, 30)
            for p in platforms:
                if er.colliderect(p): e["dx"] *= -1
            if pb.colliderect(er):
                if vel_y > 0 and player_y + 42 - vel_y <= e["y"] + 12:
                    e["alive"] = False
                    vel_y = -8
                    score += 20
                else:
                    hp -= 1
                    player_x, player_y = 80, 300
                    vel_y = 0
                    if hp <= 0: dead = True

        # 掉坑
        if player_y > 500:
            hp -= 1
            player_x, player_y = 80, 300
            if hp <= 0: dead = True

        # ★ 终点：走到传送门里就过关
        if door_rect and pb.colliderect(door_rect):
            if current_level < len(levels) - 1:
                current_level += 1
                load_level(current_level)
                transition = 60
            else:
                transition = -1

        # 相机
        tc = player_x - 266
        if tc < 0: tc = 0
        if tc > WORLD_W - 800: tc = WORLD_W - 800
        cam = tc

    # ========== 绘制 ==========
    screen.fill(SKY)

    for p in platforms:
        pygame.draw.rect(screen, GROUND, (p.x-cam, p.y, p.w, p.h))

    for c in coins:
        if c["alive"]:
            pygame.draw.circle(screen, GOLD, (c["x"]-cam+9, c["y"]+9), 8)
            pygame.draw.circle(screen, (255,255,180), (c["x"]-cam+9, c["y"]+9), 4)

    for e in enemies:
        if e["alive"]:
            ex = e["x"]-cam
            pygame.draw.rect(screen, ENEMY_C, (ex, e["y"], 30, 30), border_radius=4)
            pygame.draw.circle(screen, WHITE, (ex+10, e["y"]+12), 3)
            pygame.draw.circle(screen, WHITE, (ex+20, e["y"]+12), 3)

    # ★ 传送门（大门）
    if door_rect:
        dx = door_rect.x - cam
        dy = door_rect.y
        # 门框
        pygame.draw.rect(screen, (100, 60, 180), (dx, dy, door_rect.w, door_rect.h), border_radius=4)
        pygame.draw.rect(screen, (180, 120, 255), (dx+4, dy+4, door_rect.w-8, door_rect.h-8), border_radius=3)
        # 门内发光
        t = pygame.time.get_ticks() // 200
        glow = 150 + int(50 * (t % 4 - 2) / 2)
        pygame.draw.rect(screen, (glow, glow, 255), (dx+8, dy+8, door_rect.w-16, door_rect.h-16), border_radius=2)

    # 玩家
    if not dead:
        px = int(player_x - cam)
        py = int(player_y)
        pygame.draw.rect(screen, GROUND, (px+5, py+30, 8, 12))
        pygame.draw.rect(screen, GROUND, (px+17, py+30, 8, 12))
        pygame.draw.rect(screen, RED, (px+3, py+12, 24, 20), border_radius=3)
        pygame.draw.rect(screen, WHITE, (px+8, py+16, 14, 5))
        pygame.draw.rect(screen, GROUND, (px+5, py, 20, 14), border_radius=3)
        pygame.draw.circle(screen, (0,220,255), (px+15, py+7), 3)

    # ---------- HUD ----------
    pygame.draw.rect(screen, (0,0,0,120), (0,0,800,30))
    draw_text(screen, "关 卡", 10, 6, WHITE, 2)
    draw_text(screen, str(current_level+1)+"/3", 60, 6, GREEN, 2)
    pygame.draw.circle(screen, GOLD, (130, 15), 6)
    draw_text(screen, str(score//10), 145, 6, GOLD, 2)
    draw_text(screen, "生 命", 220, 6, WHITE, 2)
    for h in range(max_hp):
        c = RED if h < hp else (80,80,80)
        pygame.draw.rect(screen, c, (280+h*18, 8, 14, 14), border_radius=2)
    draw_text(screen, "左 右 移 动  空 格 跳 跃  走 进 传 送 门", 430, 6, (180,180,200), 2)

    # 过渡
    if transition > 0:
        a = int(255*(1-transition/60))
        ov = pygame.Surface((800,450))
        ov.set_alpha(a)
        ov.fill(WHITE)
        screen.blit(ov, (0,0))
        if transition == 1:
            draw_text(screen, "关 卡 "+str(current_level+1), 300, 200, BLUE, 4)

    if dead:
        ov = pygame.Surface((800,450))
        ov.set_alpha(180)
        ov.fill((0,0,0))
        screen.blit(ov, (0,0))
        draw_text(screen, "死 亡", 350, 180, RED, 5)
        draw_text(screen, "按 R 重 来", 310, 250, WHITE, 3)

    if transition == -1:
        ov = pygame.Surface((800,450))
        ov.set_alpha(200)
        ov.fill((0,0,0))
        screen.blit(ov, (0,0))
        draw_text(screen, "通 关 完 成", 280, 180, GOLD, 5)
        draw_text(screen, "总 分 "+str(score), 320, 250, WHITE, 3)

    pygame.display.flip()
    clock.tick(60)

    k = pygame.key.get_pressed()
    if dead and k[pygame.K_r]:
        hp = max_hp
        score = 0
        current_level = 0
        dead = False
        load_level(0)

pygame.quit()
sys.exit()