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

kotlin/app/maze.kt · 10593 字节 · 下载原文

▶ 在浏览器里试玩

// 迷宫 —— 用 **Kotlin** 写的手机小游戏
// Maze — a small phone game written in **Kotlin**
//
// 玩法(与 `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.
//
// 迷宫表示:`(2N+1) × (2M+1)` 的格子图,1 = 墙、0 = 通路;按 `cells[x * MH + y]` 平铺存。
// Representation: a `(2N+1) x (2M+1)` map, 1 = wall, 0 = passage, stored flat as `cells[x * MH + y]`.
//
// ## 这一份用到的 Kotlin 特性
// ## Kotlin features used here
//
//   · `IntArray(441)` 顶层数组 + 下标 `[i]`;
//   · `IntArray(441)` file-level arrays with `[i]` indexing;
//   · **多参数函数**(`fun move(dx: Int, dy: Int)`);
//   · **multi-parameter functions** (`fun move(dx: Int, dy: Int)`);
//   · **字符串模板**(`"$gSteps"`)画步数。
//   · **string templates** (`"$gSteps"`) for the step counter.
//
// 跑法 —— 手机:`vml run examples/kotlin/maze.kt`
// How to run — on the phone: `vml run examples/kotlin/maze.kt`
// 跑法 —— 桌面:`vmlcli Examples/kotlin/maze.kt --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/kotlin/maze.kt --screen 480x640 --frames /tmp/fr`

// ── 显式引用:下面用到的 `ui_*` 来自共享库 vmlui.vml ──────────────────
// ── Explicit reference: the `ui_*` used below come from the shared library vmlui.vml ──
// ⚠ `.*` 必须有:`import vmlui`(无 `.*`)会被 `ExtractImports` 的正则**静默忽略**。
// ⚠ The `.*` is required: `import vmlui` (without `.*`) is silently ignored.
// ⚠ 但整行删掉也照样编、照样跑 —— 前端靠 `ui_` 前缀**自动**链 `vmlui.vml`。
// ⚠ Deleting the line still compiles and runs — the frontend auto-links `vmlui.vml` from the `ui_` prefix.
#include <vml_ui.kt>
import vmlui.*

const val MAX_FRAMES = 12000
const val MW = 21
const val MH = 21
const val STACK_MAX = 512

const val C_BG = 0xFF101018
const val C_WALL = 0xFF2A2A36
const val C_PATH = 0xFF1A1A24
const val C_PLAYER = 0xFF51E86E
const val C_GOAL = 0xFFE06C50
const val C_TEXT = 0xFFE8E8F0
const val C_DIM = 0xFF9AA0B0

var LANG = 0
var SW = 360
var SH = 620
var CELL = 16
var OX = 0
var OY = 110
// 矮屏(240x240 一类)用压缩排版
// Compact layout flag for short screens (240x240 etc.)
var COMPACT = 0

var gCells = IntArray(MW * MH)
var gStX = IntArray(STACK_MAX)
var gStY = IntArray(STACK_MAX)
var gDirs = IntArray(4)
var gPx = 1
var gPy = 1
var gWon = 0
var gSteps = 0
var gSeed = 20268
var gMaxPrims = 0

/// 确定性伪随机(验收要能复现同一张迷宫)
/// Deterministic PRNG (acceptance needs to reproduce the same maze)
fun rnd(n: Int): Int {
    gSeed = (gSeed * 1103 + 12345) % 32768
    return (gSeed / 256) % n
}

