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

java/app/maze.java · 11701 字节 · 下载原文

▶ 在浏览器里试玩

// 迷宫 —— 用 **Java** 写的手机小游戏(探索 / 每局现生成)
// Maze — a small phone game written in **Java** (exploration / generated every round)
//
// 玩法(与 `Examples/c/app/maze.c` / `Examples/python/app/maze.py` 同一套):
// Gameplay (same rules as the C / Python versions):
//   · 每局**现生成**一张新迷宫(深度优先挖洞,一定连通、一定有路);
//   · 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 red cell 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", which is hard to diagnose.
//
// ## Java 前端三条实测约束(见 `Examples/java/app/memory.java` 文件头)
// ## Four measured conventions of this Java front end (see `Examples/java/app/memory.java`)
//
//   ① `import vml.ui.*;` 带来 `ui_*` 函数但**不带常量** ⇒ 常量就地声明;
//   ① `import vml.ui.*;` brings `ui_*` functions but **no constants** ⇒ declare them here;
//   ② 状态一律放 `static int[]`(堆上,读写可靠);
//   ② state lives in `static int[]` (heap-backed, reliable);
//   ③ 屏幕坐标 → 格子必须**先判负再除**(Java 除法向零截断)。
//   ③ screen coordinates → cell must **test for negatives before dividing** (Java truncates toward zero).
//
//   ④ **数组维度与下标一律用字面量,不要用 `static final` 常量**(本文件实测 2026-11-14):
//   ④ **Array dimensions and subscripts are always literals, never a `static final` constant**
//      (measured in this very file on 2026-11-14):
//      `new int[CELLS]` + `while (i < CELLS)` 时**最后一格没被初始化**(`cells[440]` 读到 0);
//      with `new int[CELLS]` + `while (i < CELLS)` the **last cell stayed uninitialised** (`cells[440]` read 0);
//      写 `cells[1 * N + 1] = 0` 之后再读 `N` 得到 **1**(期望 21)⇒ 四个方向条件全假、
//      迷宫生成 23 步就提前收工,后面还会 `内存访问越界(地址=FFFFFFFC)`。
//      after `cells[1 * N + 1] = 0`, the constant `N` read back as **1** (21 expected) => all four
//      direction tests went false, generation finished after 23 steps, then a memory fault at -4.
//      ⇒ 维度/上限/下标全写成 21 / 441 / 512,**别经过常量名**。
//      ⇒ write 21 / 441 / 512 directly for dimensions, limits and subscripts — never via a constant name.
//
// 跑法 —— 手机:`vml run examples/java/maze.java`
// How to run — on the phone: `vml run examples/java/maze.java`
// 跑法 —— 桌面:`vmlcli Examples/java/maze.java --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/java/maze.java --screen 480x640 --frames /tmp/fr`

import vml.ui.*;

public class Maze {
    static final int MSG_KEYDOWN   = 1;
    static final int MSG_MOUSEDOWN = 4;
    static final int MSG_TOUCHDOWN = 6;
    static final int MSG_TIMER     = 9;
    static final int MSG_CLOSE     = 10;
    static final int MSG_RESIZE    = 11;

    static final int KEY_ESC = 27;

    static final int ANCHOR_LEFT   = 0;
    static final int ANCHOR_CENTER = 1;

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

    
    
    // ⚠ 这里**没有** N / CELLS / STACK_MAX 常量:数组维度与下标一律用字面量(见文件头 ④)。
    // ⚠ There are **no** N / CELLS / STACK_MAX constants here: dimensions and subscripts are literals (header ④).
    static final int MAX_FRAMES = 12000;
    static final int TIMER_MS = 120;

    // 标量状态槽(见文件头 ②):0=px 1=py 2=won 3=steps 4=seed
    // 5=cell 6=ox 7=oy 8=sw 9=sh 10=lang 11=top 12=frames 13=done
    static int[] S = new int[24];
    static int[] cells = new int[441];
    static int[] stx = new int[512];
    static int[] sty = new int[512];
    static int[] dirs = new int[4];

    static String mzTr(String zh, String en) {
        if (S[10] == 0) return zh;
        return en;
    }

