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

swift/app/memory.swift · 14203 字节 · 下载原文

▶ 在浏览器里试玩

// 记忆翻牌 —— 用 **Swift** 写的手机小游戏
// Memory matching — a small phone game written in **Swift**
//
// 玩法(与 `Examples/c/app/memory.c` / `Examples/python/app/memory.py` 同一套):
// Gameplay (same rules as `Examples/c/app/memory.c` / `Examples/python/app/memory.py`):
//   · 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**: a wrong pair must not flip back immediately
//   (the player has not seen the second card yet).
//   这里用**拍数倒计时**(8 拍 × 50 ms ≈ 0.4 s),主循环每拍减一,减到 0 才扣 —— 不起线程、不 sleep。
//   It keeps a **tick countdown** (8 ticks x 50 ms ~= 0.4 s); the main loop decrements it once per tick
//   and flips the cards back at 0 — no extra thread, no sleep.
//
// ◆ Swift 前端的实测约束(写这个文件时逐条撞过,结论都来自真实编译/运行)
// ◆ Measured constraints of the Swift frontend (hit while writing this file; all from real builds/runs)
//
//   ① **状态只能放数组**:模块级标量(`var n = 5`)读出来是垃圾;
//   ① **State lives in arrays only**: a module-level scalar (`var n = 5`) reads back as garbage.
//      而且**整个程序只允许一个全局数组** —— 开两个(`var A` + `var B`)会互相踩内存。
//      And a program may have **exactly one global array** — two (`var A` + `var B`) clobber each other.
//      ⇒ 全部状态塞进 `A`,按下标分区(见下面的表)。
//      ⇒ Everything is packed into `A`, partitioned by index (table below).
//   ② **常量写成 `main` 里的局部变量 / 无参函数**;模块级 `let` 同样不可靠。
//   ② **Constants are locals in `main` / zero-argument functions**; a module-level `let` is just as unreliable.
//   ③ **颜色写成负数十进制**(本前端对十六进制字面量不可靠):`0xFF101018` ⇒ `-15724520`。
//   ③ **Colors are negative decimals** (hex literals are unreliable here): `0xFF101018` => `-15724520`.
//   ④ **整数除法向零截断**(实测 `7/2=3`、`-7/2=-3`):屏幕坐标可能是负数,
//   ④ **Integer division truncates toward zero** (measured `7/2=3`, `-7/2=-3`); screen coordinates can be
//      所以「点在哪一格」必须**先用 `tx < ox` 挡掉左上方向**再除,不能靠负除法取整。
//      negative, so "which cell was tapped" must **reject `tx < ox` first** instead of relying on the rounding.
//   ⑤ **函数名避开 `add`/`min`/`max`/`abs`/`pow`/`sum`**:库里有同名裸标签,会静默顶掉用户版本
//   ⑤ **Avoid `add`/`min`/`max`/`abs`/`pow`/`sum`**: the linked libraries define bare labels with those
//      (实测 `add(3,4)` 得到 7)⇒ 本文件所有函数带 `mm` 前缀。
//      names and silently override yours (measured `add(3,4)` = 7) ⇒ every function here carries an `mm` prefix.
//   ⑥ **`ui_msg_fetch_wait(ms)` 的返回值就是那条消息**(0 = 超时)。不要再 `ui_msg_fetch` 一次 ——
//   ⑥ **`ui_msg_fetch_wait(ms)` returns the message itself** (0 = timeout). Do not fetch again — that
//      那会把定时器消息丢掉,倒计时永远不走。
//      would drop timer messages and the countdown would never advance.
//   ⑦ **触摸坐标取 `ui_msg_get_a()` / `ui_msg_get_b()`**(`ui_touch_get_x/y` 是 `ui_touch_fetch`
//   ⑦ **Touch coordinates come from `ui_msg_get_a()` / `ui_msg_get_b()`** (`ui_touch_get_x/y` are the cache
//      的缓存,不 fetch 时恒为 0)。
//      of `ui_touch_fetch`; they are always 0 unless you fetch).
//
// 数值的唯一真源仍是 `Lib/c/vml_ui.h`。
// The single source of truth for these numbers is still `Lib/c/vml_ui.h`.

#include <vml_ui.swift>
var A = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 状态表 —— **只用一个全局数组**(见文件头 ①),下标分区:
// State table — **one global array only** (see header ①), partitioned by index:
//   0..15   第 x*4+y 格是哪一对(0..7;-1 = 已配对 / matched)
//   0..15   which pair the cell at x*4+y holds (0..7; -1 = matched)
//   16..31  同一格是否翻开中(1 = 面朝上)
//   16..31  whether the same cell is face up (1 = face up)
//   32=first_x 33=first_y 34=hideCountdown 35=moves 36=matched 37=won 38=seed
//   39=cell 40=ox 41=oy 42=w 43=h 44=lang 45=timerId 46=frames 47=hides
//   47=hides 是「倒计时到点扣回」发生的次数 —— 只给无头验收读数用
//   47=hides is how many times the countdown flipped cards back — for headless verification only
//   48=最近一次点击换算出的格号(-1 = 没打中棋盘)—— 同为验收读数
//   48=the cell index of the most recent tap (-1 = missed the board) — verification only

