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

java/app/puzzle15.java · 11537 字节 · 下载原文

▶ 在浏览器里试玩

// 数字华容道 / 15 格滑块拼图 —— 用 **Java** 写的手机小游戏
// The 15-puzzle — a small phone game written in **Java**
//
// 玩法:4×4 里 15 个数字 + 1 个空格;点空格**旁边**的块就滑过去;
// Gameplay: 15 numbers plus one blank in a 4x4; tap a tile **next to** the blank and it slides over;
//       排成 1..15 顺序即通关。
//       arranging 1..15 in order wins.
//
// 与 `Examples/c/app/puzzle15.c` / `Examples/python/app/puzzle15.py` 同一套玩法与布局。
// Same rules and layout as `Examples/c/app/puzzle15.c` / `Examples/python/app/puzzle15.py`.
//
// ◆ 打乱用的是「从解好的局面随机走 400 步合法步」⇒ 局面**一定可解**。
// ◆ The shuffle is "400 random legal moves from the solved board" ⇒ the board is **always solvable**.
//   随手随机交换有一半是死局(15-puzzle 的奇偶不变量)。
//   Random swapping is a dead board half the time (the 15-puzzle parity invariant).
//
// ◆ Java 前端实测约束(详见 memory.java 文件头,这里只重复本文件踩到的两条)
// ◆ Java front-end conventions (see memory.java; the two that bite here)
//
//   ① `import vml.ui.*;` 只带函数不带常量 ⇒ 消息类型 / 锚点就地声明成 `static final int`。
//   ① `import vml.ui.*;` brings functions but no constants ⇒ declare them as `static final int`.
//   ② 屏幕坐标 → 格子:**先判负再除**。Java 的 `/` 向零截断,`-10/80 == 0`;
//   ② Screen point → cell: **test negatives before dividing**. Java's `/` truncates toward zero,
//      否则棋盘外一点就等价于点中第一格(Python 的 `//` 是向下取整,没有这个坑)。
//      so an off-board tap would hit the first cell (Python's `//` floors and hides this).
//
// 跑法 / How to run:
//   手机 / phone:        vml run examples/java/app/puzzle15.java
//   桌面 / desktop:      vmlcli Examples/java/app/puzzle15.java --screen 411x726 --frames /tmp/fr

import vml.ui.*;

public class Puzzle15 {

    // ── 消息类型 / 键码(源:Lib/c/vml_ui.h)──
    // ── Message types / key codes (source: Lib/c/vml_ui.h) ──
    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 MSG_ORIENT    = 12;

    static final int KEY_ESC = 27;

    // ── 文字锚点(与 vml_ui.h 同值)──
    static final int ANCHOR_LEFT   = 0;
    static final int ANCHOR_CENTER = 1;

    // ── 配色:0xAARRGGBB ──
    static final int C_BG    = 0xFF101018;
    static final int C_TILE  = 0xFF4A90D9;   // 已归位(亮蓝)
    static final int C_TILE2 = 0xFF3A6FA8;   // 还没归位(暗蓝)
    static final int C_TEXT  = 0xFFE8E8F0;
    static final int C_DIM   = 0xFF9AA0B0;
    static final int C_HOLE  = 0xFF16161E;

    static final int N = 4;
    static final int SHUFFLE_STEPS = 400;
    static final int MAX_FRAMES = 6000;
    static final int TIMER_MS = 120;

    /* 状态数组 S 的下标
       The S slot map
       0..15  每格的数字(0 = 空格,下标 col*N+row)
       0..15  the number in a cell (0 = blank, index col*N+row)
       16 空格列   17 空格行   18 步数   19 是否已通关
       16 blank column; 17 blank row; 18 moves; 19 solved?
       20 随机种子 21 屏宽   22 屏高   23 格边长
       20 RNG seed; 21 screen width; 22 screen height; 23 cell size
       24 棋盘左沿 25 棋盘上沿 26 界面语言(0 中 1 英) 27 帧号
       24 board left; 25 board top; 26 UI language (0 Chinese, 1 English); 27 frame counter
       28..31 余量 */
    static int[] S = new int[32];

