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

java/app/memory.java · 14236 字节 · 下载原文

▶ 在浏览器里试玩

// 记忆翻牌 —— 用 **Java** 写的手机小游戏
// Memory matching — a small phone game written in **Java**
//
// 玩法:4×4 共 8 对;点一张翻开,再点一张;
// Gameplay: 4x4, eight pairs; tap to flip one card, tap another;
//       一样就留在明面,不一样 0.4 秒后扣回去;全部配对完成即通关。
//       an equal pair stays revealed, a different pair flips back after 0.4 s; clear all pairs to win.
//
// 与 `Examples/c/app/memory.c` / `Examples/python/app/memory.py` 同一套玩法与布局。
// Same rules and layout as `Examples/c/app/memory.c` / `Examples/python/app/memory.py`.
//
// ◆ 这个例程演示「延时动作」:翻错的两张不能立刻扣回去(玩家会看不到第二张是什么),
// ◆ This sample shows a **delayed action**: a wrong pair must not flip back immediately
// 所以记一个倒计时拍数(HIDE_TICKS),主循环每拍减一,减到 0 才扣 —— 不另起线程、不睡眠。
// (the player would never see the second card), so a countdown in ticks is decremented each frame.
//
// ◆ Java 前端三条实测约束(本文件按它们的写法来,不是风格)
// ◆ Three conventions forced by this Java front end (measured, not style)
//
//   ① `import vml.ui.*;` 带来全部 `ui_*` **函数**,但**不带常量** ⇒ 消息类型 / 键码 / 锚点
//   ① `import vml.ui.*;` brings in every `ui_*` **function** but **no constants** ⇒ message types,
//      在本文件里就地声明成 `static final int`。颜色十六进制字面量可用。
//      key codes and anchors are declared here as `static final int`. Hex colour literals work.
//
//   ② 状态一律放 `static int[] S`(Java 数组在堆上,读写可靠)。
//   ② All state lives in `static int[] S` (Java arrays are heap-backed; reads/writes are reliable).
//
//   ③ 随机数用 **16 位状态 LCG**:`seed = (seed*1103+12345) % 32768; rnd = (seed/256) % n;`
//   ③ Randomness uses a **16-bit-state LCG** — a 32-bit LCG overflows and degenerates.
//
//   ④ 屏幕坐标 → 格子时必须先判负再除:Java 的整数除法**向零截断**,
//   ④ Before dividing screen coordinates, test for negatives: Java integer division **truncates
//      `-10 / 80` 得 0 而不是 -1(Python 的 `//` 是向下取整),直接把棋盘外的点算进第一格。
//      toward zero**, so `-10 / 80` is 0 (not -1 as in Python's `//`) and an off-board tap would
//      land in the first cell.
//
//   ⑤ 自己的方法都带 `mem` 前缀 —— 与库函数同名会被链接器按名字劫持。
//   ⑤ Every method here carries the `mem` prefix — a name colliding with a library symbol gets
//      hijacked by the linker (same trap as `itoa` in the ledger's Java section).
//
// 跑法 / How to run:
//   手机 / phone:        vml run examples/java/app/memory.java
//   桌面 / desktop:      vmlcli Examples/java/app/memory.java --screen 411x726 --frames /tmp/fr

import vml.ui.*;

public class Memory {

    // ── 消息类型 / 键码(源: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 同值)──
    // ── Text anchors (same values as vml_ui.h) ──
    static final int ANCHOR_LEFT   = 0;
    static final int ANCHOR_CENTER = 1;

    // ── 配色:0xAARRGGBB ──
    // ── Palette: 0xAARRGGBB ──
    static final int C_BG   = 0xFF101018;
    static final int C_BACK = 0xFF2A2A36;
    static final int C_TEXT = 0xFFE8E8F0;
    static final int C_DIM  = 0xFF9AA0B0;
    static final int C_SLOT = 0xFF16161E;

    static final int N = 4;
    static final int PAIRS = 8;
    static final int HIDE_TICKS = 8;      // 8 拍 × 50ms ≈ 0.4 秒
    static final int MAX_FRAMES = 8000;
    static final int TIMER_MS = 50;