func mmPairColor(p: Int) -> Int {
    if p == 0 { return -2069424 }    // 0xFFE06C50
    if p == 1 { return -2509750 }    // 0xFFD9B44A
    if p == 2 { return -11409298 }   // 0xFF51E86E
    if p == 3 { return -11890471 }   // 0xFF4A90D9
    if p == 4 { return -6591248 }    // 0xFF9B6CF0
    if p == 5 { return -2069336 }    // 0xFFE06CA8
    if p == 6 { return -11871802 }   // 0xFF4AD9C6
    return -4145088                  // 0xFFC0C040
}

// 16 位 LCG。**不要**照搬 C 的 32 位 LCG:这一支的整数会溢出,后半段恒为 0。
// 16-bit LCG. Do **not** copy C's 32-bit LCG: integers overflow here and the tail becomes all 0.
func mmRnd(n: Int) -> Int {
    A[38] = (A[38] * 1103 + 12345) % 32768
    return (A[38] / 256) % n
}

func mmLayout() {
    var w = ui_scr_get_w()
    var h = ui_scr_get_h()
    if w <= 0 { w = 360 }
    if h <= 0 { h = 620 }
    A[42] = w
    A[43] = h
    var side = 0
    if w < h - 140 { side = w - 20 } else { side = h - 170 }
    var cell = side / 4
    if cell < 6 { cell = 6 }
    A[39] = cell
    A[40] = (w - 4 * cell) / 2
    A[41] = 110
}

func mmHideAll() {
    var x = 0
    while x < 4 {
        var y = 0
        while y < 4 {
            A[16 + x * 4 + y] = 0
            y = y + 1
        }
        x = x + 1
    }
    A[32] = -1
    A[33] = -1
}

func mmNewGame() {
    // 先铺成 0,0,1,1,2,2… 再 Fisher–Yates 洗牌(自带随机源,不调宿主)
    // Lay out 0,0,1,1,2,2... then Fisher-Yates shuffle (our own RNG, no host call)
    var x = 0
    while x < 4 {
        var y = 0
        while y < 4 {
            A[x * 4 + y] = (y * 4 + x) / 2
            A[16 + x * 4 + y] = 0
            y = y + 1
        }
        x = x + 1
    }
    var i = 15
    while i > 0 {
        var j = mmRnd(i + 1)
        var ax = i / 4
        var ay = i % 4
        var bx = j / 4
        var by = j % 4
        var t = A[ax * 4 + ay]
        A[ax * 4 + ay] = A[bx * 4 + by]
        A[bx * 4 + by] = t
        i = i - 1
    }
    A[32] = -1
    A[33] = -1
    A[34] = 0
    A[35] = 0
    A[36] = 0
    A[37] = 0
    A[47] = 0
    A[48] = -1
}

func mmDraw() {
    ui_2d_clear(-15724520)   // 0xFF101018
    var cell = A[39]
    var ox = A[40]
    var oy = A[41]
    var x = 0
    while x < 4 {
        var y = 0
        while y < 4 {
            var px = ox + x * cell
            var py = oy + y * cell
            var i = x * 4 + y
            var p = A[i]
            if p < 0 {
                // 已配对:淡淡地留个印子
                // Matched: leave a faint imprint
                ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, -15329762, 1, 0, 6)
            } else if A[16 + i] == 1 {
                ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, mmPairColor(p), 1, 0, 8)
                ui_2d_text(px + cell / 2, py + cell / 2 + cell / 8, int_to_str(p + 1), -15724520, cell / 2, VML_ANCHOR_CENTER)
            } else {
                ui_2d_rect(px + 3, py + 3, cell - 6, cell - 6, -14013898, 1, 0, 8)   // 0xFF2A2A36
            }
            y = y + 1
        }
        x = x + 1
    }

    // HUD:步数(左上)
    // HUD: move count (top-left)
    ui_2d_text(10, 24, int_to_str(A[35]), -1513232, 18, VML_ANCHOR_LEFT)   // 0xFFE8E8F0
    if A[44] == 0 { ui_2d_text(10, 46, "步数", -6643536, 11, VML_ANCHOR_LEFT) }
    else { ui_2d_text(10, 46, "moves", -6643536, 11, VML_ANCHOR_LEFT) }

    // 底部提示
    // Bottom hint
    var msgY = A[41] + 4 * A[39] + 30
    if A[37] == 1 {
        if A[44] == 0 { ui_2d_text(A[42] / 2, msgY, "全配好了!点一下再来", -1513232, 15, VML_ANCHOR_CENTER) }
        else { ui_2d_text(A[42] / 2, msgY, "All matched! Tap for a new one", -1513232, 15, VML_ANCHOR_CENTER) }
    } else {
        if A[44] == 0 { ui_2d_text(A[42] / 2, msgY, "翻两张一样的", -6643536, 12, VML_ANCHOR_CENTER) }
        else { ui_2d_text(A[42] / 2, msgY, "Flip two that match", -6643536, 12, VML_ANCHOR_CENTER) }
    }
    ui_2d_present()
}

