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

cpp/app/memory.cpp · 10375 字节 · 下载原文

▶ 在浏览器里试玩

// 记忆翻牌 —— 用 **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/cpp/app/snake.cpp` 文件头)
// ## Style constraints on this C++ path (see the header of `Examples/cpp/app/snake.cpp`)
//
//   · 颜色写**负数十进制**(本前端词法器十进制专用,不认 `0x`);
//   · colours are **negative decimals** (the lexer is decimal-only and does not accept `0x`);
//   · 整数转字符串走本文件的 `numstr()`(不引 `<string>` / `sprintf`);
//   · integers to strings go through `numstr()` here (no `<string>` / `sprintf`);
//   · 循环更新写 `i = i + 1`。
//   · loop updates are written `i = i + 1`.
//
// 跑法 —— 手机:`vml run examples/cpp/memory.cpp`
// How to run — on the phone: `vml run examples/cpp/memory.cpp`
// 跑法 —— 桌面:`vmlcli Examples/cpp/memory.cpp --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/cpp/memory.cpp --screen 480x640 --frames /tmp/fr`

#include <vml_ui.h>

#define MAX_FRAMES 8000
#define N 4
#define CELLS 16                   // N * N(数组维度只认字面量宏,不写表达式)
#define HIDE_TICKS 8               // 8 拍 × 50ms ≈ 0.4 秒 / 8 ticks x 50 ms ~= 0.4 s

#define C_BG      -15724520        // 0xFF101018
#define C_BACK    -14013898        // 0xFF2A2A36
#define C_MATCHED -15329762        // 0xFF16161E
#define C_TEXT     -1513232        // 0xFFE8E8F0
#define C_DIM      -6643536        // 0xFF9AA0B0
#define C_FACE    -15724520        // 0xFF101018

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

static int LANG = 0;
static int SW = 360;
static int SH = 620;
static int CELL = 80;
static int OX = 20;
static int OY = 110;

// `pairOf[i]`:这张牌属于哪一对(0..7),-1 = 已配对
// `pairOf[i]`: which pair this card belongs to (0..7), -1 = already matched
static int pairOf[CELLS];
// `up[i]`:这张牌是否正翻开
// `up[i]`: is this card face up?
static int up[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;
static int maxPrims = 0;

// 整数 → 字符串(不引 std::string;`sprintf` 在各前端形态不一)
// Integer to string (no std::string; `sprintf` differs across front ends)
static char g_num[12];

char* numstr(int v)
{
    int n = 0;
    int m = 0;
    char tmp[12];
    if (v < 0) { g_num[0] = '-'; v = -v; n = 1; }
    if (v == 0) { g_num[n] = '0'; g_num[n + 1] = 0; return g_num; }
    while (v > 0) { tmp[m] = (char)('0' + v % 10); v = v / 10; m = m + 1; }
    while (m > 0) { m = m - 1; g_num[n] = tmp[m]; n = n + 1; }
    g_num[n] = 0;
    return g_num;
}

// 确定性伪随机(验收要能复现同一局)
// Deterministic PRNG (acceptance needs to reproduce the same run)
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
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;
}

void relayout()
{
    SW = ui_scr_get_w();
    SH = ui_scr_get_h();
    if (SW <= 0) { SW = 360; }
    if (SH <= 0) { SH = 620; }
    int side = SW - 20;
    if (SW >= SH - 140) { side = SH - 170; }
    CELL = side / N;
    if (CELL < 6) { CELL = 6; }
    OX = (SW - N * CELL) / 2;
    OY = 110;
}

// 开一局:先铺成 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)
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;
}

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,
                    numstr(p + 1), C_FACE, CELL / 2, VML_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, numstr(moves), C_TEXT, 15, VML_ANCHOR_LEFT);
    if (LANG == 0) { ui_2d_text(10, 42, "步数", C_DIM, 10, VML_ANCHOR_LEFT); }
    else { ui_2d_text(10, 42, "moves", C_DIM, 10, VML_ANCHOR_LEFT); }

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

    int n = ui_res_get_count(0);
    if (n > maxPrims) { maxPrims = n; }
    ui_2d_present();
}

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;
    }
}

int main()
{
    LANG = ui_scr_get_language();

    relayout();
    if (LANG == 0) { ui_win_open("记忆翻牌", 0, 0); }
    else { ui_win_open("Memory", 0, 0); }
    relayout();
    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 == 10) { break; }                  // MSG_WINDOWCLOSE

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

        if (t == 1) {                            // MSG_KEYDOWN
            int k = ui_msg_get_a();
            if (k == 27 || k == 82) { newGame(); draw(); }
            continue;
        }

        if (t == 11) { relayout(); draw(); continue; }   // MSG_WINDOWRESIZE
        if (t == 12) { continue; }                       // MSG_WINDOWORIENT

        if (t == 9) {                            // 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_win_close();
    return 0;
}