    /* 状态数组 S 的下标(全是本文件的私有约定)
       The S slot map (private to this file)
       0..15  每张牌属于哪一对:0..7;-1 = 已配好(下标 col*N+row)
       0..15  which pair a card belongs to: 0..7; -1 = already matched (index col*N+row)
       16..31 每张牌是否翻开中
       16..31 whether a card is face up
       32 第一张的列(-1 = 没有)   33 第一张的行
       32 the first card's column (-1 = none); 33 the first card's row
       34 扣回倒计时(拍)          35 步数
       34 flip-back countdown in ticks; 35 moves
       36 已配对张数              37 是否已通关
       36 matched cards; 37 solved?
       38 随机种子                39 屏宽
       38 RNG seed; 39 screen width
       40 屏高                    41 格边长
       40 screen height; 41 cell size
       42 棋盘左沿                43 棋盘上沿
       42 board left; 43 board top
       44 界面语言(0 中 1 英)     45 帧号
       44 UI language (0 Chinese, 1 English); 45 frame counter
       46 定时器 id               47 余量
       46 timer id; 47 slack */
    static int[] S = new int[48];

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

    // 16 位 LCG:状态永远 < 32768,乘法最大 32768*1103+12345 < 2^31,不会溢出。
    // 16-bit LCG: state stays < 32768, so state*1103+12345 < 2^31 and cannot overflow.
    static int memRnd(int n) {
        S[38] = (S[38] * 1103 + 12345) % 32768;
        return (S[38] / 256) % n;
    }

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

    // 8 对卡片各一个颜色。写成 if 链而不用数组字面量 —— 这个前端对字面量静态表不稳。
    // One colour per pair, as an if chain (static array literals are fragile on this front end).
    static int memPairColor(int p) {
        if (p == 0) { return 0xFFE06C50; }
        if (p == 1) { return 0xFFD9B44A; }
        if (p == 2) { return 0xFF51E86E; }
        if (p == 3) { return 0xFF4A90D9; }
        if (p == 4) { return 0xFF9B6CF0; }
        if (p == 5) { return 0xFFE06CA8; }
        if (p == 6) { return 0xFF4AD9C6; }
        return 0xFFC0C040;
    }

    // 交换 pair_of 里两张牌
    // Swap two cards in pair_of.
    static void memSwapPair(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;
    }

    // ── 排版:全部由屏宽屏高推出来 ──
    // ── Layout: everything derives from the screen size ──
    static void memRelayout() {
        int sw = ui_scr_get_w();
        int sh = ui_scr_get_h();
        if (sw <= 0) { sw = 360; }
        if (sh <= 0) { sh = 620; }
        S[39] = sw;
        S[40] = sh;
        // 矮屏压紧页眉/页脚,4×4 棋盘从 68px 放大到约 152px。
        // Tighten header/footer on short screens; the 4x4 board 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[41] = cell;
        S[42] = (sw - N * cell) / 2;
        S[43] = top + (avail - N * cell) / 2;
        if (S[43] < top) { S[43] = top; }
    }

    // ── 开局:先铺成 0,0,1,1,2,2… 再 Fisher–Yates 洗牌 ──
    // ── New game: lay out 0,0,1,1,2,2... then shuffle with Fisher-Yates ──
    static void memNewGame() {
        int x = 0;
        int y = 0;
        while (x < N) {
            y = 0;
            while (y < N) {
                S[x * N + y] = (y * N + x) / 2;
                S[16 + x * N + y] = 0;
                y = y + 1;
            }
            x = x + 1;
        }
        int i = N * N - 1;
        while (i > 0) {
            int j = memRnd(i + 1);
            memSwapPair(i / N, i % N, j / N, j % N);
            i = i - 1;
        }
        S[32] = -1;
        S[33] = -1;
        S[34] = 0;
        S[35] = 0;
        S[36] = 0;
        S[37] = 0;
    }

