swift/app/whack.swift · 11678 字节 · 下载原文
// 打地鼠 —— 用 **Swift** 写的手机小游戏
// Whack-a-mole — a small phone game written in **Swift**
//
// 玩法(与 `Examples/c/app/whack.c` / `Examples/python/app/whack.py` 同一套):
// Gameplay (same rules as `Examples/c/app/whack.c` / `Examples/python/app/whack.py`):
// · 3×3 九个洞,每隔 **6 拍**有一个洞冒出地鼠,一只活 **14 拍**(50 ms 一拍 ≈ 0.7 s);
// · nine holes in a 3x3; every **6 ticks** one hole pops a mole, and a mole lives **14 ticks** (~0.7 s at 50 ms);
// · 它缩回去之前点中 +1 分;超时没点中扣一条命;三条命用完结束;
// · tapping it before it ducks back scores +1; missing it costs a life; three lives ends the run;
// · 结束之后点屏幕(或按 ESC / R)重开。
// · after the run ends, tap the screen (or press ESC / R) for a new game.
//
// ◆ 这一类游戏的关键是「计时归谁管」:地鼠的存活时间记在**拍数**上(`mole_ticks`),不是 `time()`。
// ◆ The key thing in this genre is **who owns the clock**: a mole's lifetime is counted in **ticks**
// (`mole_ticks`),not `time()`. 拍数与真实时间的关系由 `ui_timer_set(50, 1)` 定死,
// `ui_timer_set(50, 1)` pins the tick-to-wall-clock relation, so "how many ticks a mole stays" is
// 所以「一只活多久」是可算的、不会随机器快慢漂移。
// computable and does not drift with the machine.
//
// ◆ Swift 前端的实测约束(写这个文件时逐条撞过,结论都来自真实编译/运行)
// ◆ Measured constraints of the Swift frontend (hit while writing this file; all from real builds/runs)
//
// ① **状态只能放数组**,而且**整个程序只允许一个全局数组**(多开会互相踩内存)⇒ 全塞进 `A`。
// ① **State lives in arrays only**, and a program may have **exactly one global array** (several
// clobber each other) ⇒ everything is packed into `A`.
// ② **常量写成 `main` 里的局部变量 / 无参函数**;模块级 `let` 不可靠。
// ② **Constants are locals in `main` / zero-argument functions**; module-level `let` is unreliable.
// ③ **颜色写成负数十进制**(十六进制字面量不可靠):`0xFFD9B44A` ⇒ `-2509750`。
// ③ **Colors are negative decimals** (hex literals are unreliable): `0xFFD9B44A` => `-2509750`.
// ④ **整数除法向零截断**(实测 `7/2=3`、`-7/2=-3`):点坐标先挡 `tx < ox` / `ty < oy` 再除。
// ④ **Integer division truncates toward zero** (measured `7/2=3`, `-7/2=-3`): reject `tx < ox` / `ty < oy` before dividing.
// ⑤ **函数名避开 `add`/`min`/`max`/`abs`/`pow`/`sum`**(库里的裸标签会静默顶掉)⇒ 全部带 `wk` 前缀。
// ⑤ **Avoid `add`/`min`/`max`/`abs`/`pow`/`sum`** (bare library labels silently override) ⇒ every function is `wk`-prefixed.
// ⑥ **`ui_msg_fetch_wait(ms)` 的返回值就是那条消息**(0 = 超时),不要再 fetch 一次。
// ⑥ **`ui_msg_fetch_wait(ms)` returns the message itself** (0 = timeout); do not fetch again.
// ⑦ **触摸坐标取 `ui_msg_get_a()` / `ui_msg_get_b()`**。
// ⑦ **Touch coordinates come from `ui_msg_get_a()` / `ui_msg_get_b()`**.
//
// 数值的唯一真源仍是 `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, 0]
// 状态表 —— **只用一个全局数组**(见文件头 ①),下标分区:
// State table — **one global array only** (see header ①), partitioned by index:
// 0=mole_at(-1 = 没有地鼠)1=mole_ticks 2=wait_ticks 3=score 4=lives 5=over
// 0=mole_at (-1 = no mole) 1=mole_ticks 2=wait_ticks 3=score 4=lives 5=over
// 6=hit_flash 7=seed 8=cell 9=ox 10=oy 11=w 12=h 13=lang 14=timerId 15=frames
// 16=lastidx 17=hits 是只给无头验收用的读数(最近点击的洞 / 点中次数)
// 16=lastidx 17=hits are headless-verification readouts (last tapped hole / number of hits)
func wkShowTicks() -> Int { return 14 }
// 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 wkRnd(n: Int) -> Int {
A[7] = (A[7] * 1103 + 12345) % 32768
return (A[7] / 256) % n
}
func wkLayout() {
var w = ui_scr_get_w()
var h = ui_scr_get_h()
if w <= 0 { w = 360 }
if h <= 0 { h = 620 }
A[11] = w
A[12] = h
var side = 0
if w < h - 150 { side = w - 24 } else { side = h - 180 }
var cell = side / 3
if cell < 8 { cell = 8 }
A[8] = cell
A[9] = (w - 3 * cell) / 2
A[10] = 130
}
func wkPickHole() {
A[0] = wkRnd(9)
A[1] = wkShowTicks()
}
func wkNewGame() {
A[3] = 0
A[4] = 3
A[5] = 0
A[6] = 0
A[0] = -1
A[2] = 6
A[16] = -1
A[17] = 0
}
func wkDraw() {
ui_2d_clear(-15724520) // 0xFF101018
var cell = A[8]
var ox = A[9]
var oy = A[10]
var i = 0
while i < 9 {
var cx = ox + (i % 3) * cell + cell / 2
var cy = oy + (i / 3) * cell + cell / 2
var r = cell / 3
ui_2d_ellipse(cx, cy + r / 3, r + cell / 12, r / 2 + cell / 20, -15066588, 1, 0) // 0xFF1A1A24
if i == A[0] {
var mc = -2509750 // 0xFFD9B44A
if A[6] == 1 { mc = -1 } // 0xFFFFFFFF:打中那一下闪白
ui_2d_circle(cx, cy, r, mc, 1, 0)
ui_2d_circle(cx - r / 3, cy - r / 4, r / 5, -15724520, 1, 0)
ui_2d_circle(cx + r / 3, cy - r / 4, r / 5, -15724520, 1, 0)
}
i = i + 1
}
// HUD:得分(左上)/ 命(右上)
// HUD: score (top-left) / lives (top-right)
ui_2d_text(10, 26, int_to_str(A[3]), -1513232, 20, VML_ANCHOR_LEFT) // 0xFFE8E8F0
if A[13] == 0 { ui_2d_text(10, 50, "得分", -6643536, 11, VML_ANCHOR_LEFT) }
else { ui_2d_text(10, 50, "score", -6643536, 11, VML_ANCHOR_LEFT) }
ui_2d_text(A[11] - 10, 26, int_to_str(A[4]), -2069424, 20, VML_ANCHOR_RIGHT) // 0xFFE06C50
if A[13] == 0 { ui_2d_text(A[11] - 10, 50, "命", -6643536, 11, VML_ANCHOR_RIGHT) }
else { ui_2d_text(A[11] - 10, 50, "lives", -6643536, 11, VML_ANCHOR_RIGHT) }
// 底部提示
// Bottom hint
var msgY = A[10] + 3 * A[8] + 30
if A[5] == 1 {
if A[13] == 0 { ui_2d_text(A[11] / 2, msgY, "结束,点一下再来", -1513232, 16, VML_ANCHOR_CENTER) }
else { ui_2d_text(A[11] / 2, msgY, "Over - tap to retry", -1513232, 16, VML_ANCHOR_CENTER) }
} else {
if A[13] == 0 { ui_2d_text(A[11] / 2, msgY, "冒头就点它", -6643536, 12, VML_ANCHOR_CENTER) }
else { ui_2d_text(A[11] / 2, msgY, "Tap the mole when it pops", -6643536, 12, VML_ANCHOR_CENTER) }
}
ui_2d_present()
}
func wkTap(tx: Int, ty: Int) {
A[16] = -1
if A[5] == 1 { wkNewGame(); return }
var cell = A[8]
// ⚠ 先挡左上(负坐标再除会被向零截断成 0 格)—— 见文件头 ④
// ⚠ Reject the top-left side first (negative coordinates truncate to cell 0) — see header ④
if tx < A[9] || ty < A[10] { return }
var x = (tx - A[9]) / cell
var y = (ty - A[10]) / cell
if x >= 3 || y >= 3 { return }
var idx = y * 3 + x
A[16] = idx
if idx == A[0] {
A[3] = A[3] + 1
A[17] = A[17] + 1
A[0] = -1
A[2] = 4 + wkRnd(4)
A[6] = 1
}
}
// 每拍一次:地鼠计时 / 下一个地鼠的等待计时
// Once per tick: the mole's countdown / the wait for the next mole
func wkTick() {
if A[5] != 0 { return }
A[6] = 0
if A[0] >= 0 {
A[1] = A[1] - 1
if A[1] <= 0 {
// 没点中:扣命 / missed: lose a life
A[0] = -1
A[4] = A[4] - 1
A[2] = 8
if A[4] <= 0 { A[5] = 1 }
}
} else {
A[2] = A[2] - 1
if A[2] <= 0 { wkPickHole() }
}
}
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 (a syscall) and store it in the state table
A[13] = ui_scr_get_language()
var lang = A[13]
// 竖屏 + 不要屏幕手柄区;尺寸传 0 = 交给宿主给真实可用区
// Portrait + no on-screen gamepad; size 0 = let the host supply the real available area
ui_win_open_ex(lang == 0 ? "打地鼠" : "Whack", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD)
// 开窗**之后**再问尺寸 —— 这时给的是实测画布
// Re-read the size **after** opening — this is the measured canvas
wkLayout()
A[7] = 20267
wkNewGame()
ui_scr_set_keep_on(1)
wkDraw()
// 定时器 50 ms 一拍、**重复**(tag = 1)—— 心跳,所有计时都按拍数走
// Timer: 50 ms per tick, **repeating** (tag = 1) — the heartbeat; every clock counts ticks
A[14] = 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[15] = A[15] + 1
wkTick()
wkDraw()
continue
}
if t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN {
// 坐标只从消息里取(见文件头 ⑦)
// Coordinates come only from the message (header ⑦)
wkTap(ui_msg_get_a(), ui_msg_get_b())
wkDraw()
continue
}
if t == MSG_RESIZE {
wkLayout()
wkDraw()
continue
}
if t == MSG_KEYDOWN {
var k = ui_msg_get_a()
if k == KEY_ESCAPE || k == KEY_R || k == KEY_ENTER {
wkNewGame()
wkDraw()
}
continue
}
}
ui_timer_kill(A[14])
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("swwhack: score=" + int_to_str(A[3]))
println("swwhack: lives=" + int_to_str(A[4]))
println("swwhack: over=" + int_to_str(A[5]))
println("swwhack: hits=" + int_to_str(A[17]))
println("swwhack: lastidx=" + int_to_str(A[16]))
println("swwhack: frames=" + int_to_str(A[15]))
println("swwhack: done")
}