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

csharp/app/memory.cs · 12673 字节 · 下载原文

▶ 在浏览器里试玩

// 记忆翻牌 —— 用 **C#** 写的手机小游戏
// Memory matching — a small phone game written in **C#**
//
// 玩法(与 `Examples/c/app/memory.c` / `Examples/python/app/memory.py` 同一套):
// Gameplay (same rules as the C / Python versions):
//   · 4×4 共 8 对;点一张翻开,再点第二张;
//   · 4x4, eight pairs; tap one card to flip it, then tap a second;
//   · 一样就留在明面,不一样 **0.4 秒**后扣回去;全部配对完成即通关;
//   · an equal pair stays revealed, a different pair flips back after **0.4 s**; clear all pairs to win;
//   · 通关后点屏幕(或按 ESC / R)重开。
//   · after a win, tap the screen (or press ESC / R) for a new game.
//
// ## 这一份演示「延时动作」怎么写
// ## This sample shows **how to write a delayed action**
//
// 翻错的两张不能立刻扣回去(玩家会看不到第二张是什么),所以记一个**倒计时拍数**,
// 主循环每拍减一,减到 0 才扣 —— 不另起线程、不睡眠。
// A wrong pair must not flip back immediately (the player would never see the second card), so we
// keep a countdown in **ticks** and decrement it each frame -- no extra thread, no sleep.
//
// ## C# 这一路的写法约束(见 `Examples/csharp/app/snake.cs` 文件头)
// ## Style constraints on this C# path (see the header of `Examples/csharp/app/snake.cs`)
//
//   · 常量写**数字**(C# 前端没有 include C 头的机制,源是 `Lib/c/vml_ui.h`);
//   · constants are **numbers** (the C# frontend cannot include C headers; the source is `Lib/c/vml_ui.h`);
//   · 颜色写**负数十进制**;
//   · colours are **negative decimals**;
//   · 数字转字符串走本文件的 `numToStr()` / `digit()`(不借 C 的运行库);
//   · numbers to strings go through `numToStr()` / `digit()` here (not C's runtime library);
//   · 循环更新写 `i = i + 1`。
//   · loop updates are written `i = i + 1`.
//
// 跑法 —— 手机:`vml run examples/csharp/memory.cs`
// How to run — on the phone: `vml run examples/csharp/memory.cs`
// 跑法 —— 桌面:`vmlcli Examples/csharp/memory.cs --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/csharp/memory.cs --screen 480x640 --frames /tmp/fr`

// 显式引用 UI 库:`ui_*` 的声明在 `Lib/csharp/VmlUi.cs`(tools/GenLib 生成,别手改)。
// Explicit reference to the UI library: `ui_*` is declared in `Lib/csharp/VmlUi.cs` (generated by tools/GenLib; don't hand-edit).
using Vml.Ui;

class MemoryGame
{
    // ── 常量(源:Lib/c/vml_ui.h)──
    // ── Constants (source: Lib/c/vml_ui.h) ──
    const int MSG_KEYDOWN = 1;
    const int MSG_MOUSEDOWN = 4;
    const int MSG_TOUCHDOWN = 6;
    const int MSG_TIMER = 9;
    const int MSG_WINDOWCLOSE = 10;
    const int MSG_WINDOWRESIZE = 11;

    const int KEY_ESCAPE = 27;
    const int KEY_R = 82;

    const int ANCHOR_LEFT = 0;
    const int ANCHOR_CENTER = 1;

    const int MAX_FRAMES = 8000;
    const int N = 4;
    const int CELLS = 16;            // N * N
    const int HIDE_TICKS = 8;        // 8 拍 × 50ms ≈ 0.4 秒

    const int C_BG = -15724520;      // 0xFF101018
    const int C_BACK = -14013898;    // 0xFF2A2A36
    const int C_MATCHED = -15329762; // 0xFF16161E
    const int C_TEXT = -1513232;     // 0xFFE8E8F0
    const int C_DIM = -6643536;      // 0xFF9AA0B0
    const int C_FACE = -15724520;    // 0xFF101018

    const int P0 = -2069424;         // 0xFFE06C50
    const int P1 = -2509750;         // 0xFFD9B44A
    const int P2 = -11409298;        // 0xFF51E86E
    const int P3 = -11890471;        // 0xFF4A90D9
    const int P4 = -6591248;         // 0xFF9B6CF0
    const int P5 = -2069336;         // 0xFFE06CA8
    const int P6 = -11871802;        // 0xFF4AD9C6
    const int P7 = -4145088;         // 0xFFC0C040

