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

java/app/lightsout.java · 19527 字节 · 下载原文

▶ 在浏览器里试玩

// 关灯(Lights Out)—— 用 **Java** 写的手机益智小游戏
// Lights Out — a small puzzle game for phones, written in **Java**
//
// 玩法:5×5 的灯阵,点一格会把它**自己以及上下左右**一起翻转(亮变灭、灭变亮)。
// Gameplay: a 5×5 grid of lights. Tapping a cell flips **itself and its four neighbours**
// 目标是把所有灯全部熄灭。
// (on becomes off, off becomes on). The goal is to turn every light off.
//
// 键盘:方向键移动光标、回车/空格按下去;R 重开;ESC 退出。
// Keyboard: arrows move a cursor, Enter/Space presses it; R restarts; ESC quits.
// 触摸:直接点格子;点底部的「重开」按钮重新开局;过关后点任意处再来一局。
// Touch: tap a cell directly; tap the Restart button at the bottom for a new board;
//        after a clear, tap anywhere for another round.
//
// ◆ 为什么这个游戏适合当示例
// ◆ Why this game makes a good sample
//
// 它是**回合制**的:没有物理、没有连续动画,一帧只由「输入 / 定时器」驱动。
// It is **turn-based**: no physics, no continuous animation; a frame is driven only by
// 这样就能把重点放在「状态数组 + 命中判定 + 重排」这三件最常用的事上。
// input or the timer. That keeps the focus on the three everyday things: a state array,
// hit testing, and relayout on resize.
//
// ◆ 这个前端的两条写法约定(实测出来的,不是风格)
// ◆ Two conventions forced by this front end (measured, not style)
//
//   ① 一句 `import vml.ui.*;` 就带来全部 `ui_*` 函数声明 —— **不用再手写 static native 块**。
//   ① One `import vml.ui.*;` brings in every `ui_*` declaration — **no hand-written static native block**.
//      ⚠ 但那份清单里**只有函数、没有常量**(`VML_ANCHOR_CENTER` 这类名字导入后仍是未声明),
//      ⚠ But that list carries **functions only, no constants** (names like `VML_ANCHOR_CENTER` stay undeclared),
//      所以本文件把自己的常量就地声明成 `static final`。颜色照旧写十六进制(前端已支持)。
//      so this file declares its own constants as `static final`. Colors keep their hex form (the front end supports it).
//
//   ② 状态一律放 `static int[] S`(Java 的实例/静态数组都落在堆上,读写可靠)。
//   ② All state lives in `static int[] S` (Java arrays live on the heap; reads and writes are reliable).
//
// 数值的唯一真源仍是 `Lib/c/vml_ui.h`。
// The single source of truth for these numbers is still `Lib/c/vml_ui.h`.
//
// 跑法:手机 `vml run examples/java/app/lightsout.java`;
// How to run: phone `vml run examples/java/app/lightsout.java`;
//       桌面 `vmlcli Examples/java/app/lightsout.java --screen 411x726 --frames /tmp/fr`
//       desktop `vmlcli Examples/java/app/lightsout.java --screen 411x726 --frames /tmp/fr`
//       `--arg demo` 是无头验收模式:固定局面 + 自己退出 + 打印判据。
//       `--arg demo` is the headless acceptance mode: fixed board + self-exit + printed checkpoints.

import vml.ui.*;

public class LightsOut {

    // ── 消息类型 / 键码(源: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;
    static final int KEY_ENTER = 13;
    static final int KEY_SPACE = 32;
    static final int KEY_R     = 82;
    static final int KEY_LEFT  = 37;
    static final int KEY_UP    = 38;
    static final int KEY_RIGHT = 39;
    static final int KEY_DOWN  = 40;

    // ── 文字锚点 / 竖对齐(与 vml_ui.h 同值)──
    // ── Text anchors / vertical alignment (same values as vml_ui.h) ──
    static final int ANCHOR_LEFT   = 0;
    static final int ANCHOR_CENTER = 1;
    static final int VANCHOR_MIDDLE = 1;

