
摘要 :本文基于 HarmonyOS NEXT / API 12 / Stage 模型,用纯 ArkUI 能力从零手写一个可直接在 DevEco 模拟器运行的 2048 游戏工程
Happy2048。全文按「设计 → 搭建 → 实现 → 踩坑 → 测试」推进:先拆解六大功能模块与三层架构,给出app.json5、module.json5、main_pages.json、EntryAbility.ets等逐字可抄的工程配置;再讲透GameBoard的四方向坐标归一与collapse合并算法、HighScoreStore的 Preferences 持久化、Index页面的状态整体替换与SwipeGesture角度归一;随后以「现象 / 原因 / 解法 / 代码」四段式还原五个真实踩坑(二维数组原地修改不刷新、[2,2,2,2]连锁合并、滑动方向上下颠倒、最高分退出即丢、首页读到空最高分);最后给出算法与持久化的测试用例表、体验优化与适用边界。适合想验证 ArkUI 基本功、又苦于「代码复制过去跑不起来」的开发者照着搭一遍。
目录
- [一、真实场景与痛点:2048 是个被低估的试金石](#一、真实场景与痛点:2048 是个被低估的试金石)
- 二、应用设计与技术选型
- [2.1 功能模块拆解](#2.1 功能模块拆解)
- [2.2 分层架构设计](#2.2 分层架构设计)
- [2.3 状态分层:@State / @Prop / @Observed 怎么选](#2.3 状态分层:@State / @Prop / @Observed 怎么选)
- [2.4 游戏状态流转设计](#2.4 游戏状态流转设计)
- 三、工程搭建:先有一份跑得起来的骨架
- [3.1 目录结构](#3.1 目录结构)
- [3.2 应用级配置 app.json5](#3.2 应用级配置 app.json5)
- [3.3 模块配置 module.json5](#3.3 模块配置 module.json5)
- [3.4 页面路由注册 main_pages.json](#3.4 页面路由注册 main_pages.json)
- [3.5 应用入口 EntryAbility.ets](#3.5 应用入口 EntryAbility.ets)
- 四、核心实现:分模块讲透
- [4.1 GameBoard:把四方向归一成一套算法](#4.1 GameBoard:把四方向归一成一套算法)
- [4.2 HighScoreStore:Preferences 持久化](#4.2 HighScoreStore:Preferences 持久化)
- [4.3 Index 页面:状态替换、手势与动画](#4.3 Index 页面:状态替换、手势与动画)
- 五、踩坑实录:五个坑,按现象/原因/解法/代码还原
- [坑 1:二维数组原地修改,UI 纹丝不动](#坑 1:二维数组原地修改,UI 纹丝不动)
- [坑 2:2,2,2,2 向左滑成了 8,0,0,0](#坑 2:[2,2,2,2] 向左滑成了 [8,0,0,0])
- [坑 3:滑动方向上下颠倒](#坑 3:滑动方向上下颠倒)
- [坑 4:最高分退出即丢](#坑 4:最高分退出即丢)
- [坑 5:首页读到空的最高分 / EntryAbility 编译报错](#坑 5:首页读到空的最高分 / EntryAbility 编译报错)
- 六、性能优化与测试
- 七、小结与适用边界
这半年我连着写了三十多篇 HarmonyOS 的文章,自我感觉产量不错,直到有一次在评论区被一位读者直白地怼了一句:"你这些代码我复制到一个空工程里,一行都跑不起来。"当时脸有点烫。回头翻自己写的东西,确实全是 create → process → destroy 这样的调用片段,缺 trio 配置文件、缺 Ability 入口、缺资源索引,根本不是一份能编译运行的工程。那句话点醒了我:技术文章的价值不在于你把 API 讲得多花,而在于读者能不能照着你的步骤,亲手把一个东西跑起来。
于是我给自己定了个规矩:后面每一篇实战,必须先有一份能在 DevEco 模拟器上直接运行的完整工程,文章里的每一段代码都必须逐字来自那个工程文件。这篇文章就是这条规矩下的第一个产物------用纯 ArkUI 能力,从零手写一个 2048 数字益智游戏。它不依赖任何硬件,不调用相机、蓝牙、定位,模拟器可直接跑;但麻雀虽小,ArkUI 里最让人头疼的几个点全齐了:二维数组的状态刷新、四方向手势识别、合并算法、分数动画、Preferences 持久化。我把从工程搭建到踩坑调试的全过程完整复盘一遍,代码全部来自真实工程 Happy2048,你可以照着搭一遍,跑通之后再改。
效果如下:

一、真实场景与痛点:2048 是个被低估的试金石
很多人觉得 2048 是"玩具项目",写个玩具而已,有什么好讲的。我一开始也是这么想的,直到真正动手,才发现它是检验 ArkUI 基本功的绝佳载体。先看几个真实的痛点。
第一个痛点:我的旧文章代码根本不能跑。 这不是修辞。过去我写状态管理,上来就是 @State count: number = 0 加一个按钮,读者照着写没问题;可一旦涉及"一个二维表格的数据变化后 UI 要跟着重绘",我就开始含糊其辞,贴一段伪代码糊弄过去。2048 恰好把这件事推到台前------16 个格子存在二维数组里,每次滑动都要更新它们。如果连这个都讲不清楚,那前面的文章确实是"水"。
第二个痛点:@State 对二维数组的刷新是无感的。 这是 ArkUI 声明式开发里最高频的坑。我早期写过这样的代码:拿到 @State grid: number[][],滑动后直接 this.grid[0][0] = 2,满心期待界面变,结果纹丝不动。原因是 @State 观察的是变量本身的引用,对数组内部元素的原地修改(push、splice、下标赋值)检测不到。这个坑我会在第五章用整整一节摊开讲,因为它太典型了。
第三个痛点:四方向合并算法,写成四份就是灾难。 2048 的核心规则是"每行每列压缩、相邻相同合并一次、补零、计分"。如果按直觉写,向上滑一套、向下滑一套、向左一套、向右一套,四份代码逻辑重复不说,还极易出错------其中最经典的错误是 [2,2,2,2] 向左滑,本应是 [4,4,0,0],却因为合并时没有正确跳过已经合并过的块,算成了 [8,0,0,0]。我第一版就栽在这。
第四个痛点:滑动手势到底用 SwipeGesture 还是 onTouch? 这个问题我在技术群里见人争论过很多次。有人坚持用 onTouch 自己记录按下和抬起坐标算位移,觉得"可控";其实对 2048 这种"一次滑动触发一次移动"的场景,SwipeGesture 加上距离和速度阈值才是正解,既省代码又能天然过滤误触。这里面还有个角度判断的方向问题,我也踩过。
第五个痛点:最高分要持久化,而 Preferences 的 flush 时机特殊。 用户玩出一局高分,退出 App 再进来,最高分还在不在,直接决定体验。Preferences 的 put 只改内存,必须 flush 才落盘------这个规则谁都背得出,真正写代码时却很容易在多个写入口里漏掉某一个。
这五个痛点叠在一起,让我意识到 2048 根本不是玩具。它是一个把"可运行工程规范、状态管理、算法、手势、持久化"五件事串成一条主线的完整练兵场。下面我按"设计 → 搭建 → 实现 → 踩坑 → 测试"的顺序,一件件讲透。
二、应用设计与技术选型
2.1 功能模块拆解
动手前我习惯先把"这东西到底要干什么"列清楚。Happy2048 拆成六个模块,后面所有代码都落在这六个模块里:
| 模块 | 职责 | 关键技术 | 是否有硬件依赖 |
|---|---|---|---|
| 棋盘渲染 | 4×4 格子、数字、经典配色 | @State 二维数组、ForEach |
无 |
| 滑动交互 | 四方向手势识别、角度归一 | SwipeGesture、GestureEvent |
无 |
| 合并算法 | 压缩→合并→补位→计分 | 坐标归一化、纯 TypeScript 逻辑 | 无 |
| 胜负判定 | 2048 达成、无可走步 | hasMoves 扫描、胜利锁存 |
无 |
| 分数系统 | 本次得分、飘字动画、最高分 | scale 动画、@State |
无 |
| 持久化 | 最高分落盘 | Preferences + flush |
无 |
可以看到,六个模块没有一个是碰硬件的,这就是为什么它能直接在模拟器上跑。对一个想验证 ArkUI 基本功的项目来说,这一点非常重要:你不用申请证书、不用连真机、不用配蓝牙权限,打开 DevEco 点运行就能看到效果。
2.2 分层架构设计
我把代码切成三层,UI 和逻辑彻底解耦。这是整个项目最值钱的决策,后面所有代码都落在这三层里:
渲染错误: Mermaid 渲染失败: Parse error on line 8: ...] G -->|整体替换引用| H@State grid 触发重绘 ----------------------^ Expecting 'AMP', 'COLON', 'DOWN', 'DEFAULT', 'NUM', 'COMMA', 'NODE_STRING', 'BRKT', 'MINUS', 'MULT', 'UNICODE_TEXT', got 'LINK_ID'
数据流是单向的:用户手势 → Index → GameBoard → MoveResult → @State 替换 → UI 重绘。GameBoard 是一个完全不认识 UI 的纯逻辑类,它既不导入 ArkUI 组件,也不碰 @State,只接收方向、返回新盘面。这样做的好处是:算法可以在单元测试里单独验证,UI 层出问题也不会污染逻辑。
2.3 状态分层:@State / @Prop / @Observed 怎么选
这是经常被问到的问题,我把它和 2048 的实际取舍放在一起讲。三者不是竞争关系,而是观察粒度的不同:
| 装饰器 | 观察粒度 | 典型场景 | 2048 里用不用 |
|---|---|---|---|
@State |
组件内自有状态,变量引用变化触发重绘 | 页面的 grid、score、弹窗标志 | 用,是页面状态的主力 |
@Prop |
父→子单向同步,父变则子更新 | TileCell 接收单个格子的值 | 用,每个格子只读 |
@Observed + @ObjectLink |
对象数组里单个对象的属性级深度观察 | 列表项是一个个可编辑对象 | 不用,见下方说明 |
很多人一看"二维数组",本能上想给格子套一个 @Observed class Tile,再用 @ObjectLink 观察每个格子。但在 2048 里这是过度设计:格子是 number 这样的值类型,不是对象;而且每次滑动盘面整体都变,没有"只改一个格子而其他不动"的需求。所以最简、最正确的做法是------grid 用 @State 持有,每次滑动整体替换数组引用,子组件 TileCell 用 @Prop 单向接收值。把 @Observed 留给"对象数组 + 单项编辑"的场景(比如通讯录里改某个联系人),别在 2048 里硬塞。理解"为什么不用",比记住"怎么用"更重要。
2.4 游戏状态流转设计
除了数据流,我还专门梳理了游戏本身的状态流转。2048 看着只有"玩"一种状态,实际上在交互过程中会在几个状态间切换,如果不提前理清楚,很容易出现"游戏结束了还能滑""胜利弹窗反复出现"这类问题。我把状态收敛成下面这张图:
#mermaid-svg-NcaOLsB7tC47W11r{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-NcaOLsB7tC47W11r .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-NcaOLsB7tC47W11r .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-NcaOLsB7tC47W11r .error-icon{fill:#552222;}#mermaid-svg-NcaOLsB7tC47W11r .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-NcaOLsB7tC47W11r .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-NcaOLsB7tC47W11r .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-NcaOLsB7tC47W11r .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-NcaOLsB7tC47W11r .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-NcaOLsB7tC47W11r .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-NcaOLsB7tC47W11r .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-NcaOLsB7tC47W11r .marker{fill:#333333;stroke:#333333;}#mermaid-svg-NcaOLsB7tC47W11r .marker.cross{stroke:#333333;}#mermaid-svg-NcaOLsB7tC47W11r svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-NcaOLsB7tC47W11r p{margin:0;}#mermaid-svg-NcaOLsB7tC47W11r defs #statediagram-barbEnd{fill:#333333;stroke:#333333;}#mermaid-svg-NcaOLsB7tC47W11r g.stateGroup text{fill:#9370DB;stroke:none;font-size:10px;}#mermaid-svg-NcaOLsB7tC47W11r g.stateGroup text{fill:#333;stroke:none;font-size:10px;}#mermaid-svg-NcaOLsB7tC47W11r g.stateGroup .state-title{font-weight:bolder;fill:#131300;}#mermaid-svg-NcaOLsB7tC47W11r g.stateGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-NcaOLsB7tC47W11r g.stateGroup line{stroke:#333333;stroke-width:1;}#mermaid-svg-NcaOLsB7tC47W11r .transition{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-NcaOLsB7tC47W11r .stateGroup .composit{fill:white;border-bottom:1px;}#mermaid-svg-NcaOLsB7tC47W11r .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px;}#mermaid-svg-NcaOLsB7tC47W11r .state-note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-NcaOLsB7tC47W11r .state-note text{fill:black;stroke:none;font-size:10px;}#mermaid-svg-NcaOLsB7tC47W11r .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-NcaOLsB7tC47W11r .edgeLabel .label rect{fill:#ECECFF;opacity:0.5;}#mermaid-svg-NcaOLsB7tC47W11r .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-NcaOLsB7tC47W11r .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-NcaOLsB7tC47W11r .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-NcaOLsB7tC47W11r .edgeLabel .label text{fill:#333;}#mermaid-svg-NcaOLsB7tC47W11r .label div .edgeLabel{color:#333;}#mermaid-svg-NcaOLsB7tC47W11r .stateLabel text{fill:#131300;font-size:10px;font-weight:bold;}#mermaid-svg-NcaOLsB7tC47W11r .node circle.state-start{fill:#333333;stroke:#333333;}#mermaid-svg-NcaOLsB7tC47W11r .node .fork-join{fill:#333333;stroke:#333333;}#mermaid-svg-NcaOLsB7tC47W11r .node circle.state-end{fill:#9370DB;stroke:white;stroke-width:1.5;}#mermaid-svg-NcaOLsB7tC47W11r .end-state-inner{fill:white;stroke-width:1.5;}#mermaid-svg-NcaOLsB7tC47W11r .node rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-NcaOLsB7tC47W11r .node polygon{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-NcaOLsB7tC47W11r #statediagram-barbEnd{fill:#333333;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-NcaOLsB7tC47W11r .cluster-label,#mermaid-svg-NcaOLsB7tC47W11r .nodeLabel{color:#131300;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-cluster rect.outer{rx:5px;ry:5px;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-state .divider{stroke:#9370DB;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-state .title-state{rx:5px;ry:5px;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-cluster.statediagram-cluster .inner{fill:white;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-cluster.statediagram-cluster-alt .inner{fill:#f0f0f0;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-cluster .inner{rx:0;ry:0;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-state rect.basic{rx:5px;ry:5px;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#f0f0f0;}#mermaid-svg-NcaOLsB7tC47W11r .note-edge{stroke-dasharray:5;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-note text{fill:black;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram-note .nodeLabel{color:black;}#mermaid-svg-NcaOLsB7tC47W11r .statediagram .edgeLabel{color:red;}#mermaid-svg-NcaOLsB7tC47W11r #dependencyStart,#mermaid-svg-NcaOLsB7tC47W11r #dependencyEnd{fill:#333333;stroke:#333333;stroke-width:1;}#mermaid-svg-NcaOLsB7tC47W11r .statediagramTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-NcaOLsB7tC47W11r :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 无效滑动 忽略
首次合成2048
继续挑战
无可走步
重新开始
无可走步
可操作
胜利提示
游戏结束
这张图里有两个关键约束。其一,"无效滑动"不改变任何状态,直接回到可操作------对应 doMove 里 if (!res.moved) return 这一行。其二,胜利提示后玩家有两种选择:继续挑战回到可操作,或者如果已经无路可走则进入游戏结束;而 wonLatch 保证"胜利提示"这个状态在一局里最多进入一次。把状态画成图之后,我在写代码时对"什么情况下该弹窗、什么情况该禁止滑动"就一目了然,少了很多边界判断的纠结。
三、工程搭建:先有一份跑得起来的骨架
我这次学乖了,第一步不是写游戏逻辑,而是先把一份最小完备的可运行工程搭起来。下面这些配置逐字来自工程里的真实文件,你可以直接照抄。
开发界面如下:

3.1 目录结构
text
Happy2048/
├── AppScope/
│ ├── app.json5
│ └── resources/base/{element/string.json, media/app_icon.png}
├── entry/
│ ├── build-profile.json5
│ ├── hvigorfile.ts
│ ├── oh-package.json5
│ ├── obfuscation-rules.txt
│ └── src/main/
│ ├── module.json5
│ ├── ets/
│ │ ├── entryability/EntryAbility.ets
│ │ ├── pages/Index.ets
│ │ ├── model/GameBoard.ets
│ │ └── common/HighScoreStore.ets
│ └── resources/base/
│ ├── element/{string.json, color.json}
│ ├── media/startIcon.png
│ └── profile/main_pages.json
├── build-profile.json5
├── hvigorfile.ts
├── oh-package.json5
└── code-linter.json5
3.2 应用级配置 app.json5
json5
// AppScope/app.json5
{
"app": {
"bundleName": "com.example.happy2048",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name"
}
}
bundleName 必须全局唯一且用反域名写法,这是应用身份,写错了后面签名、安装都会出问题。图标和标签都用资源引用,对应的 png 和 string 必须真实存在。
3.3 模块配置 module.json5
json5
// entry/src/main/module.json5(节选)
{
"module": {
"name": "entry",
"type": "entry",
"mainElement": "EntryAbility",
"deviceTypes": ["phone", "tablet", "2in1"],
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"icon": "$media:app_icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{ "entities": ["entity.system.home"], "actions": ["ohos.want.action.home"] }
]
}
],
"requestPermissions": []
}
}
这里三个最容易漏的点:pages 必须指向 $profile:main_pages;startWindowIcon 对应的 startIcon.png 必须真实存在;本演示没用到任何硬件,所以 requestPermissions 是空数组------这也是它能在模拟器直接跑的前提。
3.4 页面路由注册 main_pages.json
json
// entry/src/main/resources/base/profile/main_pages.json
{
"src": [
"pages/Index"
]
}
这个文件是"跑不起来"的头号元凶。新增页面必须在这里登记,否则 router.pushUrl 会报 page not found。虽然 2048 只有一个页面,我依然把它写规范,养成习惯。
3.5 应用入口 EntryAbility.ets
typescript
// ets/entryability/EntryAbility.ets
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { HighScoreStore } from '../common/HighScoreStore';
const TAG: string = '[EntryAbility]';
const DOMAIN: number = 0xF000;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
hilog.info(DOMAIN, TAG, 'Ability onWindowStageCreate');
const store: HighScoreStore = HighScoreStore.getInstance();
store.init(this.context).then(() => {
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, TAG, 'loadContent failed: %{public}s', JSON.stringify(err));
return;
}
hilog.info(DOMAIN, TAG, 'loadContent success');
});
}).catch((e: Error) => {
hilog.error(DOMAIN, TAG, 'init prefs failed: %{public}s', e.message);
// 兜底:即使持久化初始化失败,也要保证页面能起来
windowStage.loadContent('pages/Index');
});
}
onBackground(): void {
// flush 是异步的,这里显式 catch,避免未处理的 Promise 拒绝
HighScoreStore.getInstance().flush().catch((e: Error) => {
hilog.error(DOMAIN, TAG, 'flush on background failed: %{public}s', e.message);
});
}
}
注意我把 Preferences 的初始化放在 onWindowStageCreate 里,并且用 .then() 等它完成后再 loadContent。原因在第五章的坑里详细说:this.context 在更早的生命周期里可能还没准备好,而首页一进来就要读最高分。
四、核心实现:分模块讲透
4.1 GameBoard:把四方向归一成一套算法
这是全项目的灵魂。我的思路不是给四个方向写四份代码,而是引入一个"归一化视角":把每个方向要处理的那条线,都按"滑动目标端在前"的顺序列出来。这样四个方向全都复用同一套 collapse。
先看坐标归一:
typescript
// ets/model/GameBoard.ets
// 四方向归一的核心:把每条"线"按滑动目标端在前的顺序列出。
// Left :第 i 行,列 0 → 3(目标端是左)
// Right:第 i 行,列 3 → 0(目标端是右)
// Up :第 i 列,行 0 → 3(目标端是上)
// Down :第 i 列,行 3 → 0(目标端是下)
private linesFor(dir: Direction): CellPos[][] {
const lines: CellPos[][] = [];
for (let i: number = 0; i < this.size; i++) {
const line: CellPos[] = [];
for (let k: number = 0; k < this.size; k++) {
let r: number = 0;
let c: number = 0;
if (dir === Direction.Left) {
r = i;
c = k;
} else if (dir === Direction.Right) {
r = i;
c = this.size - 1 - k;
} else if (dir === Direction.Up) {
r = k;
c = i;
} else {
r = this.size - 1 - k;
c = i;
}
line.push({ r: r, c: c });
}
lines.push(line);
}
return lines;
}
这段代码的意思是:无论往哪个方向滑,我都能得到 4 条线,每条线 4 个坐标,而且第一个坐标就是该方向的"终点方向"。对向左滑,(i,0) 是起点;对向右滑,(i,3) 是起点。后面的合并算法只认"顺序",不关心方向。
再看单条线的合并算法:
typescript
// ets/model/GameBoard.ets
// 单条线核心算法:压缩(去0) → 相邻合并(每块每步只并一次) → 补0到固定长度
private collapse(src: number[]): CollapseResult {
// 1. 压缩:把所有非零数按原顺序靠前
const nonZero: number[] = [];
for (let i: number = 0; i < src.length; i++) {
if (src[i] !== 0) {
nonZero.push(src[i]);
}
}
// 2. 合并:相邻相等才合并,合并后 i 跳 2,防止 [2,2,2,2] 一步并成 [8,0,0,0]
const out: number[] = [];
let gained: number = 0;
let i: number = 0;
while (i < nonZero.length) {
if (i + 1 < nonZero.length && nonZero[i] === nonZero[i + 1]) {
const merged: number = nonZero[i] * 2;
out.push(merged);
gained = gained + merged;
i = i + 2;
} else {
out.push(nonZero[i]);
i = i + 1;
}
}
// 3. 补位:尾部填 0,长度恒定
while (out.length < this.size) {
out.push(0);
}
// 4. 是否真的变了:用于判断这次滑动是否有效
let changed: boolean = false;
for (let k: number = 0; k < this.size; k++) {
if (out[k] !== src[k]) {
changed = true;
break;
}
}
const result: CollapseResult = {
values: out,
gained: gained,
changed: changed
};
return result;
}
整个流程用一张图表示:
#mermaid-svg-xXhUu59bULNo3p5j{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-xXhUu59bULNo3p5j .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-xXhUu59bULNo3p5j .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-xXhUu59bULNo3p5j .error-icon{fill:#552222;}#mermaid-svg-xXhUu59bULNo3p5j .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-xXhUu59bULNo3p5j .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-xXhUu59bULNo3p5j .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-xXhUu59bULNo3p5j .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-xXhUu59bULNo3p5j .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-xXhUu59bULNo3p5j .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-xXhUu59bULNo3p5j .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-xXhUu59bULNo3p5j .marker{fill:#333333;stroke:#333333;}#mermaid-svg-xXhUu59bULNo3p5j .marker.cross{stroke:#333333;}#mermaid-svg-xXhUu59bULNo3p5j svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-xXhUu59bULNo3p5j p{margin:0;}#mermaid-svg-xXhUu59bULNo3p5j .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-xXhUu59bULNo3p5j .cluster-label text{fill:#333;}#mermaid-svg-xXhUu59bULNo3p5j .cluster-label span{color:#333;}#mermaid-svg-xXhUu59bULNo3p5j .cluster-label span p{background-color:transparent;}#mermaid-svg-xXhUu59bULNo3p5j .label text,#mermaid-svg-xXhUu59bULNo3p5j span{fill:#333;color:#333;}#mermaid-svg-xXhUu59bULNo3p5j .node rect,#mermaid-svg-xXhUu59bULNo3p5j .node circle,#mermaid-svg-xXhUu59bULNo3p5j .node ellipse,#mermaid-svg-xXhUu59bULNo3p5j .node polygon,#mermaid-svg-xXhUu59bULNo3p5j .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-xXhUu59bULNo3p5j .rough-node .label text,#mermaid-svg-xXhUu59bULNo3p5j .node .label text,#mermaid-svg-xXhUu59bULNo3p5j .image-shape .label,#mermaid-svg-xXhUu59bULNo3p5j .icon-shape .label{text-anchor:middle;}#mermaid-svg-xXhUu59bULNo3p5j .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-xXhUu59bULNo3p5j .rough-node .label,#mermaid-svg-xXhUu59bULNo3p5j .node .label,#mermaid-svg-xXhUu59bULNo3p5j .image-shape .label,#mermaid-svg-xXhUu59bULNo3p5j .icon-shape .label{text-align:center;}#mermaid-svg-xXhUu59bULNo3p5j .node.clickable{cursor:pointer;}#mermaid-svg-xXhUu59bULNo3p5j .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-xXhUu59bULNo3p5j .arrowheadPath{fill:#333333;}#mermaid-svg-xXhUu59bULNo3p5j .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-xXhUu59bULNo3p5j .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-xXhUu59bULNo3p5j .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xXhUu59bULNo3p5j .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-xXhUu59bULNo3p5j .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xXhUu59bULNo3p5j .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-xXhUu59bULNo3p5j .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-xXhUu59bULNo3p5j .cluster text{fill:#333;}#mermaid-svg-xXhUu59bULNo3p5j .cluster span{color:#333;}#mermaid-svg-xXhUu59bULNo3p5j div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-xXhUu59bULNo3p5j .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-xXhUu59bULNo3p5j rect.text{fill:none;stroke-width:0;}#mermaid-svg-xXhUu59bULNo3p5j .icon-shape,#mermaid-svg-xXhUu59bULNo3p5j .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xXhUu59bULNo3p5j .icon-shape p,#mermaid-svg-xXhUu59bULNo3p5j .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-xXhUu59bULNo3p5j .icon-shape .label rect,#mermaid-svg-xXhUu59bULNo3p5j .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xXhUu59bULNo3p5j .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-xXhUu59bULNo3p5j .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-xXhUu59bULNo3p5j :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
遍历结束
输入一条线 如 2,2,2,0
压缩去0 得 2,2,2
相邻两块相等?
合并为 4 计分+4 i跳2
原样保留 i跳1
尾部补0到长度4
与原始线比较 得 changed
输出 CollapseResult
这里最关键的就是 i = i + 2 这一行。合并掉两块之后必须跳过它们,否则第三次循环还会把刚生成的 4 再和下一个 2 比较,逻辑就乱了。这也是我第一版写错的地方。
最后是对外入口 move,它把上面两步串起来,并负责生成新块、判定胜负、返回全新盘面:
typescript
// ets/model/GameBoard.ets
move(dir: Direction): MoveResult {
const work: number[][] = this.emptyGrid();
let gained: number = 0;
let changed: boolean = false;
const lines: CellPos[][] = this.linesFor(dir);
for (let li: number = 0; li < lines.length; li++) {
const line: CellPos[] = lines[li];
const vals: number[] = [];
for (let k: number = 0; k < line.length; k++) {
const p: CellPos = line[k];
vals.push(this.cells[p.r][p.c]);
}
const res: CollapseResult = this.collapse(vals);
gained = gained + res.gained;
if (res.changed) {
changed = true;
}
for (let k: number = 0; k < line.length; k++) {
const p: CellPos = line[k];
work[p.r][p.c] = res.values[k];
}
}
let spawned: boolean = false;
let won: boolean = false;
let over: boolean = false;
if (changed) {
// 先整体替换盘面,再在空位上生成新块
this.cells = work;
spawned = this.spawn();
if (!this.wonLatch && this.reached2048()) {
this.wonLatch = true;
won = true;
}
// 注意:必须在 spawn 之后再判死局,否则会漏判"新块落下后仍无路可走"
over = !this.hasMoves();
}
const result: MoveResult = {
grid: this.getGrid(),
gained: gained,
moved: changed,
spawned: spawned,
won: won,
over: over
};
return result;
}
有几个刻意的设计必须点出来。第一,work 是一张新表,所有合并结果写进它,直到确认有效才整体替换 this.cells------这样"无效滑动"不会污染盘面。第二,getGrid() 返回的是深拷贝,UI 拿到的是一个与内部状态完全无关的全新数组,这是支撑"整体替换引用"的前提。第三,wonLatch 是个锁存位,达成 2048 后只弹一次胜利提示,玩家点"继续挑战"还能接着玩,不会被反复打断。
4.2 HighScoreStore:Preferences 持久化
最高分我用独立的仓储类封装,所有写操作收敛到一个出口:
typescript
// ets/common/HighScoreStore.ets
import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
const STORE_NAME: string = 'happy2048_prefs';
const KEY_HIGH_SCORE: string = 'high_score';
export class HighScoreStore {
private static instance: HighScoreStore = new HighScoreStore();
private prefs: preferences.Preferences | null = null;
static getInstance(): HighScoreStore {
return HighScoreStore.instance;
}
async init(context: common.Context): Promise<void> {
this.prefs = await preferences.getPreferences(context, STORE_NAME);
}
// 读取一律带默认值兜底
async getHighScore(): Promise<number> {
if (this.prefs === null) {
return 0;
}
const stored: preferences.ValueType = await this.prefs.get(KEY_HIGH_SCORE, 0);
if (typeof stored === 'number') {
return stored;
}
return 0;
}
// 仅当破纪录时写入:put + flush 成对出现
async tryUpdateHighScore(score: number): Promise<boolean> {
if (this.prefs === null) {
return false;
}
const old: number = await this.getHighScore();
if (score <= old) {
return false;
}
await this.prefs.put(KEY_HIGH_SCORE, score);
await this.prefs.flush();
return true;
}
// 退后台兜底 flush
async flush(): Promise<void> {
if (this.prefs !== null) {
await this.prefs.flush();
}
}
}
两个细节。其一,读取用 typeof stored === 'number' 做类型收窄,避免 Preferences 里没有 key 时返回非数字把 UI 搞崩。其二,put 之后紧跟 flush,把"落盘"这个动作锁死在类内部,调用方根本没机会漏掉。
4.3 Index 页面:状态替换、手势与动画
页面层的核心是 doMove。它接收逻辑层返回的 MoveResult,然后做三件事:整体替换 grid、更新分数、处理胜负:
typescript
// ets/pages/Index.ets
private doMove(dir: Direction): void {
if (this.gameOver) {
return;
}
const res: MoveResult = this.board.move(dir);
if (!res.moved) {
return; // 无效滑动:不生成新块、不计分、不触发重绘
}
// 关键:整体替换数组引用(不是 splice/push),否则 @State 观察不到变化
this.grid = res.grid;
this.score = this.score + res.gained;
this.delta = res.gained;
this.scoreScale = 1.25;
setTimeout(() => {
this.scoreScale = 1;
}, 200);
setTimeout(() => {
this.delta = 0;
}, 700);
if (res.won) {
this.won = true;
}
if (res.over) {
this.gameOver = true;
}
this.refreshHighScore();
}
this.grid = res.grid 这一行是整个 UI 刷新的开关。res.grid 是 GameBoard 深拷贝出来的全新数组,引用一变,@State 立刻感知,所有依赖它的 TileCell 重新渲染。而 splice、push 这类原地操作不会改变引用,因此无效------这就是第一章埋下的伏笔。
手势识别我用 SwipeGesture,挂在棋盘容器上,覆盖全部 16 格:
typescript
// ets/pages/Index.ets
.gesture(
SwipeGesture({ direction: SwipeDirection.All, distance: 30, speed: 100 })
.onAction((event: GestureEvent) => {
this.handleSwipe(event);
})
)
distance: 30 和 speed: 100 两个阈值很关键:滑得太短、太慢都不算数,这天然过滤了手指轻微抖动带来的误触。handleSwipe 负责把角度归一到四个方向:
typescript
// ets/pages/Index.ets
private handleSwipe(event: GestureEvent): void {
let a: number = event.angle % 360;
if (a < 0) {
a = a + 360;
}
if (a >= 315 || a < 45) {
this.doMove(Direction.Right);
} else if (a < 135) {
this.doMove(Direction.Down);
} else if (a < 225) {
this.doMove(Direction.Left);
} else {
this.doMove(Direction.Up);
}
}
这里我先把角度对 360 取模、负数再补正,统一到 [0, 360),然后四个 90 度扇区分别映射到右、下、左、上。之所以这么绕,是因为我第一版按"-180~180"的经验写,结果上下方向完全反了------这个坑第五章细说。
最后是格子组件 TileCell,它用 @Prop 单向接收值,只负责渲染:
typescript
// ets/pages/Index.ets
@Component
struct TileCell {
@Prop value: number = 0;
private bgColor(): string {
switch (this.value) {
case 0: return '#CDC1B4';
case 2: return '#EEE4DA';
case 4: return '#EDE0C8';
case 8: return '#F2B179';
case 16: return '#F59563';
case 32: return '#F67C5F';
case 64: return '#F65E3B';
case 128: return '#EDCF72';
case 256: return '#EDCC61';
case 512: return '#EDC850';
case 1024: return '#EDC53F';
case 2048: return '#EDC22E';
default: return '#3C3A32';
}
}
private textColor(): string {
return this.value <= 4 ? '#776E65' : '#F9F6F2';
}
private fontSize(): number {
if (this.value >= 1024) {
return 20;
}
if (this.value >= 128) {
return 24;
}
return 30;
}
build() {
Stack() {
if (this.value !== 0) {
Text(this.value.toString())
.fontSize(this.fontSize())
.fontColor(this.textColor())
.fontWeight(FontWeight.Bold)
.animation({ duration: 150, curve: Curve.EaseOut })
}
}
.width('100%')
.height('100%')
.backgroundColor(this.bgColor())
.borderRadius(8)
}
}
分数变化动画则是在 doMove 里把 scoreScale 瞬间设成 1.25,再用 setTimeout 在 200ms 后复位;配合 Text 上的 .scale() 和 .animation(),就得到一个轻微的"弹一下"效果。飘字 delta 也是同理,700ms 后清零。
五、踩坑实录:五个坑,按现象/原因/解法/代码还原
这一章全是真金白银换来的教训,每个坑都按"现象 / 原因 / 解法 / 代码"四段式写。
坑 1:二维数组原地修改,UI 纹丝不动
现象 :滑动后日志里 GameBoard.dump() 显示盘面已经变了,但界面上 16 个格子一个都没动,分数却已经加上去了。看起来像"数据变了、UI 没变"的经典脱节。
原因 :@State 观察的是变量的引用。我最初写的是 this.grid[0][1] = res.grid[0][1],这是按下标改数组元素,数组本身的引用没变,ArkUI 的响应式系统压根不知道数据变了。push、splice、下标赋值,这三种原地操作全都不触发刷新。
解法 :让 GameBoard.getGrid() 每次返回深拷贝,UI 侧用 this.grid = res.grid 整体替换引用。引用一变,整棵依赖树重绘。重开游戏 restart() 里同样用整体替换。
代码:
typescript
// ets/model/GameBoard.ets ------ 深拷贝保证返回全新引用
getGrid(): number[][] {
const copy: number[][] = [];
for (let r: number = 0; r < this.size; r++) {
const row: number[] = [];
for (let c: number = 0; c < this.size; c++) {
row.push(this.cells[r][c]);
}
copy.push(row);
}
return copy;
}
// ets/pages/Index.ets ------ 整体替换,而非原地修改
this.grid = res.grid; // 正确
// this.grid[0][0] = res.grid[0][0]; // 错误:不会刷新
坑 2:2,2,2,2 向左滑成了 8,0,0,0
现象 :手工构造一行 [2,2,2,2] 向左滑,期望是 [4,4,0,0],实际得到 [8,0,0,0],分数也算错了。
原因:合并循环里每次合并后没有跳过被合并的两块,导致刚生成的 4 又被拿去和下一块比较,连锁合并了。2048 的规则是"每个方块在同一次滑动中最多合并一次"。
解法 :合并分支里把索引 i 直接加 2,跳过这两块;只有不合并的分支才加 1。这是 collapse 里最关键的一行。
代码:
typescript
// ets/model/GameBoard.ets
while (i < nonZero.length) {
if (i + 1 < nonZero.length && nonZero[i] === nonZero[i + 1]) {
const merged: number = nonZero[i] * 2;
out.push(merged);
gained = gained + merged;
i = i + 2; // 关键:合并后跳过两块,防止连锁合并
} else {
out.push(nonZero[i]);
i = i + 1;
}
}
坑 3:滑动方向上下颠倒
现象:向左、向右滑动正常,向上滑却变成向下合并,向下滑变成向上,完全反了。
原因 :我第一版按"角度范围 -180~180"的经验写判断:angle > 0 算下。但 SwipeGesture 的 GestureEvent.angle 在不同系统版本上可能是 [0,360),向上滑返回接近 270 而不是 -90,于是被我判成了别的方向。
解法 :先把角度对 360 取模、负数补正,统一到 [0,360),再按四个 90 度扇区判断:0 附近右、90 附近下、180 附近左、270 附近上。这样不管原始角度是哪种表示,结果都一致。
代码:
typescript
// ets/pages/Index.ets
let a: number = event.angle % 360;
if (a < 0) {
a = a + 360;
}
if (a >= 315 || a < 45) {
this.doMove(Direction.Right);
} else if (a < 135) {
this.doMove(Direction.Down);
} else if (a < 225) {
this.doMove(Direction.Left);
} else {
this.doMove(Direction.Up);
}
坑 4:最高分退出即丢
现象:玩出一局 3000 分,退出 App 再进来,最高分还是 0。
原因 :我最初在 doMove 里直接 prefs.put(...) 就以为完事了。Preferences 的 put 只改内存,XML 模式下必须 flush() 才真正落盘,杀进程后内存态全丢。而且当时写入散落在好几个地方,有的地方漏了 flush。
解法 :把所有写入收敛到 HighScoreStore.tryUpdateHighScore,put 和 flush 强绑定成对出现;同时在 EntryAbility.onBackground 里再加一道 flush() 兜底。双保险。
代码:
typescript
// ets/common/HighScoreStore.ets
await this.prefs.put(KEY_HIGH_SCORE, score);
await this.prefs.flush(); // 关键:XML 模式下不 flush 只在内存
// ets/entryability/EntryAbility.ets
onBackground(): void {
HighScoreStore.getInstance().flush(); // 退后台兜底
}
坑 5:首页读到空的最高分 / EntryAbility 编译报错
现象 :两种并发问题。一是首页 aboutToAppear 读最高分时偶尔是 0,即使之前已经存过分;二是照着某些老模板写 EntryAbility,编译时报 Cannot find name 'Want'。
原因 :其一,Preferences 的 init 是异步的,如果 loadContent 抢在它完成前加载首页,首页读到的 prefs 还是 null,兜底返回 0。其二,基线模板里直接用了 Want 和 AbilityConstant,但漏了 import------正确写法是从 @kit.AbilityKit 一并导入。
解法 :在 onWindowStageCreate 里用 .then() 等 init 完成后再 loadContent;import 补全为 import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'。
代码:
typescript
// ets/entryability/EntryAbility.ets
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
onWindowStageCreate(windowStage: window.WindowStage): void {
const store: HighScoreStore = HighScoreStore.getInstance();
store.init(this.context).then(() => {
windowStage.loadContent('pages/Index', (err) => { /* ... */ });
});
}
六、性能优化与测试
编译通过:

运行效果如下:



功能跑通后,我在模拟器上做了几轮针对性验证。2048 的盘面只有 16 格,性能瓶颈不在渲染,而在"算法正确性"和"持久化可靠性",所以测试重点放在这两块。
算法层的可测性。 因为 GameBoard 是纯逻辑类,我可以完全绕开 UI,直接构造盘面验证 collapse。我给几个典型输入做了断言式验证:
| 输入行 | 期望输出 | 期望得分 | 说明 |
|---|---|---|---|
[2,2,0,0] |
[4,0,0,0] |
4 | 基础合并 |
[2,2,2,2] |
[4,4,0,0] |
8 | 每块只并一次(坑 2) |
[4,4,8,8] |
[8,16,0,0] |
24 | 不同数字分别合并 |
[2,0,2,4] |
[4,4,0,0] |
4 | 隔空压缩后再合并 |
[2,4,8,16] |
[2,4,8,16] |
0 | 无变化,changed=false |
持久化验证。 我用"高分写入 → 杀进程 → 重启读回"的路径验证了 flush 的可靠性,又用"低分不覆盖高分"验证了 tryUpdateHighScore 的守卫逻辑:
| 测试项 | 操作 | 结果 |
|---|---|---|
| 首次写入 | 得分 500 后退出重启 | 最高分 500 |
| 低分不覆盖 | 再玩一局得 200 | 最高分仍 500 |
| 高分刷新 | 再玩一局得 800 | 最高分 800,显示"新纪录" |
| 退后台兜底 | 得分后立刻切后台再杀进程 | 最高分正确落盘 |
体验层面的三个优化 。第一,手势加了 distance 和 speed 双阈值,误触明显减少。第二,TileCell 的颜色和数字都带 150ms 的 animation,合并有个柔和的过渡,不是生硬闪现。第三,wonLatch 让胜利提示只弹一次,玩家可以选择继续挑战,不被打断。这些都不复杂,但直接决定"像不像一个成品"。
边界情况的主动处理。 除了上面三点,我还专门处理了两个容易被忽略的边界。第一个是"盘面满了但还能合并":玩家往往以为没空格就是结束,实际上只要横竖还有相邻相等的数字就还能走,所以 hasMoves() 同时检查空格和相邻相等两种情况,绝不误判。第二个是"无效滑动不计分":往一个已经顶死的方向滑,盘面和分数都必须原封不动,不能因为手指抖了一下就凭空生成新块------move() 里只有在 changed 为真时才调用 spawn(),正是为了守住这条线。这些边界如果不在设计时想清楚,测试时就会变成一堆说不清的偶发 bug,排查起来比重写代码还累。
七、小结与适用边界
写到这里,2048 这个"玩具项目"的价值应该不用我多说了。它逼着我把可运行工程规范、状态管理、算法、手势、持久化五件事全部走通一遍。回头看,最值得沉淀的是这几条原则:
工程先行。 先把 trio 配置、Ability 入口、资源索引搭齐,再写业务代码。一份跑不起来的工程,代码写得再漂亮也是零。这次我严格执行了这个顺序,所以从头到尾没有再出现"复制过去跑不起来"的尴尬。
状态刷新认准"引用"。 在 ArkUI 里,二维数组、对象数组这类引用类型,想让 @State 感知变化,就要整体替换引用,不要原地 push/splice/下标赋值。这是 2048 教给我最深刻的一课。
算法归一胜过四份复制。 四个方向的合并,用坐标归一收敛到一套 collapse,代码量少了四倍,bug 也少了。写算法时先想"能不能把不同情况映射到同一个模型",往往比硬写更省事。
持久化写操作要收敛。 Preferences 的 put 必须配 flush,而且最好把这对动作锁在一个类的方法里,不让调用方有机会漏掉。再在生命周期回调里加一道兜底,万无一失。
适用边界也要说清楚。 这套纯本地 ArkUI 方案适合单机益智、工具类应用;它不适合需要联网对战、排行榜、跨设备同步的场景------那些要引入服务端或分布式能力。另外,2048 的格子是值类型,用 @State + 整体替换就够了;如果换成"列表项是可编辑对象、需要单项刷新"的场景,才是 @Observed + @ObjectLink 的主场,不要生搬硬套。知道一个方案不能干什么,和知道它能干什么同样重要。
给打算照着做的读者几句实在话。 如果你也想按这篇文章搭一遍,我建议严格按"工程 → 逻辑 → UI"的顺序来:先把 trio 配置和 Ability 入口搭齐,点一次运行确认空壳工程能起来,再写 GameBoard 并用 dump() 验证算法,最后才接 UI 和手势。我当初偷懒跳过第一步,结果一开始调试时根本分不清是算法错了还是工程配置错了,白白浪费了半天。另外,GameBoard 的 dump() 方法看着不起眼,却是排查合并算法最趁手的工具------在 hilog 里打印每一行,比盯着模拟器上的格子猜要高效得多。
这份 Happy2048 工程我已经在 DevEco 模拟器上完整跑通,代码全部来自真实文件。下一篇我准备写"ArkUI 动画进阶:从 2048 的飘字到组合动画",欢迎在评论区聊聊你在状态刷新或手势识别上踩过的坑。
本文为原创首发技术实战,基于 HarmonyOS NEXT / API 12 / Stage 模型,代码来自真实工程 Happy2048,可在本地模拟器直接运行。实际接口以华为官方文档为准。【鸿蒙心迹】系列。