    static int mzRnd(int n) {
        S[4] = (S[4] * 1103 + 12345) % 32768;
        return (S[4] / 256) % n;
    }

    static void mzLayout() {
        S[8] = ui_scr_get_w();
        S[9] = ui_scr_get_h();
        if (S[8] <= 0) S[8] = 360;
        if (S[9] <= 0) S[9] = 620;
        // 矮屏把页眉从 110px 压到 56px、页脚留 30px,21×21 迷宫才能铺满剩下的高度。
        // On short screens the header drops 110px -> 56px and the footer keeps 30px, so the 21x21 maze fills the rest.
        int top = 110;
        int foot = 30;
        if (S[9] < 480) { top = 56; }
        int side = S[8] - 16;
        int avail = S[9] - top - foot;
        if (avail < side) side = avail;
        S[5] = side / 21;
        if (S[5] < 3) S[5] = 3;
        S[6] = (S[8] - 21 * S[5]) / 2;
        S[7] = top + (avail - 21 * S[5]) / 2;
        if (S[7] < top) S[7] = top;
    }

    // 开一局:DFS 挖洞(显式栈),每局现生成
    // New maze: DFS carving with an explicit stack, generated fresh every round
    static void mzNew() {
        int i = 0;
        while (i < 441) {
            cells[i] = 1;
            i = i + 1;
        }
        S[4] = 20268;
        S[11] = 0;
        cells[1 * 21 + 1] = 0;
        stx[S[11]] = 1;
        sty[S[11]] = 1;
        S[11] = S[11] + 1;
        while (S[11] > 0) {
            int cx = stx[S[11] - 1];
            int cy = sty[S[11] - 1];
            int n = 0;
            if (cx + 2 < 21 - 1 && cells[(cx + 2) * 21 + cy] == 1) { dirs[n] = 0; n = n + 1; }
            if (cx - 2 > 0 && cells[(cx - 2) * 21 + cy] == 1) { dirs[n] = 1; n = n + 1; }
            if (cy + 2 < 21 - 1 && cells[cx * 21 + cy + 2] == 1) { dirs[n] = 2; n = n + 1; }
            if (cy - 2 > 0 && cells[cx * 21 + cy - 2] == 1) { dirs[n] = 3; n = n + 1; }
            if (n == 0) {
                S[11] = S[11] - 1;
            } else {
                int k = dirs[mzRnd(n)];
                if (k == 0) { cells[(cx + 1) * 21 + cy] = 0; cx = cx + 2; }
                else if (k == 1) { cells[(cx - 1) * 21 + cy] = 0; cx = cx - 2; }
                else if (k == 2) { cells[cx * 21 + cy + 1] = 0; cy = cy + 2; }
                else { cells[cx * 21 + cy - 1] = 0; cy = cy - 2; }
                cells[cx * 21 + cy] = 0;
                if (S[11] < 512) {
                    stx[S[11]] = cx;
                    sty[S[11]] = cy;
                    S[11] = S[11] + 1;
                }
            }
        }
        // 右下角出口强制打通(保证一定到得了)
        // Force the bottom-right exit open (so it is always reachable)
        i = 0;
        while (i < 3) {
            cells[(21 - 2 - i) * 21 + 21 - 2] = 0;
            cells[(21 - 2) * 21 + 21 - 2 - i] = 0;
            i = i + 1;
        }
        S[0] = 1;
        S[1] = 1;
        S[2] = 0;
        S[3] = 0;
    }