func mmTap(tx: Int, ty: Int) {
    A[48] = -1
    if A[37] == 1 { mmNewGame(); return }
    var cell = A[39]
    // ⚠ 先挡左上(负坐标再除会被向零截断成 0 格)—— 见文件头 ④
    // ⚠ Reject the top-left side first (negative coordinates truncate to cell 0) — see header ④
    if tx < A[40] || ty < A[41] { return }
    var x = (tx - A[40]) / cell
    var y = (ty - A[41]) / cell
    if x >= 4 || y >= 4 { return }
    var i = x * 4 + y
    A[48] = i
    if A[i] < 0 || A[16 + i] == 1 || A[34] > 0 { return }

    A[16 + i] = 1
    if A[32] < 0 {
        A[32] = x
        A[33] = y
        return
    }

    A[35] = A[35] + 1
    var fi = A[32] * 4 + A[33]
    if A[fi] == A[i] {
        A[fi] = -1
        A[i] = -1
        A[36] = A[36] + 2
        if A[36] >= 16 { A[37] = 1 }
        A[32] = -1
        A[33] = -1
    } else {
        // 记个倒计时,主循环到点扣回(8 拍 × 50 ms ≈ 0.4 s)
        // Countdown; the main loop flips back at 0 (8 ticks x 50 ms ~= 0.4 s)
        A[34] = 8
    }
}

func main() {
    var MSG_KEYDOWN = 1
    var MSG_MOUSEDOWN = 4
    var MSG_TOUCHDOWN = 6
    var MSG_TIMER = 9
    var MSG_CLOSE = 10
    var MSG_RESIZE = 11
    var KEY_ESCAPE = 27
    var KEY_ENTER = 13
    var KEY_R = 82

    // 界面语言只问一次(那是 syscall),存进状态表(模块级标量读出来是垃圾)
    // Ask for the UI language once (it is a syscall) and store it in the state table
    // (module-level scalars read back as garbage)
    A[44] = ui_scr_get_language()
    var lang = A[44]

    // 竖屏 + 不要屏幕手柄区;尺寸传 0 = 交给宿主给真实可用区
    // Portrait + no on-screen gamepad; size 0 = let the host supply the real available area
    ui_win_open_ex(lang == 0 ? "记忆翻牌" : "Memory", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD)

    // 开窗**之后**再问尺寸 —— 这时给的是实测画布
    // Re-read the size **after** opening — this is the measured canvas
    mmLayout()
    A[38] = 20265
    mmNewGame()
    ui_scr_set_keep_on(1)
    mmDraw()

    // 定时器 50 ms 一拍、**重复**(tag = 1)
    // Timer: 50 ms per tick, **repeating** (tag = 1)
    A[45] = ui_timer_set(50, 1)

    while ui_win_is_closed() == 0 {
        // ⚠ 返回值就是那条消息;再 fetch 一次会把定时器消息丢掉(见文件头 ⑥)
        // ⚠ The return value IS the message; fetching again would drop timer messages (header ⑥)
        var t = ui_msg_fetch_wait(50)
        if t == 0 { continue }

        if t == MSG_CLOSE { break }

        if t == MSG_TIMER {
            A[46] = A[46] + 1
            if A[34] > 0 {
                A[34] = A[34] - 1
                if A[34] == 0 {
                    mmHideAll()
                    A[47] = A[47] + 1
                }
            }
            mmDraw()
            continue
        }

        if t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN {
            // 坐标只从消息里取(见文件头 ⑦)
            // Coordinates come only from the message (header ⑦)
            mmTap(ui_msg_get_a(), ui_msg_get_b())
            mmDraw()
            continue
        }

        if t == MSG_RESIZE {
            mmLayout()
            mmDraw()
            continue
        }

        if t == MSG_KEYDOWN {
            var k = ui_msg_get_a()
            if k == KEY_ESCAPE || k == KEY_R || k == KEY_ENTER {
                mmNewGame()
                mmDraw()
            }
            continue
        }
    }

    ui_timer_kill(A[45])
    ui_scr_set_keep_on(0)
    ui_win_close()

    // 无头验收读数(一行一个数,避开 int_to_str 共用静态缓冲的坑)
    // Headless acceptance readouts (one number per line, avoiding int_to_str's shared static buffer)
    println("swmemory: moves=" + int_to_str(A[35]))
    println("swmemory: matched=" + int_to_str(A[36]))
    println("swmemory: hides=" + int_to_str(A[47]))
    println("swmemory: won=" + int_to_str(A[37]))
    println("swmemory: lastcell=" + int_to_str(A[48]))
    println("swmemory: frames=" + int_to_str(A[46]))
    println("swmemory: done")
}