← 都来码 / Dolaima← 例程索引python/app/maze.py▶ 在浏览器里试玩 原文

python/app/maze.py · 8901 字节 · 下载原文

▶ 在浏览器里试玩

# maze.py —— 迷宫(VML 的 Python 前端)
# maze.py -- maze (VML's Python frontend)
#
# 与 `Examples/c/app/maze.c` **同一套玩法**:
# Same rules as `Examples/c/app/maze.c`:
#   · 每局**现生成**一张新迷宫(深度优先挖洞,一定连通、一定有路);
#   · every round **generates** a fresh maze (depth-first carving; always connected, always solvable);
#   · 方向键 / 点屏幕四边移动,走到右下角出口即通关,ESC / 点一下换一张。
#   · arrow keys / tapping a screen edge move; reaching the bottom-right exit wins;
#     ESC or a tap after winning gives a new maze.
#
# 生成用的是**显式栈**(数组 + 栈顶下标),不是递归 —— 递归在这种规模上容易把
# 固定额度的栈吃掉,症状是"跑到一半没了",很难查。
# Generation uses an **explicit stack**, not recursion -- recursion at this size can eat the
# fixed stack budget and the symptom is "it just vanished halfway".
#
# 迷宫表示:`(2N+1) × (2M+1)` 的格子图,1 = 墙、0 = 通路;按**平铺**数组 `cells[x * MH + y]` 存。
# Representation: a `(2N+1) x (2M+1)` map, 1 = wall, 0 = passage, stored **flat** as `cells[x * MH + y]`.

# 显式引入共享库声明(GenLib 生成,勿手写)。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write).
# ⚠ 注释行别以 `Import` / `Include` 开头 —— 前端会把整行当 `#include` 指令。
# ⚠ Never start a comment line with `Import` / `Include` -- it becomes a `#include` directive.
import vml_ui

MAX_FRAMES = 12000
MW = 21
MH = 21
STACK_MAX = 512

C_BG = 0xFF101018
C_WALL = 0xFF2A2A36
C_PATH = 0xFF1A1A24
C_PLAYER = 0xFF51E86E
C_GOAL = 0xFFE06C50
C_TEXT = 0xFFE8E8F0
C_DIM = 0xFF9AA0B0

SW = 360
SH = 620
CELL = 16
OX = 0
OY = 110
LANG = 0

# ⚠ 别叫 `map`:本前端里它和内建 `map()` 撞名,实测整局卡死在 builtin 里。
# ⚠ Do not name it `map`: it collides with the built-in `map()` on this frontend and was
#   measured to hang inside the builtin.
cells = [1] * (MW * MH)
sx = [0] * STACK_MAX
sy = [0] * STACK_MAX
dirs = [0, 0, 0, 0]     # ⚠ 列表字面量放**模块级**:在函数/循环里现建列表实测会卡死(见 generate)
                        # ⚠ The list literal lives at **module level**: building a list inside
                        #   a loop was measured to hang (see generate)
px = 1
py = 1
won = 0
steps = 0
seed = 20268