    // ── 配色:0xAARRGGBB(Java 前端支持十六进制字面量)──
    // ── Palette: 0xAARRGGBB (this front end accepts hex literals) ──
    static final int C_BG      = 0xFF101018;   // 背景
    // background
    static final int C_PANEL   = 0xFF171B24;   // 棋盘底板
    // board panel
    static final int C_ON      = 0xFFFFC040;   // 亮着的灯(暖金)
    // a lit cell (warm gold)
    static final int C_ON_HI   = 0xFFFFE08A;   // 灯芯高光
    // the bright core
    static final int C_OFF     = 0xFF232A38;   // 灭掉的灯
    // a dark cell
    static final int C_LINE    = 0xFF3A4252;   // 灭灯的描边
    // the stroke of a dark cell
    static final int C_TEXT    = 0xFFE8E8F0;
    static final int C_MUTED   = 0xFF9AA0B0;
    static final int C_GOLD    = 0xFFFFC040;
    static final int C_GREEN   = 0xFF51E86E;
    static final int C_BTN     = 0xFF2A3344;
    static final int C_BTN_HI  = 0xFF3A4A60;
    static final int C_SCRIM   = 0xCC000000;   // 过关遮罩(半透明黑)

    static final int N = 5;
    static final int CELLS = 25;
    static final int DEMO_TAPS = 7;            // 正常开局随机点几下
    // how many random flips normal play starts from

    /* 状态数组 S 的下标
       The S slot map
       0..24   灯:1 = 亮,0 = 灭(按下标 r*5+c)
       0..24   lights: 1 = on, 0 = off (index r*5+c)
       25 步数   26 是否已过关   27 帧号   28 屏宽   29 屏高   30 界面语言
       25 moves; 26 solved?; 27 frame; 28 screen width; 29 screen height; 30 UI language
       31 棋盘左沿   32 棋盘上沿   33 格边长
       31 board left; 32 board top; 33 cell size
       34 亮灯数   35 帧上限(0 = 不限)   36 光标行   37 光标列
       34 lit count; 35 frame limit (0 = none); 36 cursor row; 37 cursor col
       38 按钮 x   39 按钮 y   40 按钮宽   41 按钮高
       38 button x; 39 button y; 40 button width; 41 button height
       42 演示用:第一次的亮灯数   43 演示用:第一次的步数
       42 demo: lit count after the first tap set; 43 demo: moves at that point */
    static int[] S = new int[48];

    // ── 小工具 ──
    // ── Small helpers ──
    static int inRange(int v, int lo, int hi) {
        if (v < lo) { return 0; }
        if (v > hi) { return 0; }
        return 1;
    }

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

    // ── 棋盘逻辑 ──
    // ── Board logic ──
    static void flip(int r, int c) {
        if (inRange(r, 0, N - 1) == 0) { return; }
        if (inRange(c, 0, N - 1) == 0) { return; }
        if (S[r * N + c] == 0) { S[r * N + c] = 1; } else { S[r * N + c] = 0; }
    }

    static void countOn() {
        int i = 0;
        int n = 0;
        while (i < CELLS) {
            if (S[i] != 0) { n = n + 1; }
            i = i + 1;
        }
        S[34] = n;
    }

    // 玩家按下一格:自身 + 四邻翻转,步数 +1,然后判过关。
    // A player press: flip the cell and its four neighbours, count a move, then test for a clear.
    static void press(int r, int c) {
        if (S[26] != 0) { return; }
        flip(r, c);
        flip(r - 1, c);
        flip(r + 1, c);
        flip(r, c - 1);
        flip(r, c + 1);
        S[25] = S[25] + 1;
        countOn();
        if (S[34] == 0) {
            S[26] = 1;
            ui_audio_beep(1047, 180);
        } else {
            ui_audio_beep(520, 35);
        }
    }

    // 开局:从全灭出发随机翻若干格 —— 这样得到的局面**一定可解**(把同样几下再按一遍就全灭)。
    // New board: start from all-off and flip a few random cells — the result is **always solvable**
    // (press the same cells again and it goes all-off).
    static void clearBoard() {
        int i = 0;
        while (i < CELLS) { S[i] = 0; i = i + 1; }
        S[25] = 0;
        S[26] = 0;
        S[34] = 0;
    }