fun relayout() {
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if (SW <= 0) { SW = 360 }
    if (SH <= 0) { SH = 620 }
    COMPACT = 0
    OY = 110
    var bottom = 40
    if (SH < 420) {
        COMPACT = 1
        OY = 56
        bottom = 46
    }
    // 迷宫同时受宽、高(扣掉顶部步数行与底部提示)约束
    // The maze respects both width and height (minus the top step line and the bottom hint)
    var side = SW - 16
    var sideH = SH - OY - bottom
    if (sideH < side) { side = sideH }
    CELL = side / MW
    if (CELL < 3) { CELL = 3 }
    OX = (SW - MW * CELL) / 2
}

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

    var top = 0
    var x0 = 1
    var y0 = 1
    gCells[x0 * MH + y0] = 0
    gStX[top] = x0
    gStY[top] = y0
    top = top + 1

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

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

        var k = gDirs[rnd(n)]
        if (k == 0) {
            gCells[(cx + 1) * MH + cy] = 0
            cx = cx + 2
        } else if (k == 1) {
            gCells[(cx - 1) * MH + cy] = 0
            cx = cx - 2
        } else if (k == 2) {
            gCells[cx * MH + cy + 1] = 0
            cy = cy + 2
        } else {
            gCells[cx * MH + cy - 1] = 0
            cy = cy - 2
        }
        gCells[cx * MH + cy] = 0
        if (top < STACK_MAX) {
            gStX[top] = cx
            gStY[top] = cy
            top = top + 1
        }
    }

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

fun newGame() {
    generate()
    gPx = 1
    gPy = 1
    gWon = 0
    gSteps = 0
}

fun draw() {
    ui_2d_clear(C_BG)

    var x = 0
    while (x < MW) {
        var y = 0
        while (y < MH) {
            var c = C_PATH
            if (gCells[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 + gPx * CELL + 1, OY + gPy * CELL + 1,
        CELL - 2, CELL - 2, C_PLAYER, 1, 0, CELL / 2)

    ui_2d_text(10, 24, "$gSteps", 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) }

    // 矮屏把提示行贴紧迷宫、字号缩小
    // On short screens the hint hugs the maze with a smaller font
    var hintDy = 28
    var hintFs = 11
    var wonFs = 15
    if (COMPACT == 1) { hintDy = 16; hintFs = 10; wonFs = 11 }
    if (gWon == 1) {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + MH * CELL + hintDy, "走出来了!点一下/ESC 换一张", C_TEXT, wonFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + MH * CELL + hintDy, "Out! Tap / ESC for a new maze", C_TEXT, wonFs, VML_ANCHOR_CENTER) }
    } else {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + MH * CELL + hintDy, "方向键 / 点屏幕四边,走到红格", C_DIM, hintFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + MH * CELL + hintDy, "Arrows / tap a screen edge; reach the red cell", C_DIM, hintFs, VML_ANCHOR_CENTER) }
    }

    var n = ui_res_get_count(0)
    if (n > gMaxPrims) { gMaxPrims = n }
    ui_2d_present()
}

fun move(dx: Int, dy: Int) {
    if (gWon == 1) { return }
    var nx = gPx + dx
    var ny = gPy + dy
    if (nx < 0 || ny < 0 || nx >= MW || ny >= MH) { return }
    if (gCells[nx * MH + ny] == 1) { return }
    gPx = nx
    gPy = ny
    gSteps = gSteps + 1
    if (gPx == MW - 2 && gPy == MH - 2) { gWon = 1 }
}

/// 点屏幕四边:离哪边最近就往那边走
/// A screen edge decides the direction (whichever side is nearest)
fun tap(tx: Int, ty: Int) {
    if (gWon == 1) {
        newGame()
        return
    }
    var dl = tx
    var dr = SW - tx
    var dt = ty
    var 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) }
}

fun main() {
    LANG = ui_scr_get_language()

    relayout()
    if (LANG == 0) { ui_win_open_ex("迷宫", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    else { ui_win_open_ex("Maze", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    ui_scr_lock_orientation(VML_LOCK_PORTRAIT)
    relayout()
    newGame()
    draw()

    var tid = ui_timer_set(120, 1)
    var frames = 0
    var done = 0
    while (done == 0 && ui_win_is_closed() == 0) {
        var t = ui_msg_fetch_wait(120)
        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
            var 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()
}

main()