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

cpp/app/maze.cpp · 9959 字节 · 下载原文

▶ 在浏览器里试玩

// 迷宫 —— 用 **C++** 写的手机小游戏
// Maze — a small phone game written in **C++**
//
// 玩法(与 `Examples/c/app/maze.c` / `Examples/python/app/maze.py` 同一套):
// Gameplay (same rules as the C / Python versions):
//   · 每局**现生成**一张新迷宫(深度优先挖洞,一定连通、一定有路);
//   · every round **generates** a fresh maze (depth-first carving; always connected, always solvable);
//   · 方向键 / 点屏幕四边移动,走到右下角红格即通关;ESC / 通关后点一下换一张。
//   · arrow keys / tapping a screen edge move; reaching the bottom-right red cell wins;
//     ESC or a tap after winning gives a new maze.
//
// ## 生成用**显式栈**,不用递归
// ## Generation uses an **explicit stack**, not recursion
//
// 递归在这种规模上容易把固定额度的栈吃掉,症状是"跑到一半没了",很难查。
// Recursion at this size can eat the fixed stack budget and the symptom is "it just vanished
// halfway", which is hard to diagnose.
//
// ## 写法约束(同 `Examples/cpp/app/snake.cpp` 文件头)
// ## Style constraints (same as the header of `Examples/cpp/app/snake.cpp`)
//
//   · 颜色写**负数十进制**;数组维度只写**字面量宏**(`(MW * MH)` 这种表达式宏实测越界);
//   · colours are **negative decimals**; array dimensions use **literal macros only**
//     (an expression macro like `(MW * MH)` was measured to overrun);
//   · 整数转字符串走本文件的 `numstr()`;循环更新写 `i = i + 1`。
//   · integers to strings go through `numstr()`; loop updates are written `i = i + 1`.
//
// 跑法 —— 手机:`vml run examples/cpp/maze.cpp`
// How to run — on the phone: `vml run examples/cpp/maze.cpp`
// 跑法 —— 桌面:`vmlcli Examples/cpp/maze.cpp --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/cpp/maze.cpp --screen 480x640 --frames /tmp/fr`

#include <vml_ui.h>

#define MAX_FRAMES 12000
#define MW 21
#define MH 21
#define MAPCELLS 441               // MW * MH(数组维度只认字面量宏,不写表达式)
#define STACK_MAX 512

#define C_BG      -15724520        // 0xFF101018
#define C_WALL    -14013898        // 0xFF2A2A36
#define C_PATH    -15066588        // 0xFF1A1A24
#define C_PLAYER  -11409298        // 0xFF51E86E
#define C_GOAL     -2069424        // 0xFFE06C50
#define C_TEXT     -1513232        // 0xFFE8E8F0
#define C_DIM      -6643536        // 0xFF9AA0B0

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

static int cells[MAPCELLS];
static int stX[STACK_MAX];
static int stY[STACK_MAX];
static int dirs[4];
static int px = 1;
static int py = 1;
static int won = 0;
static int steps = 0;
static int seed = 20268;
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 maze)
int rnd(int n)
{
    seed = (seed * 1103 + 12345) % 32768;
    return (seed / 256) % n;
}

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 - 16;
    if (SW >= SH - 150) { side = SH - 170; }
    CELL = side / MW;
    if (CELL < 3) { CELL = 3; }
    OX = (SW - MW * CELL) / 2;
    OY = 110;
}

// 深度优先挖洞:从 (1,1) 出发,每次跳两格、挖通中间那格
// Depth-first carving from (1,1); each step jumps two cells and opens the one between
void generate()
{
    int x = 0;
    while (x < MW) {
        int y = 0;
        while (y < MH) {
            cells[x * MH + y] = 1;
            y = y + 1;
        }
        x = x + 1;
    }

    int top = 0;
    int x0 = 1;
    int y0 = 1;
    cells[x0 * MH + y0] = 0;
    stX[top] = x0;
    stY[top] = y0;
    top = top + 1;

    while (top > 0) {
        int cx = stX[top - 1];
        int cy = stY[top - 1];
        int n = 0;
        // 找出四个方向里"目标格还是墙"的那些(那种才没挖过)
        // Collect directions whose two-step target is still all wall (not carved yet)
        if (cx + 2 < MW - 1 && cells[(cx + 2) * MH + cy] == 1) {
            dirs[n] = 0;
            n = n + 1;
        }
        if (cx - 2 > 0 && cells[(cx - 2) * MH + cy] == 1) {
            dirs[n] = 1;
            n = n + 1;
        }
        if (cy + 2 < MH - 1 && cells[cx * MH + cy + 2] == 1) {
            dirs[n] = 2;
            n = n + 1;
        }
        if (cy - 2 > 0 && cells[cx * MH + cy - 2] == 1) {
            dirs[n] = 3;
            n = n + 1;
        }

        if (n == 0) {
            // 死路:回退 / dead end: backtrack
            top = top - 1;
            continue;
        }

        int k = dirs[rnd(n)];
        if (k == 0) {
            cells[(cx + 1) * MH + cy] = 0;
            cx = cx + 2;
        } else if (k == 1) {
            cells[(cx - 1) * MH + cy] = 0;
            cx = cx - 2;
        } else if (k == 2) {
            cells[cx * MH + cy + 1] = 0;
            cy = cy + 2;
        } else {
            cells[cx * MH + cy - 1] = 0;
            cy = cy - 2;
        }
        cells[cx * MH + cy] = 0;
        if (top < STACK_MAX) {
            stX[top] = cx;
            stY[top] = cy;
            top = top + 1;
        }
    }

    // 右下角出口强制打通(保证一定到得了)
    // Force the bottom-right exit open (must be reachable)
    int i = 0;
    while (i < 3) {
        if (MW - 2 - i >= 0) { cells[(MW - 2 - i) * MH + MH - 2] = 0; }
        if (MH - 2 - i >= 0) { cells[(MW - 2) * MH + MH - 2 - i] = 0; }
        i = i + 1;
    }
}