    static void newBoard(int flips) {
        int i = 0;
        clearBoard();
        i = 0;
        while (i < flips) {
            int r = ui_math_rand(N);
            int c = ui_math_rand(N);
            flip(r, c);
            i = i + 1;
        }
        countOn();
        // 极小概率随机翻完仍是全灭 —— 补一下,避免"开局即过关"
        // A tiny chance the random flips cancel out — nudge once so the game does not start solved
        if (S[34] == 0) { flip(0, 0); countOn(); }
        S[36] = 2;
        S[37] = 2;
    }

    // ── 排版:全部由屏宽屏高推出来,没有一处写死的画布尺寸 ──
    // ── Layout: everything is derived from the screen size; no hard-coded canvas value ──
    static void layout() {
        int w = S[28];
        int h = S[29];
        int small = 0;
        if (w < 360 || h < 360) { small = 1; }
        // 小屏收紧页眉与按钮,给棋盘留出尽可能大的空间;大屏保持原比例。
        // Small screens tighten the header and the button so the board gets the space; large screens keep the old ratios.
        int header = 132;
        int foot = 24;
        int btnH = 52;
        int btnGap = 24;
        int btnW = 200;
        if (small != 0) {
            header = 64;
            foot = 16;
            btnH = 32;
            btnGap = 12;
            btnW = 132;
        }
        int availW = w - 24;
        int availH = h - header - btnH - btnGap - foot;
        int cell = availW / N;
        if (availH / N < cell) { cell = availH / N; }
        if (cell < 16) { cell = 16; }
        S[33] = cell;
        S[31] = (w - cell * N) / 2;
        S[32] = header + (availH - cell * N) / 2;
        if (S[32] < header) { S[32] = header; }
        S[40] = btnW;
        S[41] = btnH;
        S[38] = (w - S[40]) / 2;
        S[39] = S[32] + cell * N + btnGap;
        int maxY = h - foot - btnH;
        if (S[39] > maxY) { S[39] = maxY; }
        if (S[39] < S[32] + cell * N) { S[39] = S[32] + cell * N; }
    }

    // 屏幕坐标 → 格子(不在棋盘里返回 -1)
    // Screen point -> cell (-1 when outside the board)
    static int cellAt(int x, int y) {
        int relX = x - S[31];
        int relY = y - S[32];
        if (relX < 0 || relY < 0) { return -1; }
        int c = relX / S[33];
        int r = relY / S[33];
        if (c >= N || r >= N) { return -1; }
        return r * N + c;
    }

    static int inButton(int x, int y) {
        if (x < S[38] || x > S[38] + S[40]) { return 0; }
        if (y < S[39] || y > S[39] + S[41]) { return 0; }
        return 1;
    }

    // ── 绘制 ──
    // ── Drawing ──
    static void drawCell(int r, int c, int on, int focused) {
        int x = S[31] + c * S[33];
        int y = S[32] + r * S[33];
        int pad = 4;
        int sz = S[33] - pad * 2;
        if (on != 0) {
            ui_2d_rect(x + pad, y + pad, sz, sz, C_ON, 1, 0, 9);
            ui_2d_rect(x + pad + sz / 3, y + pad + sz / 3, sz / 3, sz / 3, C_ON_HI, 1, 0, 6);
        } else {
            ui_2d_rect(x + pad, y + pad, sz, sz, C_OFF, 1, 0, 9);
            ui_2d_rect(x + pad, y + pad, sz, sz, C_LINE, 0, 1, 9);
        }
        if (focused != 0) {
            ui_2d_rect(x + pad - 2, y + pad - 2, sz + 4, sz + 4, C_GREEN, 0, 2, 10);
        }
    }