    static int lang;
    static int sw = 360;
    static int sh = 620;
    static int cell = 80;
    static int ox = 20;
    static int oy = 110;

    static int[] pairOf = new int[CELLS];
    static int[] up = new int[CELLS];
    static int firstX = -1;
    static int firstY = -1;
    static int hide = 0;
    static int moves = 0;
    static int matched = 0;
    static int won = 0;
    static int seed = 20265;

    // 数字 → 字符串。**不能借标准库的字符串转换**:那是 C 的运行库,别的前端不一定有。
    // Number → string. **Cannot borrow the standard library's string conversion**: that is C's runtime library.
    static string numToStr(int v)
    {
        if (v == 0) return "0";
        string s = "";
        int neg = 0;
        if (v < 0) { neg = 1; v = 0 - v; }
        while (v > 0)
        {
            int d = v % 10;
            s = digit(d) + s;
            v = v / 10;
        }
        if (neg != 0) s = "-" + s;
        return s;
    }

    static string digit(int d)
    {
        if (d == 0) return "0";
        if (d == 1) return "1";
        if (d == 2) return "2";
        if (d == 3) return "3";
        if (d == 4) return "4";
        if (d == 5) return "5";
        if (d == 6) return "6";
        if (d == 7) return "7";
        if (d == 8) return "8";
        return "9";
    }

    // 确定性伪随机(验收要能复现同一局)
    // Deterministic PRNG (acceptance needs to reproduce the same run)
    static int rnd(int n)
    {
        seed = (seed * 1103 + 12345) % 32768;
        return (seed / 256) % n;
    }

    // 一对牌的颜色 —— 8 种固定色,按配对号取
    // The colour of a pair — eight fixed colours indexed by pair number
    static int pairColor(int p)
    {
        if (p == 0) return P0;
        if (p == 1) return P1;
        if (p == 2) return P2;
        if (p == 3) return P3;
        if (p == 4) return P4;
        if (p == 5) return P5;
        if (p == 6) return P6;
        return P7;
    }

    static void layout()
    {
        sw = ui_scr_get_w();
        sh = ui_scr_get_h();
        if (sw <= 0) sw = 360;
        if (sh <= 0) sh = 620;
        // 同 maze:边长取宽/高可用区中小的那个,方屏上不要按绝对阈值压扁。
        // Same as maze: take the smaller available dimension; don't squash square screens with an
        // absolute threshold.
        int topReserve = 60;     // 顶部步数 HUD
        int botReserve = 48;     // 网格下方提示行
        int maxW = sw - 20;
        int maxH = sh - topReserve - botReserve;
        int side = maxW < maxH ? maxW : maxH;
        cell = side / N;
        if (cell < 6) cell = 6;
        ox = (sw - N * cell) / 2;
        oy = 110;
        if (oy + N * cell > sh - botReserve)
            oy = topReserve + (maxH - N * cell) / 2;
        if (oy < topReserve) oy = topReserve;
    }

    // 开一局:先铺成 0,0,1,1,2,2…再 Fisher–Yates 洗牌(自带随机源,可复现)
    // New game: lay out 0,0,1,1,2,2... then Fisher-Yates shuffle (own RNG, reproducible)
    static void newGame()
    {
        int x = 0;
        while (x < N)
        {
            int y = 0;
            while (y < N)
            {
                pairOf[x * N + y] = (y * N + x) / 2;
                up[x * N + y] = 0;
                y = y + 1;
            }
            x = x + 1;
        }
        int i = CELLS - 1;
        while (i > 0)
        {
            int j = rnd(i + 1);
            int t = pairOf[i];
            pairOf[i] = pairOf[j];
            pairOf[j] = t;
            i = i - 1;
        }
        firstX = -1;
        firstY = -1;
        hide = 0;
        moves = 0;
        matched = 0;
        won = 0;
    }