void newGame()
{
    generate();
    px = 1;
    py = 1;
    won = 0;
    steps = 0;
}

void draw()
{
    ui_2d_clear(C_BG);

    int x = 0;
    while (x < MW) {
        int y = 0;
        while (y < MH) {
            int c = C_PATH;
            if (cells[x * MH + y] == 1) { c = C_WALL; }
            ui_2d_rect(OX + x * CELL, OY + y * CELL, CELL, CELL, c, 1, 0, 0);
            y = y + 1;
        }
        x = x + 1;
    }

    ui_2d_rect(OX + (MW - 2) * CELL + 1, OY + (MH - 2) * CELL + 1,
        CELL - 2, CELL - 2, C_GOAL, 1, 0, 2);
    ui_2d_rect(OX + px * CELL + 1, OY + py * CELL + 1,
        CELL - 2, CELL - 2, C_PLAYER, 1, 0, CELL / 2);

    ui_2d_text(10, 24, numstr(steps), C_TEXT, 15, VML_ANCHOR_LEFT);
    if (LANG == 0) { ui_2d_text(10, 46, "步数", C_DIM, 10, VML_ANCHOR_LEFT); }
    else { ui_2d_text(10, 46, "steps", C_DIM, 10, VML_ANCHOR_LEFT); }

    if (won == 1) {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + MH * CELL + 28, "走出来了!点一下/ESC 换一张", C_TEXT, 15, VML_ANCHOR_CENTER); }
        else { ui_2d_text(SW / 2, OY + MH * CELL + 28, "Out! Tap / ESC for a new maze", C_TEXT, 15, VML_ANCHOR_CENTER); }
    } else {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + MH * CELL + 28, "方向键 / 点屏幕四边,走到红格", C_DIM, 11, VML_ANCHOR_CENTER); }
        else { ui_2d_text(SW / 2, OY + MH * CELL + 28, "Arrows / tap a screen edge; reach the red cell", C_DIM, 11, VML_ANCHOR_CENTER); }
    }

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

void move(int dx, int dy)
{
    if (won == 1) { return; }
    int nx = px + dx;
    int ny = py + dy;
    if (nx < 0 || ny < 0 || nx >= MW || ny >= MH) { return; }
    if (cells[nx * MH + ny] == 1) { return; }
    px = nx;
    py = ny;
    steps = steps + 1;
    if (px == MW - 2 && py == MH - 2) { won = 1; }
}

// 点屏幕四边:离哪边最近就往那边走
// A screen edge decides the direction (whichever side is nearest)
void tap(int tx, int ty)
{
    if (won == 1) {
        newGame();
        return;
    }
    int dl = tx;
    int dr = SW - tx;
    int dt = ty;
    int db = SH - ty;
    if (dl <= dr && dl <= dt && dl <= db) { move(-1, 0); }
    else if (dr <= dt && dr <= db) { move(1, 0); }
    else if (dt <= db) { move(0, -1); }
    else { move(0, 1); }
}

int main()
{
    LANG = ui_scr_get_language();

    relayout();
    if (LANG == 0) { ui_win_open("迷宫", 0, 0); }
    else { ui_win_open("Maze", 0, 0); }
    relayout();
    newGame();
    draw();

    int tid = ui_timer_set(120, 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) { newGame(); }
            else if (k == 37) { move(-1, 0); }
            else if (k == 39) { move(1, 0); }
            else if (k == 38) { move(0, -1); }
            else if (k == 40) { move(0, 1); }
            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; }
            continue;
        }
    }

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