    static void draw() {
        int i = 0;
        int r = 0;
        int c = 0;
        int w = S[28];
        int h = S[29];

        ui_2d_clear(C_BG);

        int small = 0;
        if (w < 360 || h < 360) { small = 1; }
        if (small != 0) {
            // 小屏只留三行:标题 / 一句玩法 / 步数与剩余灯数并排
            // Small screens keep three lines: title, a one-line rule, and moves + lit count together.
            ui_2d_text(w / 2, 12, tr("关灯", "Lights Out"), C_TEXT, 18, ANCHOR_CENTER);
            ui_2d_text(w / 2, 32, tr("点一格,翻转十字", "Tap a cell: flip a cross"), C_MUTED, 9, ANCHOR_CENTER);
            ui_2d_text(w / 2, 48, tr("步数 ", "Moves ") + S[25] + tr(" · 还剩 ", " · Lit ") + S[34],
                       C_GOLD, 11, ANCHOR_CENTER);
        } else {
            ui_2d_text(w / 2, 22, tr("关灯", "Lights Out"), C_TEXT, 26, ANCHOR_CENTER);
            ui_2d_text(w / 2, 56, tr("点一格,它和上下左右一起翻转", "Tap a cell: it and its neighbours flip"), C_MUTED, 13, ANCHOR_CENTER);
            ui_2d_text(w / 2, 84, tr("步数 ", "Moves ") + S[25], C_GOLD, 16, ANCHOR_CENTER);
            ui_2d_text(w / 2, 110, tr("还剩 ", "Lit: ") + S[34], C_MUTED, 13, ANCHOR_CENTER);
        }

        // 棋盘底板:格距 2px 的浅色边由底板透出来,比逐格描边省图元
        // Board panel: a 2px gap lets the panel colour show through — cheaper than outlining every cell
        ui_2d_rect(S[31] - 6, S[32] - 6, S[33] * N + 12, S[33] * N + 12, C_PANEL, 1, 0, 16);

        while (r < N) {
            c = 0;
            while (c < N) {
                int focus = 0;
                if (r == S[36] && c == S[37]) { focus = 1; }
                drawCell(r, c, S[r * N + c], focus);
                c = c + 1;
            }
            r = r + 1;
        }

        // 「重开」按钮
        // Restart button
        ui_2d_rect(S[38], S[39], S[40], S[41], C_BTN, 1, 0, 14);
        ui_2d_rect(S[38], S[39], S[40], S[41], C_BTN_HI, 0, 1, 14);
        ui_2d_text_v(w / 2, S[39] + S[41] / 2, tr("重开(R)", "Restart (R)"), C_TEXT, small != 0 ? 14 : 16,
                     ANCHOR_CENTER, VANCHOR_MIDDLE, 0);

        if (small != 0) {
            ui_2d_text(w / 2, h - 9, tr("方向键移动 · 回车按下 · ESC 退出", "Arrows move · Enter presses · ESC quits"),
                       C_MUTED, 9, ANCHOR_CENTER);
        } else {
            ui_2d_text(w / 2, h - 10, tr("方向键移动 · 回车按下 · ESC 退出", "Arrows move · Enter presses · ESC quits"), C_MUTED, 12, ANCHOR_CENTER);
        }

        if (S[26] != 0) {
            ui_2d_rect(0, 0, w, h, C_SCRIM, 1, 0, 0);
            ui_2d_text(w / 2, h / 2 - 34, tr("全部熄灭!", "All lights out!"), C_GREEN, 30, ANCHOR_CENTER);
            ui_2d_text(w / 2, h / 2 + 6, tr("用了 ", "Solved in ") + S[25] + tr(" 步", " moves"), C_TEXT, 17, ANCHOR_CENTER);
            ui_2d_text(w / 2, h / 2 + 40, tr("点任意处再来一局", "Tap anywhere for another round"), C_MUTED, 14, ANCHOR_CENTER);
        }

        ui_2d_present();
    }