def rnd(n):
    # 16 位 LCG(32 位整数下 C 的 32 位 LCG 会溢出、恒返回 0,见 game2048.py)。
    # 16-bit LCG (the C 32-bit LCG overflows with 32-bit ints and always returns 0; see game2048.py).
    global seed
    seed = (seed * 1103 + 12345) % 32768
    return (seed // 256) % n


def relayout():
    global SW, SH, CELL, OX, OY
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if SW <= 0:
        SW = 360
    if SH <= 0:
        SH = 620
    # 迷宫取「宽度」与「扣掉顶栏/底部提示后的高度」里较小的那个 ——
    # 方形小画布上原来的 `SW < SH - 150` 分支会让棋盘只剩 70px。
    # The maze takes the smaller of "width" and "height after header/footer" --
    # the old `SW < SH - 150` branch left a 70px board on a square tiny canvas.
    OY = 60
    side = SW - 16
    tall = SH - OY - 40
    if tall < side:
        side = tall
    CELL = side // MW
    if CELL < 3:
        CELL = 3
    OX = (SW - MW * CELL) // 2


# 深度优先挖洞:从 (1,1) 出发,每次跳两格挖通中间那格。
# Depth-first carving from (1,1); each step jumps two cells and opens the one between.
def generate():
    x = 0
    while x < MW:
        y = 0
        while y < MH:
            cells[x * MH + y] = 1
            y = y + 1
        x = x + 1

    top = 0
    x = 1
    y = 1
    cells[x * MH + y] = 0
    sx[top] = x
    sy[top] = y
    top = top + 1

    while top > 0:
        cx = sx[top - 1]
        cy = sy[top - 1]
        n = 0
        # 找出四个方向里"还全是墙"的那些(那种才没挖过)
        # Collect the directions whose two-step target is still all wall (not carved yet).
        if cx + 2 < MW - 1 and cells[(cx + 2) * MH + cy] == 1:
            dirs[n] = 0
            n = n + 1
        if cx - 2 > 0 and cells[(cx - 2) * MH + cy] == 1:
            dirs[n] = 1
            n = n + 1
        if cy + 2 < MH - 1 and cells[cx * MH + cy + 2] == 1:
            dirs[n] = 2
            n = n + 1
        if cy - 2 > 0 and cells[cx * MH + cy - 2] == 1:
            dirs[n] = 3
            n = n + 1

        if n == 0:
            top = top - 1          # 死路:回退 / dead end: backtrack
            continue

        k = dirs[rnd(n)]
        if k == 0:
            cells[(cx + 1) * MH + cy] = 0
            cx = cx + 2
        elif k == 1:
            cells[(cx - 1) * MH + cy] = 0
            cx = cx - 2
        elif k == 2:
            cells[cx * MH + cy + 1] = 0
            cy = cy + 2
        else:
            cells[cx * MH + cy - 1] = 0
            cy = cy - 2
        cells[cx * MH + cy] = 0
        if top < STACK_MAX:
            sx[top] = cx
            sy[top] = cy
            top = top + 1

    # 右下角出口强制打通(保证一定到得了)
    # Force the bottom-right exit open (must be reachable).
    i = 0
    while i < 3:
        if MW - 2 - i >= 0:
            cells[(MW - 2 - i) * MH + MH - 2] = 0
        if MH - 2 - i >= 0:
            cells[(MW - 2) * MH + MH - 2 - i] = 0
        i = i + 1


def new_game():
    global px, py, won, steps
    generate()
    px = 1
    py = 1
    won = 0
    steps = 0


def draw():
    ui_2d_clear(C_BG)

    x = 0
    while x < MW:
        y = 0
        while y < MH:
            if cells[x * MH + y] == 1:
                c = C_WALL
            else:
                c = C_PATH
            ui_2d_rect(OX + x * CELL, OY + y * CELL, CELL, CELL, c, 1, 0, 0)
            y = y + 1
        x = x + 1

    ui_2d_rect(OX + (MW - 2) * CELL + 1, OY + (MH - 2) * CELL + 1,
               CELL - 2, CELL - 2, C_GOAL, 1, 0, 2)
    ui_2d_rect(OX + px * CELL + 1, OY + py * CELL + 1,
               CELL - 2, CELL - 2, C_PLAYER, 1, 0, CELL // 2)

    ui_2d_text(10, 24, str(steps), C_TEXT, 15, VML_ANCHOR_LEFT)
    if LANG == 0:
        ui_2d_text(10, 46, "步数", C_DIM, 10, VML_ANCHOR_LEFT)
    else:
        ui_2d_text(10, 46, "steps", C_DIM, 10, VML_ANCHOR_LEFT)

    if won == 1:
        if LANG == 0:
            msg = "走出来了!点一下/ESC 换一张"
        else:
            msg = "Out! Tap / ESC for a new maze"
        ui_2d_text(SW // 2, OY + MH * CELL + 28, msg, C_TEXT, 15, VML_ANCHOR_CENTER)
    else:
        if LANG == 0:
            msg = "方向键 / 点屏幕四边,走到红格"
        else:
            msg = "Arrows / tap a screen edge; reach the red cell"
        ui_2d_text(SW // 2, OY + MH * CELL + 28, msg, C_DIM, 11, VML_ANCHOR_CENTER)
    ui_2d_present()


def move(dx, dy):
    global px, py, won, steps
    if won == 1:
        return
    nx = px + dx
    ny = py + dy
    if nx < 0 or ny < 0 or nx >= MW or ny >= MH:
        return
    if cells[nx * MH + ny] == 1:
        return
    px = nx
    py = ny
    steps = steps + 1
    if px == MW - 2 and py == MH - 2:
        won = 1


# 点屏幕四边:离哪边最近就往那边走
# A screen edge decides the direction (whichever side is nearest).
def tap(x, y):
    if won == 1:
        new_game()
        return
    dl = x
    dr = SW - x
    dt = y
    db = SH - y
    if dl <= dr and dl <= dt and dl <= db:
        move(-1, 0)
    elif dr <= dt and dr <= db:
        move(1, 0)
    elif dt <= db:
        move(0, -1)
    else:
        move(0, 1)


def main():
    global LANG
    LANG = ui_scr_get_language()

    relayout()
    ui_win_open_ex("迷宫" if LANG == 0 else "Maze (py)", 0, 0, 1, 0)
    relayout()
    new_game()
    draw()

    tid = ui_timer_set(120, 1)
    frames = 0
    done = 0
    while done == 0 and ui_win_is_closed() == 0:
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(120)
        if t == 0:
            continue

        if t == 6 or t == 4:
            tap(ui_msg_get_a(), ui_msg_get_b())
            draw()
            continue

        if t == 1:
            k = ui_msg_get_a()
            if k == 27:
                new_game()
            elif k == 37:
                move(-1, 0)
            elif k == 39:
                move(1, 0)
            elif k == 38:
                move(0, -1)
            elif k == 40:
                move(0, 1)
            draw()
            continue

        if t == 11:
            relayout()
            draw()
            continue

        if t == 9:
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1
            continue

        if t == 10:
            break

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()