{"id":13671506,"url":"https://github.com/leeenx/popstar","last_synced_at":"2026-01-12T02:29:57.261Z","repository":{"id":57327485,"uuid":"111139534","full_name":"leeenx/popstar","owner":"leeenx","description":"H5小游戏100例：消灭星星","archived":false,"fork":false,"pushed_at":"2020-03-16T16:52:40.000Z","size":714,"stargazers_count":300,"open_issues_count":0,"forks_count":94,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-04-20T05:48:23.557Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/leeenx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-17T18:51:57.000Z","updated_at":"2025-03-22T10:58:27.000Z","dependencies_parsed_at":"2022-09-13T19:00:29.819Z","dependency_job_id":null,"html_url":"https://github.com/leeenx/popstar","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fpopstar","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fpopstar/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fpopstar/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fpopstar/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/leeenx","download_url":"https://codeload.github.com/leeenx/popstar/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251187156,"owners_count":21549596,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:01:11.379Z","updated_at":"2026-01-12T02:29:57.249Z","avatar_url":"https://github.com/leeenx.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# H5小游戏100例：消灭星星\n\n「消灭星星」是一款很经典的「消除类游戏」，它的玩法很简单：消除相连通的同色砖块。\n\n![demo](http://7xv39r.com1.z0.glb.clouddn.com/popstar.gif)\n\n## 1. 游戏规则\n\n「消灭星星」存在多个版本，不过它们的规则除了「关卡分值」有些出入外，其它的规则都是一样的。笔者介绍的版本的游戏规则整理如下：\n\n**1. 色砖分布**\n\n- 10 x 10 的表格\n- 5种颜色 ------ 红、绿、蓝，黄，紫\n- 每类色砖个数在指定区间内随机\n- 5类色砖在 10 x 10 表格中随机分布\n\n**2. 消除规则**\n\n两个或两个以上同色砖块相连通即是可被消除的砖块。\n\n**3. 分值规则**\n\n- 消除总分值 = n * n * 5\n- 奖励总分值 = 2000 - n * n * 20\n\n「n」表示砖块数量。上面是「总」分值的规则，还有「单」个砖块的分值规则：\n\n- 消除砖块得分值 = 10 * i + 5\n- 剩余砖块扣分值 = 40 * i + 20 \n\n「i」表示砖块的索引值（从 0 开始）。简单地说，单个砖块「得分值」和「扣分值」是一个等差数列。\n\n**4. 关卡分值** \n\n关卡分值 = 1000 + (level - 1) * 2000；「level」即当前关卡数。\n\n**5. 通关条件**\n\n- 可消除色块不存在\n- 累计分值 \u003e= 当前关卡分值\n\n上面两个条件同时成立游戏才可以通关。\n\n## 2. MVC 设计模式\n\n笔者这次又是使用了 MVC 模式来写「消灭星星」。星星「砖块」的数据结构与各种状态由 Model 实现，游戏的核心在 Model 中完成；View 映射 Model 的变化并做出对应的行为，它的任务主要是展示动画；用户与游戏的交互由 Control 完成。\n\n从逻辑规划上看，Model 很重而View 与 Control 很轻，不过，从代码量上看，View 很重而 Model 与 Control 相对很轻。\n\n\n## 3. Model \n\n10 x 10 的表格用长度为 100 的数组可完美映射游戏的星星「砖块」。\n\n```javascript\n[\n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P, \n\tR, R, G, G, B, B, Y, Y, P, P\n]\n```\nR - 红色，G - 绿色，B - 蓝色，Y - 黄色，P - 紫色。Model 的核心任务是以下四个：\n\n- 生成砖墙\n- 消除砖块 （生成砖块分值）\n- 夯实砖墙 \n- 清除残砖 （生成奖励分值）\n\n### 3.1 生成砖墙\n\n砖墙分两步生成：\n- 色砖数量分配\n- 打散色砖\n\n理论上，可以将 100 个格子可以均分到 5 类颜色，不过笔者玩过的「消灭星星」都不使用均分策略。通过分析几款「消灭星星」，其实可以发现一个规律 ------ 「**色砖之间的数量差在一个固定的区间内**」。\n\n如果把传统意义上的均分称作「完全均分」，那么「消灭星星」的分配是一种在均分线上下波动的「不完全均分」。\n\n![正余弦波线图](http://7xv39r.com1.z0.glb.clouddn.com/2017-12-06-waveAverage.gif)\n\n笔者把上面的「不完全均分」称作「波动均分」，算法的具体实现可以参见「[波动均分算法](https://aotu.io/notes/2018/01/11/waveaverage/)」。\n\n「打散色砖」其实就是将数组乱序的过程，笔者推荐使用「 [费雪耶兹乱序算法](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)」。\n\n以下是伪代码的实现：\n```javascript\n// 波动均分色砖\nwaveaverage(5, 4, 4).forEach(\n\t// tiles 即色墙数组\n\t(count, clr) =\u003e tiles.concat(generateTiles(count, clr)); \n); \n// 打散色砖\nshuffle(tiles); \n```\n\n### 3.2 消除砖块 \n\n「消除砖块」的规则很简单 ------ **相邻相连通相同色即可以消除**。\n\n![连通图](http://7xv39r.com1.z0.glb.clouddn.com/20180111-connection.png)\n前两个组合符合「相邻相连通相同色即可以消除」，所以它们可以被消除；第三个组合虽然「相邻相同色」但是不「相连通」所以它不能被消除。\n\n「消除砖块」的同时有一个重要的任务：生成砖块对应的分值。在「游戏规则」中，笔者已经提供了对应的数学公式：「消除砖块得分值 = 10 * i + 5」。\n\n**「消除砖块」算法实现如下：**\n```javascript\nfunction clean(tile) { \n\tlet count = 1; \n\tlet sameTiles = searchSameTiles(tile); \n\tif(sameTiles.length \u003e 0) { \n\t\tdeleteTile(tile); \n\t\twhile(true) {\n\t\t\tlet nextSameTiles = []; \n\t\t\tsameTiles.forEach(tile =\u003e { \n\t\t\t\tnextSameTiles.push(...searchSameTiles(tile)); \n\t\t\t\tmakeScore(++count * 10 + 5); // 标记当前分值 \n\t\t\t\tdeleteTile(tile); // 删除砖块\n\t\t\t}); \n\t\t\t// 清除完成，跳出循环\n\t\t\tif(nextSameTiles.length === 0) break; \n\t\t\telse {\n\t\t\t\tsameTiles = nextSameTiles; \n\t\t\t}\n\t\t}\n\t}\n}\n```\n清除的算法使用「递归」逻辑上会清晰一些，不过「递归」在浏览器上容易「栈溢出」，所以笔者没有使用「递归」实现。\n\n### 3.3 夯实砖墙\n\n砖墙在消除了部分砖块后，会出现空洞，此时需要对墙体进行夯实：\n\n| ![向下夯实](http://7xv39r.com1.z0.glb.clouddn.com/20180112-down.gif) | ![向左夯实](http://7xv39r.com1.z0.glb.clouddn.com/20180112-left.gif) | ![先下再左夯实](http://7xv39r.com1.z0.glb.clouddn.com/20180112-down-left.gif) | \n| :----: | :----: | :----: |\n| **向下夯实** | **向左夯实** | **向左下夯实**（先下后左） |\n\n一种快速的实现方案是，每次「消除砖块」后直接遍历砖墙数组（10x10数组）再把空洞夯实，伪代码表示如下：\n\n```javascript\nfor(let row = 0; row \u003c 10; ++row) {\n\tfor(let col = 0; col \u003c 10; ++col) { \n\t\tif(isEmpty(row, col)) {\n\t\t\t// 水平方向（向左）夯实\n\t\t\tif(isEmptyCol(col)) { \n\t\t\t\ttampRow(col); \n\t\t\t}\n\t\t\t// 垂直方向（向下）夯实\n\t\t\telse {\n\t\t\t\ttampCol(col); \n\t\t\t}\n\t\t\tbreak; \n\t\t}\n\t}\n}\n```\n\nBut... 为了夯实一个空洞对一张大数组进行全量遍历并不是一种高效的算法。在笔者看来影响「墙体夯实」效率的因素有：\n\n1. 定位空洞\n2. 砖块移动（夯实）\n\n扫描墙体数组的主要目的是「定位空洞」，但能否不扫描墙体数组直接「定位空洞」？\n\n墙体的「空洞」是由于「消除砖块」造成的，换种说法 ------ **被消除的砖块留下来的坑位就是墙体的空洞**。在「消除砖块」的同时标记空洞的位置，这样就无须全量扫描墙体数组，伪代码如下：\n\n```javascript\nfunction deleteTile(tile) { \n\t// 标记空洞\n\tmarkHollow(tile.index); \n\t// 删除砖块逻辑\n\t...\n}\n```\n\n在上面的夯实动图，其实可以看到它的夯实过程如下：\n\n1. 空洞上方的砖块向下移动\n2. 空列右侧的砖块向左移动\n\n墙体在「夯实」过程中，它的边界是实时在变化，如果「夯实」不按真实边界进行扫描，会产生多余的空白扫描：\n\n![对比](http://7xv39r.com1.z0.glb.clouddn.com/20180116-clean.gif)\n\n**如何记录墙体的边界？**  \n把墙体拆分成一个个单独的列，那么列最顶部的空白格片段就是墙体的「空白」，而其余非顶部的空白格片段即墙体的「空洞」。\n\n![列](http://7xv39r.com1.z0.glb.clouddn.com/20180117-col.gif)\n\n笔者使用一组「列集合」来描述墙体的边界并记录墙体的空洞，它的模型如下：\n\n```javascript\n/*\n\t@ count - 列砖块数\n\t@ start - 顶部行索引\n\t@ end - 底部行索引\n\t@ pitCount - 坑数\n\t@ topPit - 最顶部的坑\n\t@ bottomPit - 最底部的坑\n*/ \nlet wall = [\n\t{count, start, end, pitCount, topPit, bottomPit}, \n\t{count, start, end, pitCount, topPit, bottomPit},\n\t...\n]; \n```\n这个模型可以描述墙体的三个细节：\n\n- 空列\n- 列的连续空洞\n- 列的非连续空洞\n\n```javascript\n// 空列\nif(count === 0) { \n\t...\n}\n// 连续空洞\nelse if(bottomPit - topPit + 1 === pitCount) { \n\t...\n}\n// 非连续空洞\nelse {\n\t...\n}\n```\n\n砖块在消除后，映射到单个列上的空洞会有两种分布形态 ------ 连续与非连续。  \n\n![连续空格与非连续空格](http://7xv39r.com1.z0.glb.clouddn.com/20180117-col2.gif)\n\n「连续空洞」与「非连续空洞」的夯实过程如下：\n\n![空洞压缩](http://7xv39r.com1.z0.glb.clouddn.com/20180117-tamp.gif)\n\n其实「空列」放大于墙体上，也会有「空洞」类似的分布形态 ------ 连续与非连续。\n![空洞压缩](http://7xv39r.com1.z0.glb.clouddn.com/20180117-col3.gif)\n\n它的夯实过程与空洞类似，这里就不赘述了。\n\n### 4.4 消除残砖\n\n上一小节提到了「描述墙体的边界并记录墙体的空洞」的「列集合」，笔者是直接使用这个「列集合」来消除残砖的，伪代码如下：\n\n```javascript\nfunction clearAll() {\n\tlet count = 0; \n\tfor(let col = 0, len = this.wall.length;  col \u003c len; ++col) { \n\t\tlet colInfo = this.wall[col]; \n\t\tfor(let row = colInfo.start; row \u003c= colInfo.end; ++row) {\n\t\t\tlet tile = this.grid[row * this.col + col]; \n\t\t\ttile.score = -20 - 40 * count++; // 标记奖励分数\n\t\t\ttile.removed = true; \n\t\t}\n\t}\n}\n```\n\n## 4. View\n\nView 主要的功能有两个：\n\n- UI 管理\n- 映射 Model 的变化（动画）\n\nUI 管理主要是指「界面绘制」与「资源加载管理」，这两项功能比较常见本文就直接略过了。View 的重头戏是「映射 Model 的变化」并完成对应的动画。动画是复杂的，而映射的原理是简单的，如下伪代码：\n\n```javascript\nupdate({originIndex, index, clr, removed, score}) { \n\t// 还没有 originIndex 或没有色值，直接不处理\n\tif(originIndex === undefined || clr === undefined) return ; \n\tlet tile = this.tiles[originIndex]; \n\t// tile 存在，判断颜色是否一样\n\tif(tile.clr !== clr) {\n\t\tthis.updateTileClr(tile, clr); \n\t}\n\t// 当前索引变化 ----- 表示位置也有变化 \n\tif(tile.index !== index) { \n\t\tthis.updateTileIndex(tile, index); \n\t}\n\t// 设置分数\n\tif(tile.score !== score) {\n\t\ttile.score = score; \n\t}\n\n\tif(tile.removed !== removed) { \n\t\t// 移除或添加当前节点\n\t\ttrue === removed ? this.bomb(tile) : this.area.addChild(tile.sprite); \n\t\ttile.removed = removed; \n\t}\n}\n```\n\nModel 的砖块每次数据的更改都会通知到 View 的砖块，View 会根据对应的变化做对应的动作（动画）。\n\n## 5. Control\n\nControl 要处理的事务比较多，如下：\n\n- 绑定 Model \u0026 View \n- 生成通关分值\n- 判断通关条件\n- 对外事件\n- 用户交互\n\n\n初始化时，Control 把 Model 的砖块单向绑定到 View 的砖块了。如下：\n\n```javascript\nObject.defineProperties(model.tile, \n\t{\n\t\toriginIndex: {\n\t\t\tget: () =\u003e {...}, \n\t\t\tset: () =\u003e {\n\t\t\t\t...\n\t\t\t\tview.update({originIndex});\n\t\t\t}\n\t\t},  \n\t\tindex: {\n\t\t\tget: () =\u003e {...}, \n\t\t\tset: () =\u003e {\n\t\t\t\t...\n\t\t\t\tview.update({index});\n\t\t\t}\n\t\t}, \n\t\tclr: {\n\t\t\tget: () =\u003e {...}, \n\t\t\tset: () =\u003e {\n\t\t\t\t...\n\t\t\t\tview.update({clr});\n\t\t\t}\n\t\t}, \n\t\tremoved: {\n\t\t\tget: () =\u003e {...}, \n\t\t\tset: () =\u003e {\n\t\t\t\t...\n\t\t\t\tview.update({removed});\n\t\t\t}\n\t\t},  \n\t\tscore: {\n\t\t\tget: () =\u003e {...}, \n\t\t\tset: () =\u003e {\n\t\t\t\t...\n\t\t\t\tview.update({score});\n\t\t\t}\n\t\t}, \n\t}\n); \n``` \n\n「通关分值」与「判断通关条件」这对逻辑在本文的「游戏规则」中有相关介绍，这里不再赘述。\n\n对外事件规划如下：\n\n| name | detail | \n| :-- | :-- |\n| pass | 通关 |\n| pause | 暂停 |\n| resume | 恢复 |\n| gameover | 游戏结束 |\n\n用户交互 APIs 规划如下：\n\n| name | type | deltail |\n| :-- | :-- | :-- |\n| init | method | 初始化游戏 |\n| next | method | 进入下一关 |\n| enter | method | 进入指定关卡 |\n| pause | method | 暂停 |\n| resume | method | 恢复 | \n| destroy | method | 销毁游戏 |\n\n## 6. 问题\n\n在知乎有一个关于「消灭星星」的话题：[popstar关卡是如何设计的？](https://www.zhihu.com/question/22530789)\n\n这个话题在最后提出了一个问题 ------ **「无法消除和最大得分不满足过关条件的矩阵」**。\n\n![两个问题](https://pic1.zhimg.com/50/98d59c105bc5331d0596e20ec2e2e554_hd.jpg)\n\n「无法消除的矩阵」其实就是最大得分为0的矩阵，本质上是「最大得分不满足过关条件的矩阵」。\n\n**最大得分不满足过关条件的矩阵**  \n求「矩阵」的最大得分是一个 「[背包问题](https://baike.baidu.com/item/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98)」，求解的算法不难：对当前矩阵用「递归」的形式把所有的消灭分支都执行一次，并取最高分值。但是  javascript 的「递归」极易「栈溢出」导致算法无法执行。\n\n其实在知乎的话题中提到一个解决方案：\n\n\u003e 网上查到有程序提出做个工具随机生成关卡，自动计算，把符合得分条件的关卡筛选出来\n\n这个解决方案代价是昂贵的！笔者提供有源码并没有解决这个问题，而是用一个比较取巧的方法：**进入游戏前检查是事为「无法消除矩阵」，如果是重新生成关卡矩阵**。\n\n注意：笔者使用的取巧方案并没有解决问题。\n\n\n## 7. 结语\n\n下面是本文介绍的「消灭星星」的线上 DEMO 的二维码：\n\n![二维码](http://7xv39r.com1.z0.glb.clouddn.com/qr.jpg)\n\n游戏的源码托管在：[https://github.com/leeenx/popstar](https://github.com/leeenx/popstar)\n\n感谢耐心阅读完本文章的读者。本文仅代表笔者的个人观点，如有不妥之处请不吝赐教。\n如果对「H5游戏开发」感兴趣，欢迎关注我们的[专栏](https://zhuanlan.zhihu.com/snsgame)。 \n\n## 参考资料\n\n- [Knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem)\n- [NP-completeness](https://en.wikipedia.org/wiki/NP-completeness)\n- [popstar关卡是如何设计的？](https://www.zhihu.com/question/22530789)\n- [费雪耶兹乱序算法](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)\n- [波动均分算法](https://aotu.io/notes/2018/01/11/waveaverage/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleeenx%2Fpopstar","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleeenx%2Fpopstar","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleeenx%2Fpopstar/lists"}