swift/app/g2048.swift · 21620 字节 · 下载原文
// 2048 —— 用 **Swift** 写的手机小游戏
// 2048 — a small phone game written in **Swift**
//
// 玩法:手指**滑**(上下左右)或按方向键合并数字;两个相同的数撞在一起就翻倍。
// Gameplay: **swipe** (up/down/left/right) or press the arrow keys to merge numbers;
// 目标是拼出 2048(拼出来之后仍可继续玩)。R 重开,ESC 退出。
// two equal numbers that collide double. The goal is to reach 2048 (play continues after that).
// R restarts, ESC quits.
//
// ◆ 这个示例的重点:**滑动判定**与**合并算法**
// ◆ What this sample focuses on: **swipe detection** and **the merge algorithm**
//
// ① 滑动不靠 `TOUCHUP`:手指松开可以滑出屏幕、系统也可能吃掉 UP 消息 ⇒ 旗子会卡住。
// ① Swipes do not rely on `TOUCHUP`: a finger can leave the screen and the system may swallow the UP
// 这里是「按下记起点、移动超过阈值就判一次方向、然后把起点挪到当前位置」——
// message. Here we "remember the start on press, decide a direction once the move passes a threshold,
// 一次滑动只产生一次移动,与 UP 到不到无关。
// then move the start to the current point" — one move per swipe, regardless of UP.
//
// ② 合并只在**一条线内**做(压缩 + 每个格子最多参与一次合并),四行四列共用同一个
// ② Merging happens **inside one line** (compact, and each cell merges at most once). All rows and
// `moveLine`:方向只影响「这条线从哪头开始数」,用 `cellIndex` 一处换算。
// columns share the same `moveLine`; the direction only decides which end the line is read from,
// converted in one place, `cellIndex`.
//
// ◆ 这个前端的写法约定(实测)
// ◆ Conventions of this front end (measured)
//
// · 全局数组读写可靠(本文件只用**一个** `B` 装 16 格棋盘,状态量用少量全局标量)。
// · global arrays are reliable (this file uses **one** array `B` for the 16 cells, plus a few global scalars).
// · 字符串 `+` 可用(HUD 文案直接拼);`print/println` 的**字符串版本自带换行**,
// · string `+` works (HUD text is concatenated directly); the **string version of `print`/`println`
// 所以本文件一律用 `println` 打印,不依赖 `print` 不换行。
// appends a newline itself, so this file always uses `println` and never relies on `print`.
// · 函数名避开 `add`/`min`/`max`/`abs` 这类会被链接进来的库版本顶掉的名字。
// · function names avoid `add`/`min`/`max`/`abs`, which the linked library versions would take over.
//
// 数值的唯一真源仍是 `Lib/c/vml_ui.h`。
// The single source of truth for these numbers is still `Lib/c/vml_ui.h`.
//
// 跑法:手机 `vml run examples/swift/app/g2048.swift`;
// How to run: phone `vml run examples/swift/app/g2048.swift`;
// 桌面 `vmlcli Examples/swift/app/g2048.swift --screen 411x726 --frames /tmp/fr`
// desktop `vmlcli Examples/swift/app/g2048.swift --screen 411x726 --frames /tmp/fr`
// `--arg demo` 是无头验收模式:固定棋盘 + 三步已知移动 + 打印判据 + 自己退出。
// `--arg demo` is the headless acceptance mode: fixed board + three known moves + printed checkpoints + self-exit.
// ✅ 标准库 include **自动找**(2026-10-25 用户定):写 `#include <vml_ui.swift>` 即可,
// ✅ The standard-library include is **auto-found** (user rule, 2026-10-25): just write
// `#include <vml_ui.swift>` — `Lib/swift/` 与 `Lib/shared/` 由编译器自己找(手机上
// `#include <vml_ui.swift>`; the compiler searches `Lib/swift/` and `Lib/shared/` itself
// (示例不在 VML 树里也一样)。判据见 `scripts/vml-include-lib-probe`,教训见 E339。
// (so it also works on devices, where examples live outside the VML tree). See
// `scripts/vml-include-lib-probe` and lesson E339.
#include <vml_ui.swift>
// 16 格棋盘(0 = 空;其余是 2 的幂)
// The 16-cell board (0 = empty; everything else is a power of two)
var B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// ── 状态(全局标量)──
// ── State (global scalars) ──
var gScore = 0
var gBest = 0
var gWon = 0 // 1 = 已经拼出过 2048
// 1 = 2048 has been reached
var gOver = 0 // 1 = 无路可走
// 1 = no moves left
var gLang = 0
var gW = 0
var gH = 0
var gCell = 0 // 一格边长(px)
// cell side in px
var gBX = 0 // 棋盘左沿
// board left edge
var gBY = 0 // 棋盘上沿
// board top edge
var gDemo = 0
var gFrameLimit = 0
var gFrames = 0
var gTouchX = 0
var gTouchY = 0
var gTouching = 0
// ── 配色(0xAARRGGBB 的十进制负数)──
// ── Colors (decimal-negative 0xAARRGGBB) ──
func colBg() -> Int { return -15724520 } // 0xFF101018
func colPanel() -> Int { return -14472648 } // 0xFF232A38
func colEmpty() -> Int { return -15328476 } // 0xFF161B24
func colText() -> Int { return -1513232 } // 0xFFE8E8F0
func colMuted() -> Int { return -6643536 } // 0xFF9AA0B0
func colGold() -> Int { return -16320 } // 0xFFFFC040
func colGreen() -> Int { return -11409298 } // 0xFF51E86E
func colScrim() -> Int { return -872415232 } // 0xCC000000
func tileColor(v: Int) -> Int {
if v == 2 { return -12694434 } // 0xFF3E4C5E
if v == 4 { return -11900022 } // 0xFF4A6B8A
if v == 8 { return -11625760 } // 0xFF4E9AE0
if v == 16 { return -12681280 } // 0xFF3E7FC0
if v == 32 { return -7710000 } // 0xFF8A5AD0
if v == 64 { return -5219632 } // 0xFFB05AD0
if v == 128 { return -3113926 } // 0xFFD0703A
if v == 256 { return -2072496 } // 0xFFE06050
if v == 512 { return -2052032 } // 0xFFE0A040
if v == 1024 { return -16320 } // 0xFFFFC040
return -11409298 // 0xFF51E86E(2048 及以上)
}
func t(zh: String, en: String) -> String {
if gLang == 0 { return zh }
return en
}
func numToStr(v: Int) -> String {
if v == 0 { return "0" }
var s = ""
var n = v
while n > 0 {
var d = n % 10
if d == 0 { s = "0" + s }
else if d == 1 { s = "1" + s }
else if d == 2 { s = "2" + s }
else if d == 3 { s = "3" + s }
else if d == 4 { s = "4" + s }
else if d == 5 { s = "5" + s }
else if d == 6 { s = "6" + s }
else if d == 7 { s = "7" + s }
else if d == 8 { s = "8" + s }
else { s = "9" + s }
n = n / 10
}
return s
}
// ── 棋盘代数 ──
// ── Board algebra ──
// d:0=左 1=右 2=上 3=下;line:第几行/列;pos:沿这条线**从方向那头数**的第几格
// d: 0=left 1=right 2=up 3=down; line: which row/column; pos: how far along that line **from the direction's end**
func cellIndex(d: Int, line: Int, pos: Int) -> Int {
if d == 0 { return line * 4 + pos }
if d == 1 { return line * 4 + (3 - pos) }
if d == 2 { return pos * 4 + line }
return (3 - pos) * 4 + line
}
func cellGet(d: Int, line: Int, pos: Int) -> Int {
return B[cellIndex(d: d, line: line, pos: pos)]
}
func cellSet(d: Int, line: Int, pos: Int, v: Int) {
B[cellIndex(d: d, line: line, pos: pos)] = v
}
// 压缩 + 合并一条线;返回这一线的得分增量。
// Compact and merge one line; returns the score gained along it.
func moveLine(d: Int, line: Int) -> Int {
var gained = 0
var tgt = 0
var lastMerged = 0 - 1
var pos = 0
while pos < 4 {
var v = cellGet(d: d, line: line, pos: pos)
if v != 0 {
if tgt > 0 && lastMerged != tgt - 1 && cellGet(d: d, line: line, pos: tgt - 1) == v {
cellSet(d: d, line: line, pos: tgt - 1, v: v * 2)
cellSet(d: d, line: line, pos: pos, v: 0)
gained = gained + v * 2
lastMerged = tgt - 1
if v * 2 >= 2048 { gWon = 1 }
} else {
if tgt != pos {
cellSet(d: d, line: line, pos: tgt, v: v)
cellSet(d: d, line: line, pos: pos, v: 0)
}
tgt = tgt + 1
}
}
pos = pos + 1
}
while tgt < 4 {
cellSet(d: d, line: line, pos: tgt, v: 0)
tgt = tgt + 1
}
return gained
}
func moveBoard(d: Int) -> Int {
var gained = 0
var line = 0
while line < 4 {
gained = gained + moveLine(d: d, line: line)
line = line + 1
}
return gained
}
func emptyCount() -> Int {
var i = 0
var n = 0
while i < 16 {
if B[i] == 0 { n = n + 1 }
i = i + 1
}
return n
}
// 在随机空格里放一个 2(九成)或 4(一成)
// Put a 2 (nine times out of ten) or a 4 (one time) in a random empty cell
func spawn() {
var total = emptyCount()
if total <= 0 { return }
var pick = ui_math_rand(total)
var i = 0
var seen = 0
var slot = 0 - 1
while i < 16 {
if B[i] == 0 {
if seen == pick { slot = i }
seen = seen + 1
}
i = i + 1
}
if slot < 0 { return }
if ui_math_rand(10) == 0 { B[slot] = 4 } else { B[slot] = 2 }
}
func hasMoves() -> Int {
if emptyCount() > 0 { return 1 }
var r = 0
while r < 4 {
var c = 0
while c < 4 {
var v = B[r * 4 + c]
if c < 3 && B[r * 4 + c + 1] == v { return 1 }
if r < 3 && B[(r + 1) * 4 + c] == v { return 1 }
c = c + 1
}
r = r + 1
}
return 0
}
func maxTile() -> Int {
var i = 0
var m = 0
while i < 16 {
if B[i] > m { m = B[i] }
i = i + 1
}
return m
}
func clearBoard() {
var i = 0
while i < 16 { B[i] = 0; i = i + 1 }
gScore = 0
gWon = 0
gOver = 0
}
func newGame() {
clearBoard()
spawn()
spawn()
}
// 玩家走一步(含重新放新格与结束判定)
// One player move (includes spawning a new cell and the end-of-game check)
func playerMove(d: Int) {
if gOver != 0 { return }
var gained = moveBoard(d: d)
if gained > 0 {
gScore = gScore + gained
if gScore > gBest { gBest = gScore }
// demo 模式**不放新格** —— 判据要完全可复现
// demo mode **does not spawn** — the checkpoints must be fully reproducible
if gDemo == 0 { spawn() }
if hasMoves() == 0 { gOver = 1 }
}
}
// ── 排版 ──
// ── Layout ──
func layout() {
// 页面留白 / 头部 / 底部都由当前画布算:240x240 上棋盘缩到 128px 仍可点,1024 上放宽到 804px。
// Page padding / header / footer all come from the canvas: the board shrinks to 128px on 240x240
// (still tappable) and grows to 804px on 1024x1024.
var pad = gW / 40
if pad < 6 { pad = 6 }
if pad > 14 { pad = 14 }
var header = gH * 18 / 100
if header < 70 { header = 70 }
if header > 130 { header = 130 }
var footer = gH * 12 / 100
if footer < 42 { footer = 42 }
if footer > 90 { footer = 90 }
var availW = gW - pad * 2
var availH = gH - header - footer
gCell = availW / 4
if availH / 4 < gCell { gCell = availH / 4 }
if gCell < 12 { gCell = 12 }
gBX = (gW - gCell * 4) / 2
gBY = header + (availH - gCell * 4) / 2
if gBY < header { gBY = header }
}
// ── 绘制 ──
// ── Drawing ──
func drawTile(r: Int, c: Int, v: Int) {
var x = gBX + c * gCell
var y = gBY + r * gCell
var pad = 4
var sz = gCell - pad * 2
if v == 0 {
ui_2d_rect(x + pad, y + pad, sz, sz, colEmpty(), 1, 0, 10)
} else {
ui_2d_rect(x + pad, y + pad, sz, sz, tileColor(v: v), 1, 0, 10)
// 字号跟着格子边长走:240x240 上格子 32px,"1024" 用 7 号字也放得下
// Font size follows the cell: on 240x240 a cell is 32px and even "1024" fits at size 7
var size = gCell / 4
if size < 9 { size = 9 }
if v >= 100 {
size = gCell / 5
if size < 8 { size = 8 }
}
if v >= 1000 {
size = gCell / 6
if size < 7 { size = 7 }
}
ui_2d_text_v(x + gCell / 2, y + gCell / 2, numToStr(v: v), colText(), size, VML_ANCHOR_CENTER, VML_VANCHOR_MIDDLE, 1)
}
}
func draw() {
ui_2d_clear(colBg())
// 头部三段(标题 / 副标题 / 得分)按高度缩放并依次排开:240x240 上全部落在 70px 头部内
// Three header rows (title / subtitle / score) scale with the height and stack in order:
// on 240x240 all of them fit inside the 70px header.
var pad = gW / 40
if pad < 6 { pad = 6 }
if pad > 14 { pad = 14 }
var titleSize = gH / 26
if titleSize < 18 { titleSize = 18 }
if titleSize > 32 { titleSize = 32 }
var subSize = gH / 52
if subSize < 10 { subSize = 10 }
if subSize > 14 { subSize = 14 }
var scoreSize = gH / 45
if scoreSize < 12 { scoreSize = 12 }
if scoreSize > 17 { scoreSize = 17 }
// ⚠ ui_2d_text 的 y 是文字**底边**,所以每行都要先留出字高
// ⚠ ui_2d_text's y is the text **bottom**, so each row must add its font size
var titleY = pad + titleSize
var subY = titleY + 4 + subSize
var scoreY = subY + 4 + scoreSize
var side = gW / 6
ui_2d_text(gW / 2, titleY, "2048", colText(), titleSize, VML_ANCHOR_CENTER)
ui_2d_text(gW / 2, subY, t(zh: "滑动合并,拼出 2048", en: "Swipe to merge; reach 2048"), colMuted(), subSize, VML_ANCHOR_CENTER)
ui_2d_text(gW / 2 - side, scoreY, t(zh: "得分 ", en: "Score ") + numToStr(v: gScore), colGold(), scoreSize, VML_ANCHOR_CENTER)
ui_2d_text(gW / 2 + side, scoreY, t(zh: "最高 ", en: "Best ") + numToStr(v: gBest), colMuted(), scoreSize, VML_ANCHOR_CENTER)
ui_2d_rect(gBX - 6, gBY - 6, gCell * 4 + 12, gCell * 4 + 12, colPanel(), 1, 0, 16)
var r = 0
while r < 4 {
var c = 0
while c < 4 {
drawTile(r: r, c: c, v: B[r * 4 + c])
c = c + 1
}
r = r + 1
}
var footer = gH * 12 / 100
if footer < 42 { footer = 42 }
if footer > 90 { footer = 90 }
var hintSize = gH / 60
if hintSize < 9 { hintSize = 9 }
if hintSize > 12 { hintSize = 12 }
var hintY = gBY + gCell * 4 + footer / 3
if hintY > gH - 20 { hintY = gH - 20 }
ui_2d_text(gW / 2, hintY, t(zh: "方向键 / 滑动 · R 重开 · ESC 退出", en: "Arrows / swipe · R restarts · ESC quits"), colMuted(), hintSize, VML_ANCHOR_CENTER)
var winSize = gH / 45
if winSize < 12 { winSize = 12 }
if winSize > 15 { winSize = 15 }
if gWon != 0 && gOver == 0 {
var wy = hintY + hintSize + 6
if wy > gH - 12 { wy = gH - 12 }
ui_2d_text(gW / 2, wy, t(zh: "已达成 2048,可以继续!", en: "2048 reached — keep going!"), colGreen(), winSize, VML_ANCHOR_CENTER)
}
if gOver != 0 {
var ovSize = gH / 9
if ovSize < 18 { ovSize = 18 }
if ovSize > 26 { ovSize = 26 }
var scSize = gH / 13
if scSize < 14 { scSize = 14 }
if scSize > 20 { scSize = 20 }
var ovHint = gH / 18
if ovHint < 10 { ovHint = 10 }
if ovHint > 14 { ovHint = 14 }
ui_2d_rect(0, 0, gW, gH, colScrim(), 1, 0, 0)
ui_2d_text(gW / 2, gH / 2 - 24, t(zh: "无处可动了", en: "No moves left"), colText(), ovSize, VML_ANCHOR_CENTER)
ui_2d_text(gW / 2, gH / 2 + 14, t(zh: "得分 ", en: "Score ") + numToStr(v: gScore), colGold(), scSize, VML_ANCHOR_CENTER)
ui_2d_text(gW / 2, gH / 2 + 46, t(zh: "点任意处 / 回车再来一局", en: "Tap anywhere / Enter for a new game"), colMuted(), ovHint, VML_ANCHOR_CENTER)
}
ui_2d_present()
}
// ── 无头验收:固定棋盘 + 三步已知移动 ──
// ── Headless acceptance: a fixed board plus three known moves ──
func demoChecks() {
// 第 0 行 2 2 4 4 → 左移:4 8 0 0(得 12)
// Row 0 "2 2 4 4" moved left gives "4 8 0 0" (gaining 12)
// 第 1 行 4 4 8 8 → 8 16 0 0(得 24);第 2/3 行各得 4 ⇒ 首步共 44
// Row 1 "4 4 8 8" gives "8 16 0 0" (gaining 24); rows 2 and 3 gain 4 each => 44 in total
B[0] = 2; B[1] = 2; B[2] = 4; B[3] = 4
B[4] = 4; B[5] = 4; B[6] = 8; B[7] = 8
B[8] = 0; B[9] = 2; B[10] = 0; B[11] = 2
B[12] = 2; B[13] = 0; B[14] = 2; B[15] = 0
playerMove(d: 0)
println("sw2048: after-left=" + numToStr(v: gScore))
println("sw2048: row0=" + numToStr(v: B[0]) + "," + numToStr(v: B[1]) + "," + numToStr(v: B[2]) + "," + numToStr(v: B[3]))
println("sw2048: row1=" + numToStr(v: B[4]) + "," + numToStr(v: B[5]) + "," + numToStr(v: B[6]) + "," + numToStr(v: B[7]))
// 再左移一次:已经没有可合并的对 ⇒ 得分不变
// Another left move: no equal neighbours remain => the score does not change
playerMove(d: 0)
println("sw2048: after-left2=" + numToStr(v: gScore))
// 下移:第 0 列 4,8,4,4 → 自下而上 4,4,8,4 ⇒ 底 8、其上一格 8、再上一格 4(得 8)
// Down: column 0 "4,8,4,4" read bottom-up is "4,4,8,4" => 8 at the bottom, 8 above it, 4 above that (gaining 8)
playerMove(d: 3)
println("sw2048: after-down=" + numToStr(v: gScore))
println("sw2048: col0=" + numToStr(v: B[0]) + "," + numToStr(v: B[4]) + "," + numToStr(v: B[8]) + "," + numToStr(v: B[12]))
println("sw2048: sum=" + numToStr(v: maxTile()) + "/" + numToStr(v: hasMoves()))
}
func main() {
var KEY_ESCAPE = 27
var KEY_ENTER = 13
var KEY_LEFT = 37
var KEY_UP = 38
var KEY_RIGHT = 39
var KEY_DOWN = 40
var MSG_KEYDOWN = 1
var MSG_MOUSEDOWN = 4
var MSG_TOUCHDOWN = 6
var MSG_TOUCHMOVE = 7
var MSG_TOUCHUP = 8
var MSG_TIMER = 9
var MSG_CLOSE = 10
var MSG_RESIZE = 11
gLang = ui_scr_get_language()
if ui_arg_get_count() > 1 { gDemo = 1; gFrameLimit = 8 }
ui_win_open_ex("2048", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD)
// 开窗之后再问尺寸 —— 这时给的是实测画布
// Ask for the size after opening — that is the measured canvas
gW = ui_scr_get_w()
gH = ui_scr_get_h()
if gW <= 0 { gW = 411 }
if gH <= 0 { gH = 726 }
layout()
if gDemo != 0 {
clearBoard()
demoChecks()
} else {
newGame()
}
draw()
var tid = ui_timer_set(120, 0)
while ui_win_is_closed() == 0 {
var m = ui_msg_fetch_wait(120)
if m == MSG_CLOSE { break }
if m == MSG_TIMER {
gFrames = gFrames + 1
draw()
if gFrameLimit > 0 && gFrames >= gFrameLimit { break }
continue
}
if m == MSG_RESIZE {
gW = ui_scr_get_w()
gH = ui_scr_get_h()
if gW <= 0 { gW = 411 }
if gH <= 0 { gH = 726 }
layout()
draw()
continue
}
if m == MSG_KEYDOWN {
var k = ui_msg_get_a()
if k == KEY_ESCAPE { break }
if k == KEY_ENTER {
newGame()
draw()
} else if k == KEY_LEFT {
playerMove(d: 0)
draw()
} else if k == KEY_RIGHT {
playerMove(d: 1)
draw()
} else if k == KEY_UP {
playerMove(d: 2)
draw()
} else if k == KEY_DOWN {
playerMove(d: 3)
draw()
} else if k == 82 || k == 114 {
newGame()
draw()
}
continue
}
if m == MSG_TOUCHDOWN || m == MSG_MOUSEDOWN {
if gOver != 0 {
newGame()
draw()
} else {
gTouchX = ui_msg_get_a()
gTouchY = ui_msg_get_b()
gTouching = 1
}
continue
}
if m == MSG_TOUCHMOVE {
if gTouching != 0 && gOver == 0 {
var x = ui_msg_get_a()
var y = ui_msg_get_b()
var dx = x - gTouchX
var dy = y - gTouchY
var adx = dx
var ady = dy
if adx < 0 { adx = 0 - adx }
if ady < 0 { ady = 0 - ady }
if adx > 34 || ady > 34 {
if adx >= ady {
if dx > 0 { playerMove(d: 1) } else { playerMove(d: 0) }
} else {
if dy > 0 { playerMove(d: 3) } else { playerMove(d: 2) }
}
// 一次滑动只算一步:起点挪到当前位置
// one move per swipe: move the origin to the current point
gTouchX = x
gTouchY = y
draw()
}
}
continue
}
if m == MSG_TOUCHUP { gTouching = 0; continue }
}
ui_timer_kill(tid)
ui_scr_set_keep_on(0)
ui_win_close()
// 给无头验证留确定性判据
// Deterministic checkpoints for headless verification
println("sw2048: score=" + numToStr(v: gScore))
println("sw2048: max=" + numToStr(v: maxTile()))
println("sw2048: moves=" + numToStr(v: hasMoves()))
println("sw2048: frames=" + numToStr(v: gFrames))
println("sw2048: done")
}