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

kotlin/app/memory.kt · 10670 字节 · 下载原文

▶ 在浏览器里试玩

// 记忆翻牌 —— 用 **Kotlin** 写的手机小游戏
// Memory matching — a small phone game written in **Kotlin**
//
// 玩法(与 `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.
//
// ## 这一份用到的 Kotlin 特性
// ## Kotlin features used here
//
//   · `const val` 颜色常量与**顶层 `var` 数组**(`IntArray(16)`);
//   · `const val` colour constants and **file-level `var` arrays** (`IntArray(16)`);
//   · **字符串模板**(`"$gMoves"`)画计数;
//   · **string templates** (`"$gMoves"`) for counters;
//   · **多参数函数**(`fun tap(tx: Int, ty: Int)`);
//   · **multi-parameter functions** (`fun tap(tx: Int, ty: Int)`).
//
// 跑法 —— 手机:`vml run examples/kotlin/memory.kt`
// How to run — on the phone: `vml run examples/kotlin/memory.kt`
// 跑法 —— 桌面:`vmlcli Examples/kotlin/memory.kt --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/kotlin/memory.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 = 8000
const val N = 4
const val CELLS = N * N
const val HIDE_TICKS = 8     // 8 拍 × 50ms ≈ 0.4 秒 / 8 ticks x 50 ms ~= 0.4 s

const val C_BG = 0xFF101018
const val C_BACK = 0xFF2A2A36
const val C_MATCHED = 0xFF16161E
const val C_TEXT = 0xFFE8E8F0
const val C_DIM = 0xFF9AA0B0
const val C_FACE = 0xFF101018

const val P0 = 0xFFE06C50
const val P1 = 0xFFD9B44A
const val P2 = 0xFF51E86E
const val P3 = 0xFF4A90D9
const val P4 = 0xFF9B6CF0
const val P5 = 0xFFE06CA8
const val P6 = 0xFF4AD9C6
const val P7 = 0xFFC0C040

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

// `gPair[i]`:这张牌属于哪一对(0..7),-1 = 已配对
// `gPair[i]`: which pair this card belongs to (0..7), -1 = already matched
var gPair = IntArray(CELLS)
// `gUp[i]`:这张牌是否正翻开
// `gUp[i]`: is this card face up?
var gUp = IntArray(CELLS)
var gFirstX = -1
var gFirstY = -1
var gHide = 0
var gMoves = 0
var gMatched = 0
var gWon = 0
var gSeed = 20265
var gMaxPrims = 0

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

/// 一对牌的颜色 —— 8 种固定色,按配对号取
/// The colour of a pair — eight fixed colours indexed by pair number
fun pairColor(p: Int): Int {
    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
}

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 = 44
    if (SH < 420) {
        COMPACT = 1
        OY = 56
        bottom = 46
    }
    // 牌桌同时受宽、高(扣掉顶部步数行与底部提示)约束
    // The card table respects both width and height (minus the top move line and the bottom hint)
    var side = SW - 20
    var sideH = SH - OY - bottom
    if (sideH < side) { side = sideH }
    CELL = side / N
    if (CELL < 6) { CELL = 6 }
    OX = (SW - N * CELL) / 2
}

/// 开一局:先铺成 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)
fun newGame() {
    var x = 0
    while (x < N) {
        var y = 0
        while (y < N) {
            gPair[x * N + y] = (y * N + x) / 2
            gUp[x * N + y] = 0
            y = y + 1
        }
        x = x + 1
    }
    var i = CELLS - 1
    while (i > 0) {
        var j = rnd(i + 1)
        var t = gPair[i]
        gPair[i] = gPair[j]
        gPair[j] = t
        i = i - 1
    }
    gFirstX = -1
    gFirstY = -1
    gHide = 0
    gMoves = 0
    gMatched = 0
    gWon = 0
}

fun draw() {
    ui_2d_clear(C_BG)

    var x = 0
    while (x < N) {
        var y = 0
        while (y < N) {
            var px = OX + x * CELL
            var py = OY + y * CELL
            var p = gPair[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 (gUp[x * N + y] == 1) {
                ui_2d_rect(px + 3, py + 3, CELL - 6, CELL - 6, pairColor(p), 1, 0, 8)
                // 牌面用数字(与 Python/C 版一致:随包字体缺花色字形会成豆腐块)
                // The face is a number (same as the C/Python versions: glyphs like suits may be missing)
                var face = p + 1
                ui_2d_text(px + CELL / 2, py + CELL / 2 + CELL / 8,
                    "$face", 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, "$gMoves", 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) }

    // 矮屏把提示行贴紧牌桌、字号缩小
    // On short screens the hint hugs the table with a smaller font
    var hintDy = 28
    var hintFs = 12
    var wonFs = 15
    if (COMPACT == 1) { hintDy = 16; hintFs = 10; wonFs = 11 }
    if (gWon == 1) {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + N * CELL + hintDy, "全配好了!点一下再来", C_TEXT, wonFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + N * CELL + hintDy, "All matched! Tap for a new one", C_TEXT, wonFs, VML_ANCHOR_CENTER) }
    } else {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + N * CELL + hintDy, "翻两张一样的", C_DIM, hintFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + N * CELL + hintDy, "Flip two that match", C_DIM, hintFs, VML_ANCHOR_CENTER) }
    }

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

fun tap(tx: Int, ty: Int) {
    if (gWon == 1) {
        newGame()
        return
    }
    var x = (tx - OX) / CELL
    var y = (ty - OY) / CELL
    if (x < 0 || y < 0 || x >= N || y >= N) { return }
    var i = x * N + y
    if (gPair[i] < 0 || gUp[i] == 1 || gHide > 0) { return }

    gUp[i] = 1
    if (gFirstX < 0) {
        gFirstX = x
        gFirstY = y
        return
    }

    gMoves = gMoves + 1
    var fi = gFirstX * N + gFirstY
    if (gPair[fi] == gPair[i]) {
        gPair[fi] = -1
        gPair[i] = -1
        gMatched = gMatched + 2
        if (gMatched >= CELLS) { gWon = 1 }
        gFirstX = -1
    } else {
        // 记个倒计时,主循环到点扣回
        // Countdown; the main loop flips them back at 0
        gHide = HIDE_TICKS
    }
}

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("Memory", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    ui_scr_lock_orientation(VML_LOCK_PORTRAIT)
    relayout()
    newGame()
    draw()

    var tid = ui_timer_set(50, 1)
    var frames = 0
    var done = 0
    while (done == 0 && ui_win_is_closed() == 0) {
        var t = ui_msg_fetch_wait(50)
        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 || 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 (gHide > 0) {
                gHide = gHide - 1
                if (gHide == 0) {
                    // 扣回所有翻开的牌
                    // Flip every face-up card back
                    var x = 0
                    while (x < N) {
                        var y = 0
                        while (y < N) {
                            gUp[x * N + y] = 0
                            y = y + 1
                        }
                        x = x + 1
                    }
                    gFirstX = -1
                }
            }
            draw()
            continue
        }
    }

    ui_timer_kill(tid)
    ui_win_close()
}

main()