    // ── 小工具 ──
    // ── Small helpers ──

    // 16 位 LCG(32 位状态会溢出退化,见 memory.java)
    // 16-bit LCG (a 32-bit state overflows and degenerates; see memory.java).
    static int puzRnd(int n) {
        S[20] = (S[20] * 1103 + 12345) % 32768;
        return (S[20] / 256) % n;
    }

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

    static void puzSwap(int ax, int ay, int bx, int by) {
        int t = S[ax * N + ay];
        S[ax * N + ay] = S[bx * N + by];
        S[bx * N + by] = t;
    }

    // ── 排版 ──
    static void puzRelayout() {
        int sw = ui_scr_get_w();
        int sh = ui_scr_get_h();
        if (sw <= 0) { sw = 360; }
        if (sh <= 0) { sh = 620; }
        S[21] = sw;
        S[22] = sh;
        // 矮屏压紧页眉/页脚,4×4 拼图从约 68px 放大到约 152px。
        // Tighten header/footer on short screens; the 4x4 puzzle grows from ~68px to ~152px.
        int top = 110;
        int foot = 30;
        if (sh < 480) { top = 56; }
        int side = sw - 20;
        int avail = sh - top - foot;
        if (avail < side) { side = avail; }
        int cell = side / N;
        if (cell < 6) { cell = 6; }
        S[23] = cell;
        S[24] = (sw - N * cell) / 2;
        S[25] = top + (avail - N * cell) / 2;
        if (S[25] < top) { S[25] = top; }
    }

    // 合法步:空格与四邻里挑一个
    // One legal move: pick one of the blank's four neighbours.
    static int puzSlideRandom() {
        int k = puzRnd(4);
        int dx = 0;
        int dy = 0;
        if (k == 0) { dx = 1; }
        if (k == 1) { dx = -1; }
        if (k == 2) { dy = 1; }
        if (k == 3) { dy = -1; }
        int nx = S[16] + dx;
        int ny = S[17] + dy;
        if (nx < 0 || ny < 0 || nx >= N || ny >= N) { return 0; }
        puzSwap(S[16], S[17], nx, ny);
        S[16] = nx;
        S[17] = ny;
        return 1;
    }

    // ── 开局:解好的局面 + 400 步随机合法步 ──
    // ── New game: the solved board + 400 random legal moves ──
    static void puzNewGame() {
        int v = 1;
        int x = 0;
        int y = 0;
        while (x < N) {
            y = 0;
            while (y < N) {
                S[x * N + y] = v;
                v = v + 1;
                y = y + 1;
            }
            x = x + 1;
        }
        S[N * N - 1] = 0;
        S[16] = N - 1;
        S[17] = N - 1;
        int i = 0;
        while (i < SHUFFLE_STEPS) {
            puzSlideRandom();
            i = i + 1;
        }
        S[18] = 0;
        S[19] = 0;
    }

    // 排成 1..15、最后一格是 0 即通关
    // Win when the tiles read 1..15 and the last cell is the blank.
    static int puzCheckWin() {
        int v = 1;
        int x = 0;
        int y = 0;
        while (x < N) {
            y = 0;
            while (y < N) {
                if (x == N - 1 && y == N - 1) {
                    if (S[x * N + y] == 0) { return 1; }
                    return 0;
                }
                if (S[x * N + y] != v) { return 0; }
                v = v + 1;
                y = y + 1;
            }
            x = x + 1;
        }
        return 1;
    }

    // ── 绘制 ──
    static void puzDrawTile(int col, int row) {
        int px = S[24] + col * S[23];
        int py = S[25] + row * S[23];
        int cell = S[23];
        int v = S[col * N + row];
        if (v == 0) {
            ui_2d_rect(px + 2, py + 2, cell - 4, cell - 4, C_HOLE, 1, 0, 6);
            return;
        }
        // 排好的那些用亮蓝、还没回去的用暗蓝 —— 一眼看出差多少
        // Tiles already home are bright blue, the rest dark blue — see the deficit at a glance.
        int c = C_TILE2;
        if ((v - 1) % N == col && (v - 1) / N == row) { c = C_TILE; }
        ui_2d_rect(px + 2, py + 2, cell - 4, cell - 4, c, 1, 0, 8);
        ui_2d_text(px + cell / 2, py + cell / 2 + cell / 8,
                   "" + v, C_TEXT, cell / 2, ANCHOR_CENTER);
    }