    // 无头验收:固定局面 + 已知按键序列,把结果打进 stdout。
    // Headless acceptance: a fixed board plus a known press sequence, with the results printed to stdout.
    static void demoCheck() {
        clearBoard();
        press(0, 0);
        press(2, 2);
        press(4, 4);
        S[42] = S[34];
        S[43] = S[25];
        System.out.print("lightsout: on1=");   System.out.println(S[42]);
        System.out.print("lightsout: moves1="); System.out.println(S[43]);
        // 同样三下再按一遍 ⇒ 各自翻转两次、回到全灭 —— 同时验证「过关」判定。
        // Press the same three again ⇒ every cell flips twice and returns to all-off — this also exercises the clear check.
        press(0, 0);
        press(2, 2);
        press(4, 4);
        System.out.print("lightsout: on2=");    System.out.println(S[34]);
        System.out.print("lightsout: moves2="); System.out.println(S[25]);
        System.out.print("lightsout: solved="); System.out.println(S[26]);
    }

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

        S[30] = ui_scr_get_language();
        S[35] = 0;
        if (ui_arg_get_count() > 1) { S[35] = 8; }

        // 开窗:尺寸传 0 ⇒ 交给宿主给真实可用区(开窗之前问到的只是估算值)
        // Opening: pass 0 ⇒ the host supplies the real available area (a pre-open read is only an estimate)
        ui_win_open_ex(S[30] == 0 ? "关灯" : "Lights Out", 0, 0, 0, 0);
        ui_scr_set_keep_on(1);

        S[28] = ui_scr_get_w();
        S[29] = ui_scr_get_h();
        if (S[28] <= 0) { S[28] = 411; }
        if (S[29] <= 0) { S[29] = 726; }
        layout();

        if (S[35] > 0) {
            demoCheck();
        } else {
            newBoard(DEMO_TAPS);
        }
        draw();

        tid = ui_timer_set(250, 0);

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

            if (t == MSG_TIMER) {
                S[27] = S[27] + 1;
                draw();
                if (S[35] > 0 && S[27] >= S[35]) { break; }
                continue;
            }

            if (t == MSG_RESIZE || t == MSG_ORIENT) {
                S[28] = ui_scr_get_w();
                S[29] = ui_scr_get_h();
                if (S[28] <= 0) { S[28] = 411; }
                if (S[29] <= 0) { S[29] = 726; }
                layout();
                draw();
                continue;
            }

            if (t == MSG_KEYDOWN) {
                k = ui_msg_get_a();
                if (k == KEY_ESC) { break; }
                if (k == KEY_R || k == KEY_ENTER) {
                    newBoard(DEMO_TAPS);
                    ui_audio_beep(523, 60);
                    draw();
                    continue;
                }
                int moved = 0;
                if (k == KEY_LEFT)  { if (S[37] > 0) { S[37] = S[37] - 1; moved = 1; } }
                if (k == KEY_RIGHT) { if (S[37] < N - 1) { S[37] = S[37] + 1; moved = 1; } }
                if (k == KEY_UP)    { if (S[36] > 0) { S[36] = S[36] - 1; moved = 1; } }
                if (k == KEY_DOWN)  { if (S[36] < N - 1) { S[36] = S[36] + 1; moved = 1; } }
                if (k == KEY_SPACE) {
                    if (S[26] != 0) { newBoard(DEMO_TAPS); } else { press(S[36], S[37]); }
                    moved = 1;
                }
                if (moved == 1) { draw(); }
                continue;
            }

            if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN) {
                int x = ui_msg_get_a();
                int y = ui_msg_get_b();
                if (S[26] != 0) {
                    newBoard(DEMO_TAPS);
                    ui_audio_beep(523, 60);
                } else if (inButton(x, y) != 0) {
                    newBoard(DEMO_TAPS);
                    ui_audio_beep(523, 60);
                } else {
                    int cell = cellAt(x, y);
                    if (cell >= 0) {
                        press(cell / N, cell % N);
                        S[36] = cell / N;
                        S[37] = cell % N;
                    }
                }
                draw();
                continue;
            }
        }

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

        // 给无头验证留确定性判据
        // Deterministic checkpoints for headless verification
        System.out.print("lightsout: on2=");    System.out.println(S[34]);
        System.out.print("lightsout: moves2="); System.out.println(S[25]);
        System.out.print("lightsout: solved="); System.out.println(S[26]);
        System.out.print("lightsout: frames="); System.out.println(S[27]);
        System.out.println("lightsout: done");
    }
}