    // ── 绘制 ──
    // ── Drawing ──
    static void memDrawCard(int col, int row) {
        int px = S[42] + col * S[41];
        int py = S[43] + row * S[41];
        int cell = S[41];
        int i = col * N + row;
        int p = S[i];
        if (p < 0) {
            // 已配对:淡淡地留个印子
            // Matched: leave a faint imprint.
            ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, C_SLOT, 1, 0, 6);
            return;
        }
        if (S[16 + i] == 1) {
            ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, memPairColor(p), 1, 0, 8);
            // 用数字当牌面(字符串下标取字符在这个前端不可靠)
            // A number is the face (string subscripting is unreliable on this front end).
            ui_2d_text(px + cell / 2, py + cell / 2 + cell / 8,
                       "" + (p + 1), 0xFF101018, cell / 2, ANCHOR_CENTER);
        } else {
            ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, C_BACK, 1, 0, 8);
        }
    }

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

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

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

        int msgY = S[43] + N * S[41] + 28;
        if (msgY > S[40] - 10) { msgY = S[40] - 10; }
        if (S[37] == 1) {
            ui_2d_text(S[39] / 2, msgY, memTr("全配好了!点一下再来", "All matched! Tap for a new one"),
                       C_TEXT, 15, ANCHOR_CENTER);
        } else {
            ui_2d_text(S[39] / 2, msgY, memTr("翻两张一样的", "Flip two that match"),
                       C_DIM, 12, ANCHOR_CENTER);
        }
        ui_2d_present();
    }

    // 点屏幕:命中格子 → 翻牌逻辑
    // A screen tap: hit-test the grid, then run the flip logic.
    static void memTap(int tx, int ty) {
        if (S[37] == 1) {
            memNewGame();
            return;
        }
        // ⚠ 先判负再除:Java 的 / 向零截断(-10/80 == 0),棋盘外的点会被算进第一格。
        // ⚠ Test negatives before dividing: Java's / truncates toward zero, so an off-board tap
        //   would otherwise land in the first cell.
        int relX = tx - S[42];
        int relY = ty - S[43];
        if (relX < 0 || relY < 0) { return; }
        int x = relX / S[41];
        int y = relY / S[41];
        if (x >= N || y >= N) { return; }

        int i = x * N + y;
        if (S[i] < 0 || S[16 + i] == 1 || S[34] > 0) { return; }

        S[16 + i] = 1;
        if (S[32] < 0) {
            S[32] = x;
            S[33] = y;
            return;
        }

        S[35] = S[35] + 1;
        int fi = S[32] * N + S[33];
        if (S[fi] == S[i]) {
            S[fi] = -1;
            S[i] = -1;
            S[36] = S[36] + 2;
            if (S[36] >= N * N) { S[37] = 1; }
            S[32] = -1;
            S[33] = -1;
        } else {
            S[34] = HIDE_TICKS;      // 记个倒计时,主循环到点扣回 / countdown; flipped back at 0
        }
    }

    // 倒计时到 0:把所有翻开的牌扣回去
    // Countdown reached 0: flip every face-up card back.
    static void memHideAll() {
        int x = 0;
        int y = 0;
        while (x < N) {
            y = 0;
            while (y < N) {
                S[16 + x * N + y] = 0;
                y = y + 1;
            }
            x = x + 1;
        }
        S[32] = -1;
        S[33] = -1;
    }

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

        S[44] = ui_scr_get_language();
        S[38] = 20265;

        // 开窗:尺寸传 0 ⇒ 宿主给真实可用区
        // Opening: pass 0 ⇒ the host supplies the real available area.
        memRelayout();
        ui_win_open_ex(memTr("记忆翻牌", "Memory (java)"), 0, 0, 1, 0);
        ui_scr_set_keep_on(1);
        memRelayout();
        memNewGame();
        memDraw();

        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) {
                memTap(ui_msg_get_a(), ui_msg_get_b());
                memDraw();
                continue;
            }

            if (t == MSG_KEYDOWN) {
                // ESC 重开(本作不靠 ESC 退出,退出走窗口关闭)
                // ESC restarts (this game quits via the window, not ESC).
                if (ui_msg_get_a() == KEY_ESC) {
                    memNewGame();
                    memDraw();
                }
                continue;
            }

            if (t == MSG_RESIZE || t == MSG_ORIENT) {
                memRelayout();
                memDraw();
                continue;
            }

            if (t == MSG_TIMER) {
                S[45] = S[45] + 1;
                if (S[45] >= MAX_FRAMES) { break; }
                if (S[34] > 0) {
                    S[34] = S[34] - 1;
                    if (S[34] == 0) { memHideAll(); }
                }
                memDraw();
                continue;
            }
        }

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

        // 给无头验证留确定性判据
        // Deterministic checkpoints for headless verification.
        System.out.print("memory: moves=");  System.out.println(S[35]);
        System.out.print("memory: matched="); System.out.println(S[36]);
        System.out.print("memory: won=");    System.out.println(S[37]);
        System.out.println("memory: done");
    }
}