    static void draw()
    {
        ui_2d_clear(C_BG);

        int x = 0;
        while (x < N)
        {
            int y = 0;
            while (y < N)
            {
                int px = ox + x * cell;
                int py = oy + y * cell;
                int p = pairOf[x * N + y];
                if (p < 0)
                {
                    // 已配对:淡淡地留个印子
                    // Matched: leave a faint imprint
                    ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, C_MATCHED, 1, 0, 6);
                }
                else if (up[x * N + y] == 1)
                {
                    ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, pairColor(p), 1, 0, 8);
                    // 牌面用数字(与 C/Python 版一致:随包字体缺花色字形会成豆腐块)
                    // The face is a number (same as the C/Python versions: glyphs like suits may be missing)
                    ui_2d_text(px + cell / 2, py + cell / 2 + cell / 8,
                        numToStr(p + 1), C_FACE, cell / 2, ANCHOR_CENTER);
                }
                else
                {
                    ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, C_BACK, 1, 0, 8);
                }
                y = y + 1;
            }
            x = x + 1;
        }

        ui_2d_text(10, 22, numToStr(moves), C_TEXT, 15, ANCHOR_LEFT);
        if (lang == 0) ui_2d_text(10, 42, "步数", C_DIM, 10, ANCHOR_LEFT);
        else ui_2d_text(10, 42, "moves", C_DIM, 10, ANCHOR_LEFT);

        if (won == 1)
        {
            if (lang == 0) ui_2d_text(sw / 2, oy + N * cell + 28, "全配好了!点一下再来", C_TEXT, 15, ANCHOR_CENTER);
            else ui_2d_text(sw / 2, oy + N * cell + 28, "All matched! Tap for a new one", C_TEXT, 15, ANCHOR_CENTER);
        }
        else
        {
            if (lang == 0) ui_2d_text(sw / 2, oy + N * cell + 28, "翻两张一样的", C_DIM, 12, ANCHOR_CENTER);
            else ui_2d_text(sw / 2, oy + N * cell + 28, "Flip two that match", C_DIM, 12, ANCHOR_CENTER);
        }

        ui_2d_present();
    }

    static void tap(int tx, int ty)
    {
        if (won == 1)
        {
            newGame();
            return;
        }
        int x = (tx - ox) / cell;
        int y = (ty - oy) / cell;
        if (x < 0 || y < 0 || x >= N || y >= N) return;
        int i = x * N + y;
        if (pairOf[i] < 0 || up[i] == 1 || hide > 0) return;

        up[i] = 1;
        if (firstX < 0)
        {
            firstX = x;
            firstY = y;
            return;
        }

        moves = moves + 1;
        int fi = firstX * N + firstY;
        if (pairOf[fi] == pairOf[i])
        {
            pairOf[fi] = -1;
            pairOf[i] = -1;
            matched = matched + 2;
            if (matched >= CELLS) won = 1;
            firstX = -1;
        }
        else
        {
            // 记个倒计时,主循环到点扣回
            // Countdown; the main loop flips them back at 0
            hide = HIDE_TICKS;
        }
    }

    static void Main()
    {
        lang = ui_scr_get_language();

        ui_win_open(lang == 0 ? "记忆翻牌" : "Memory", 0, 0);
        layout();
        ui_scr_set_keep_on(1);
        newGame();
        draw();

        int tid = ui_timer_set(50, 0);
        int frames = 0;
        int done = 0;
        while (done == 0 && ui_win_is_closed() == 0)
        {
            int t = ui_msg_fetch_wait(0);
            if (t == 0) continue;
            if (t == MSG_WINDOWCLOSE) break;

            if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN)
            {
                tap(ui_msg_get_a(), ui_msg_get_b());
                draw();
                continue;
            }

            if (t == MSG_KEYDOWN)
            {
                int k = ui_msg_get_a();
                if (k == KEY_ESCAPE || k == KEY_R) { newGame(); draw(); }
                continue;
            }

            if (t == MSG_WINDOWRESIZE) { layout(); draw(); continue; }

            if (t == MSG_TIMER)
            {
                frames = frames + 1;
                if (frames >= MAX_FRAMES) done = 1;
                if (hide > 0)
                {
                    hide = hide - 1;
                    if (hide == 0)
                    {
                        // 扣回所有翻开的牌
                        // Flip every face-up card back
                        int x = 0;
                        while (x < N)
                        {
                            int y = 0;
                            while (y < N)
                            {
                                up[x * N + y] = 0;
                                y = y + 1;
                            }
                            x = x + 1;
                        }
                        firstX = -1;
                    }
                }
                draw();
                continue;
            }
        }

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