    static void puzDraw() {
        int x = 0;
        int y = 0;
        ui_2d_clear(C_BG);

        while (x < N) {
            y = 0;
            while (y < N) {
                puzDrawTile(x, y);
                y = y + 1;
            }
            x = x + 1;
        }

        ui_2d_text(10, 22, "" + S[18], C_TEXT, 15, ANCHOR_LEFT);
        ui_2d_text(10, 42, puzTr("步数", "moves"), C_DIM, 10, ANCHOR_LEFT);

        int msgY = S[25] + N * S[23] + 28;
        if (msgY > S[22] - 10) { msgY = S[22] - 10; }
        if (S[19] == 1) {
            ui_2d_text(S[21] / 2, msgY, puzTr("拼好了!点一下再来", "Solved! Tap for a new one"),
                       C_TEXT, 15, ANCHOR_CENTER);
        } else {
            ui_2d_text(S[21] / 2, msgY, puzTr("点空格旁边的块", "Tap a tile next to the blank"),
                       C_DIM, 12, ANCHOR_CENTER);
        }
        ui_2d_present();
    }

    // 点屏幕:只认空格上下左右相邻的块(斜着不算)
    // Screen tap: only the blank's orthogonal neighbours count (diagonals do not).
    static void puzTap(int tx, int ty) {
        if (S[19] == 1) {
            puzNewGame();
            return;
        }
        // ⚠ 先判负再除(Java 的 / 向零截断)
        // ⚠ Test negatives before dividing (Java's / truncates toward zero).
        int relX = tx - S[24];
        int relY = ty - S[25];
        if (relX < 0 || relY < 0) { return; }
        int x = relX / S[23];
        int y = relY / S[23];
        if (x >= N || y >= N) { return; }

        int adjacent = 0;
        if (x == S[16] && (y == S[17] - 1 || y == S[17] + 1)) { adjacent = 1; }
        if (y == S[17] && (x == S[16] - 1 || x == S[16] + 1)) { adjacent = 1; }
        if (adjacent == 1) {
            puzSwap(S[16], S[17], x, y);
            S[16] = x;
            S[17] = y;
            S[18] = S[18] + 1;
            S[19] = puzCheckWin();
        }
    }

    public static void main(String[] args) {
        int t = 0;
        int tid = 0;

        S[26] = ui_scr_get_language();
        S[20] = 20266;

        puzRelayout();
        ui_win_open_ex(puzTr("数字华容道", "15-puzzle (java)"), 0, 0, 1, 0);
        ui_scr_set_keep_on(1);
        puzRelayout();
        puzNewGame();
        puzDraw();

        tid = ui_timer_set(TIMER_MS, 1);

        while (ui_win_is_closed() == 0) {
            t = ui_msg_fetch_wait(TIMER_MS);
            if (t == MSG_CLOSE) { break; }

            if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN) {
                puzTap(ui_msg_get_a(), ui_msg_get_b());
                puzDraw();
                continue;
            }

            if (t == MSG_KEYDOWN) {
                if (ui_msg_get_a() == KEY_ESC) {
                    puzNewGame();
                    puzDraw();
                }
                continue;
            }

            if (t == MSG_RESIZE || t == MSG_ORIENT) {
                puzRelayout();
                puzDraw();
                continue;
            }

            if (t == MSG_TIMER) {
                S[27] = S[27] + 1;
                if (S[27] >= MAX_FRAMES) { break; }
                puzDraw();
                continue;
            }
        }

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

        System.out.print("puzzle15: moves="); System.out.println(S[18]);
        System.out.print("puzzle15: solved="); System.out.println(S[19]);
        System.out.print("puzzle15: blank="); System.out.print(S[16]); System.out.print(","); System.out.println(S[17]);
        System.out.println("puzzle15: done");
    }
}