    static void mzDraw() {
        ui_2d_clear(C_BG);
        int x = 0;
        while (x < 21) {
            int y = 0;
            while (y < 21) {
                if (cells[x * 21 + y] == 1)
                    ui_2d_rect(S[6] + x * S[5], S[7] + y * S[5], S[5], S[5], C_WALL, 1, 0, 0);
                else
                    ui_2d_rect(S[6] + x * S[5], S[7] + y * S[5], S[5], S[5], C_PATH, 1, 0, 0);
                y = y + 1;
            }
            x = x + 1;
        }
        ui_2d_rect(S[6] + (21 - 2) * S[5] + 1, S[7] + (21 - 2) * S[5] + 1,
                   S[5] - 2, S[5] - 2, C_GOAL, 1, 0, 2);
        ui_2d_rect(S[6] + S[0] * S[5] + 1, S[7] + S[1] * S[5] + 1,
                   S[5] - 2, S[5] - 2, C_PLAYER, 1, 0, S[5] / 2);

        ui_2d_text(10, 24, "" + S[3], C_TEXT, 15, ANCHOR_LEFT);
        ui_2d_text(10, 46, mzTr("步数", "steps"), C_DIM, 10, ANCHOR_LEFT);

        // 复用循环结束后的 y 当提示行 y,并钳进画布(240×240 底部只剩几像素)。
        // Reuse y after the loops as the hint line's y, clamped into the canvas (a 240x240 footer is only a few pixels).
        y = S[7] + 21 * S[5] + 28;
        if (y > S[9] - 10) y = S[9] - 10;
        if (S[2] != 0) {
            ui_2d_text(S[8] / 2, y, mzTr("走出来了!点一下/ESC 换一张", "Out! Tap / ESC for a new maze"),
                       C_TEXT, 15, ANCHOR_CENTER);
        } else {
            ui_2d_text(S[8] / 2, y, mzTr("方向键 / 点屏幕四边,走到红格", "Arrows / tap a screen edge; reach the red cell"),
                       C_DIM, 11, ANCHOR_CENTER);
        }
    }

    // 试着走一步(nx, ny 是目标格);走成了返回 1
    // Try one step to (nx, ny); returns 1 when the move happened
    static int mzMove(int nx, int ny) {
        if (S[2] != 0) return 0;
        if (nx < 0 || ny < 0 || nx >= 21 || ny >= 21) return 0;
        if (cells[nx * 21 + ny] != 0) return 0;
        S[0] = nx;
        S[1] = ny;
        S[3] = S[3] + 1;
        if (nx == 21 - 2 && ny == 21 - 2) S[2] = 1;
        return 1;
    }

    public static void main(String[] args) {
        S[10] = ui_scr_get_language();
        ui_win_open(mzTr("迷宫", "Maze"), 0, 0);
        ui_scr_set_keep_on(1);

        mzLayout();
        mzNew();
        mzDraw();

        int tid = ui_timer_set(TIMER_MS, 1);

        while (S[13] == 0 && ui_win_is_closed() == 0) {
            int t = ui_msg_fetch_wait(TIMER_MS);
            if (t == MSG_CLOSE) { S[13] = 1; }

            if (t == MSG_KEYDOWN) {
                int k = ui_msg_get_a();
                if (k == KEY_ESC) { mzNew(); }
                else if (k == 37) { mzMove(S[0] - 1, S[1]); }
                else if (k == 39) { mzMove(S[0] + 1, S[1]); }
                else if (k == 38) { mzMove(S[0], S[1] - 1); }
                else if (k == 40) { mzMove(S[0], S[1] + 1); }
            }

            if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN) {
                int tx = ui_msg_get_a();
                int ty = ui_msg_get_b();
                if (S[2] != 0) {
                    mzNew();
                } else {
                    // 点屏幕四边:离哪边最近就往那边走(坐标一定非负,不用先判负)
                    // A screen edge decides the direction (whichever side is nearest)
                    int dl = tx;
                    int dr = S[8] - tx;
                    int dt = ty;
                    int db = S[9] - ty;
                    if (dl <= dr && dl <= dt && dl <= db) { mzMove(S[0] - 1, S[1]); }
                    else if (dr <= dt && dr <= db) { mzMove(S[0] + 1, S[1]); }
                    else if (dt <= db) { mzMove(S[0], S[1] - 1); }
                    else { mzMove(S[0], S[1] + 1); }
                }
            }

            if (t == MSG_RESIZE) { mzLayout(); }

            if (t == MSG_TIMER) {
                S[12] = S[12] + 1;
                if (S[12] >= MAX_FRAMES) S[13] = 1;
            }

            mzDraw();
            ui_2d_present();
        }

        ui_timer_kill(tid);
        ui_scr_set_keep_on(0);
        ui_win_close();
    }
}