⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

version unknown

guizang-game-skill

op7418@op7418⭐ 308 stars· last commit 4d ago· 3 open issues

用 AI 生成素材(Tripo 等 3D 模型、即梦等图片与配音、Suno 等配乐)加 three.js,做一个能在浏览器里跑、最后打包成单个 HTML 的 3D 动作游戏的完整流程和踩坑清单。只要用户想做网页 3D 游戏、WebGL 游戏、three.js 游戏、俯视角或魂类动作游戏、带 Boss 战的 demo,或者提到"打击感""技能特效""掉落物""单文件分发""用 AI 生成模型做游戏",哪怕没说"用这个 skill",都应该先读它再动手。Build a polished browser 3D action game (three.js / WebGL, isometric soulslike, boss fight) with AI-generated assets and ship it as one HTML file.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐⭐ 308 on GitHubGitHub ↗

Popular

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

歸藏 Game Skill

让 AI 从零做出一个能在浏览器里玩的 3D 动作游戏

English · 简体中文

试玩演示 License Stars

上面这段是演示游戏《雾锁山门》里的实机画面。点这里直接玩,电脑和手机都能打开,不用安装。


这是什么

一个给 AI 编程助手(Claude Code、Codex 等)用的 Skill。装上之后,对它说"做一个武侠题材的俯视角 3D 动作游戏",它会按一套走通过的流程去做:先问清楚你要什么,接上你手头的素材生成工具,自己推进画面、自己截图核对,最后把游戏打包成一个网页文件。

Skill 里写的不是理论,是我用 Fable 5.2 花一个下午做出《雾锁山门》的过程中踩过的坑,和最后留下来的做法。那次大约 6 小时、4.5 亿 Token(其中一部分是 Opus 5.5 跑的测试),很多都花在了返工和试错上。这个 Skill 的目的就是让你和你的 AI 少走这些弯路。

演示游戏:雾锁山门

一个仙侠题材的俯视角 3D 动作游戏:一个场景、一段小怪遭遇战、一场 Boss 战,有剧情和配音。所有创意都是 AI 自己定的,我只说了要做国风仙侠。

  • 画面:大片随风起伏的草,分层的雾、雪和远山,覆水石台上的反光。渲染流程是在 three.js 上自己搭的,只用兼容性最好的 WebGL,所以手机、电脑、小程序类容器里都能跑
  • 角色与场景:5 个带骨骼的 3D 角色、2 把武器、12 种场景道具、5 种掉落物。先用即梦出设定图,再用 Tripo 转成模型,提示词都是 AI 自己写的
  • 战斗:三段连招、闪避、格挡、弹反、处决,还有饮药、御剑和大招"万剑归宗"。Boss 有二阶段、起身过场和台词
  • 声音:8 条配音、配乐、环境音和音效
  • 体积:原始素材将近 100MB,打包后是一个约 33MB 的 HTML,里面包含全部模型、贴图、音乐和配音

演示的三种形态,都是同一份源码打出来的:

形态说明
在线版先渲染出场景再边跑边加载;手机有触屏摇杆和按钮;设置里可以调画质、换高清材质、改按键
单文件版一个约 33MB 的 HTML,没有任何网络请求
小程序容器版按小红书小工具的限制(不能联网、不能用 WASM、包体 10MiB)单独构建,约 8MiB

这个 Skill 帮你做什么

直接让 AI"做个 3D 游戏",通常会得到一个方块灰模、手感发飘、要自己搭环境才能跑的东西。装上这个 Skill 之后:

  1. 开工前先问清楚。参考、视角、氛围、范围,以及你手头有哪些素材工具和多少额度。它不会闷头写一个方块模型出来,上来就把你给的工具接上
  2. 自己验证,不用你反复试。第一天就装好自测工具:逐帧推进画面、直达某一关的网址参数、F3 诊断面板。它自己截图核对,再告诉你哪些看过、哪些只是没报错
  3. 战斗手感有章可循。出招前摇和后摇、命中顿帧、分级击退、格挡与弹反、敌人轮流进攻而不是一拥而上、闪避能打断动作。打击感从哪来,都写进去了
  4. 一份踩坑清单。方向键卡住、预设动画把角色甩离原地、泛光过曝、镜头被屋顶挡住、打包后角色缩小一半……每条都有症状、原因和做法
  5. 三种打包方式。把很大的模型和素材压到很小:单个 HTML、先出画面再加载的静态站点、受限容器的离线包

安装

把这个仓库的链接发给你的 AI,让它安装即可。或者手动:

git clone https://github.com/op7418/guizang-game-skill ~/.claude/skills/guizang-game-skill

Codex 等其它工具,克隆到它们各自的 skills 目录。

然后直接说需求,比如:

做一个武侠题材的俯视角网页 3D 动作游戏,一个场景、一波小怪、一个 Boss。
我有 Tripo 和即梦可以用。

需要准备

东西用途没有的话
Node.js 18+本地服务器和打包必需
Tripo图片转 3D 模型、骨骼绑定改用免费模型和程序化几何体,画面会打折扣
即梦 或其它出图工具角色设定图、图标、题字、配音改用免费素材
Suno配乐Skill 会写好提示词给你,或用程序生成的配乐

素材工具对最终效果影响很大。我一开始让它直接用文字生成模型,质量很差;改成"先出设定图,再转 3D"之后上了一个大档次。

流程

调研与规划 → 设定与素材 → 动作 → 手感与特效 → 声音与打包
  1. 调研与规划:读参考、查这类游戏的做法,写调研文档和分阶段计划
  2. 设定与素材:世界观、角色设定图、图转 3D、骨骼绑定
  3. 动作:平台给的预设动作不多,其余用程序算出每个姿势里手脚的位置
  4. 手感与特效:按战斗手感清单逐项做,特效走"网格 + 着色器"而不是堆粒子
  5. 声音与打包:音效、配音、配乐,然后压缩并打成单文件

目录

路径内容
SKILL.md整体流程和每个阶段的检查点
references/assets.md素材生成与免费素材来源
references/characters-animation.md角色、骨骼与动画
references/combat-feel.md战斗手感
references/vfx-ui-audio.md特效、界面与声音
references/pitfalls.md踩坑清单
references/packaging.md体积优化、单文件打包、在线托管、手机与受限容器
scripts/可直接复用的输入处理、本地服务器、三种打包脚本

先说清楚的事

  • 它不是一句话出成品。《雾锁山门》我试玩了 7 轮,每轮提 5 到 10 个问题。我不懂做游戏,只会说"动作很僵硬""打击感很差",AI 会把这些话翻译成专业做法去查、去改。你仍然需要来回试玩提意见
  • 几件事我会坚持让 AI 做:给它参考视频;要求"先调研再动手";别让它自己造轮子,把现成的素材工具接上
  • Skill 目前只在一个项目上完整走过一遍,另做过一次计划层面的对照测试。它能让方向少走弯路,不保证成品质量

许可

  • Skill 本身(本仓库 main 分支的文档与脚本):AGPL-3.0
  • 演示游戏《雾锁山门》的内容(美术、模型、配音、配乐、文案,位于 gh-pages 分支):© 2026 歸藏,保留所有权利。欢迎试玩和分享链接,未经许可请勿转载、改名再发布或商用

作者

歸藏。觉得有用的话点个 Star,也欢迎把你做出来的游戏发给我看。

// HOW IT'S BUILT

// FILES

21 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md7.6 KB5b841036e1f5upstream ↗
    ---
    name: guizang-game-skill
    license: AGPL-3.0
    description: 用 AI 生成素材(Tripo 等 3D 模型、即梦等图片与配音、Suno 等配乐)加 three.js,做一个能在浏览器里跑、最后打包成单个 HTML 的 3D 动作游戏的完整流程和踩坑清单。只要用户想做网页 3D 游戏、WebGL 游戏、three.js 游戏、俯视角或魂类动作游戏、带 Boss 战的 demo,或者提到"打击感""技能特效""掉落物""单文件分发""用 AI 生成模型做游戏",哪怕没说"用这个 skill",都应该先读它再动手。Build a polished browser 3D action game (three.js / WebGL, isometric soulslike, boss fight) with AI-generated assets and ship it as one HTML file.
    ---
    
    # 网页 3D 动作游戏:从零到单文件
    
    这份流程来自一次完整的实战:一个仙侠题材、斜俯视角、有小怪战和 Boss 战的网页动作游戏,最后打包成约 30MB 的单个 HTML。中间走了很多弯路,下面的每一条都对应一次真实的返工。
    
    核心判断只有一个:**这类项目失败的原因几乎从来不是代码写不出来,而是没人看过画面、没人听过声音、没人真的按过键。** 所以整份流程的重心是"怎么让每一步都被验证"和"哪些东西不要自己从零写"。
    
    ## 开工前必须和用户对齐的四件事
    
    1. **参考物**。让用户给参考视频或游戏,并且自己认真看、逐条拆解(镜头、技能节奏、界面风格)。没有参考就做出来的第一版,用户的评价通常是"和参考有半毛钱关系吗"。
    2. **视角和玩法范围**。斜俯视角比第三人称省非常多的工作量,画面也更容易显得精致。范围建议:一个场景、一段小怪战、一个 Boss。
    3. **可用的生成工具和积分**。问清楚有哪些命令行工具可用(3D 模型、图片、配音、配乐),每次花费多少。**用户主动提供工具时立刻接上**,不要坚持自己用几何体拼。
    4. **先调研再动手**。用户说"先调研"是认真的。把调研结论和分阶段计划写成文档,让用户确认后再开工。
    
    ## 阶段顺序(每阶段结束都要让用户看到东西)
    
    | 阶段 | 产出 | 验收方式 |
    |---|---|---|
    | 0 调研与设定 | 调研文档、设定、分阶段计划 | 用户确认 |
    | 1 渲染底座 | 能看的空场景:HDR、雾、泛光、调色 | 截图给用户 |
    | 2 场景 | 地面、植被、道具摆放 | 截图,先过静态图再做动态 |
    | 3 角色与动作 | 模型、骨骼、招式 | 单独的展示页,近景截图 |
    | 4 战斗 | 可玩的战斗 | 用户试玩 |
    | 5 演出与 Boss | 过场、Boss 招式 | 用户试玩 |
    | 6 界面、音乐、语音 | 完整包装 | 用户试玩并听 |
    | 7 打磨与打包 | 单文件 | 用户双击打开 |
    
    每个阶段结束把没解决的问题写进一个待办清单文件,并且**如实区分"验证过"和"只是不报错"**。
    
    按需读这些参考文件:
    
    - `references/assets.md` — 生成 3D 模型、图片、配音、配乐的具体做法和省钱办法。开始做任何素材前读。
    - `references/characters-animation.md` — 生成的角色模型怎么接、动作怎么做才不僵。做角色前读。
    - `references/combat-feel.md` — 打击感、格挡弹反、怪物设计、镜头。做战斗前读。
    - `references/vfx-ui-audio.md` — 技能特效、掉落物、界面、音量。做特效和界面前读。
    - `references/pitfalls.md` — 按症状查的踩坑清单。遇到怪问题时先查这里。
    - `references/packaging.md` — 压缩资源并打包成单个 HTML。配套 `scripts/build_single_html.mjs`。
    
    可以直接拿去用的脚本:
    
    - `scripts/input.js` — 不怕丢失松键事件的键鼠输入,带 F3 调试面板。项目一开始就用它,别自己重写输入。
    - `scripts/serve.mjs` — 本地静态服务器。
    - `scripts/build_single_html.mjs` — 压缩资源并内嵌成单个 HTML 的打包脚本(按 `references/packaging.md` 改路径)。
    
    ## 贯穿始终的工作方式
    
    **能用现成的就不要自己写。** 模型用生成工具或免费素材库,贴图用 CC0 材质库,音效用 CC0 音效包,配乐让用户用音乐模型出。自己写的合成音效和几何体模型,用户一眼(一耳)就能认出来是凑合的。
    
    **素材先出图再出模型。** 文字直接生成 3D 的质量明显差。稳定的做法是:图片模型出一张"单个物体、纯色背景、无特效"的设定图,再用图生 3D。图片便宜,可以多出几张挑。
    
    **每一步都要真的看。** 写完着色器、动作、特效之后,在浏览器里载入、截图、放大看。不要因为"语法检查过了"就汇报完成。具体方法见下一节。
    
    **花钱前报价,花完报数。** 生成工具通常有报价命令。视频类模型比图片、配音贵一到两个数量级,同一个目标优先找便宜的专用模型(例如配音不要走视频模型)。
    
    **用户的反馈要按原话逐条落实,然后再查资料。** 用户说"特效很僵""打击感差"时,不要凭感觉调参数,去查这个领域的常规做法,把结论写进调研文档再改。
    
    ## 怎么自己验证(没有人盯着屏幕的时候)
    
    浏览器标签页隐藏时不会跑动画帧,所以需要一套不依赖实时渲染的调试钩子。项目一开始就加上:
    
    ```js
    G.step = (n = 60, dt = 1/60) => { for (let i = 0; i < n; i++) frame(0, dt); };   // 手动推进 n 帧(含渲染)
    G.upd  = (n = 30, dt = 1/60) => { for (let i = 0; i < n; i++) updatePlayer(dt); }; // 只跑移动逻辑,快
    G.press = (...codes) => codes.forEach(c => pressed.add(c));                        // 模拟一次按键
    G.keys, G.mouse, G.pl(), G.fx, G.spawn(kind, pos)                                  // 暴露状态和生成器
    ```
    
    再配几个网址参数:`?stage=court` 直接进某一关,`?auto` 跳过标题,`?god` 无敌,`?show=char` 打开单独的角色展示页。
    
    用法:推进若干帧 → 读状态数值 → 截图 → 放大局部。几条经验:
    
    - **结论靠数值,截图只做辅助。** 截图偶尔是旧画面;状态数值不会骗人。
    - **带渲染的 `G.step` 很慢**,一次调用别超过一千帧,大规模扫描(例如全图找卡点)用只跑逻辑的 `G.upd`。
    - **自动测试默认静音**,否则用户会听到后台一直在响。测完把页面切回标题画面。
    - **改完代码必须在浏览器里实际载入一次并看控制台**,语法检查不够(见 `references/pitfalls.md` 的"游戏打不开")。
    
    ## 汇报的规矩
    
    用户不看代码,只看你怎么说。每次汇报:
    
    - 先说结论:改了什么、现在是什么状态。
    - 明确分开三类:实际看到或听到验证过的、只确认不报错的、没法验证需要用户试的。
    - 找不到原因就直说找不到,并给用户一个抓现场的办法(例如按 F3 显示调试面板再截图)。一次有效的截图比十轮猜测有用。
    - 报出这一轮花掉的积分。
    
    ## 这类项目最常见的七个翻车点
    
    1. 第一版自己用几何体和合成音拼,被整体推翻重做。
    2. 角色动作靠猜关节角度,姿势扭曲。应该指定手脚目标位置,用两段骨骼解算。
    3. 特效是"一张贴图盖在面片上"。应该用贴合运动轨迹的网格、滚动噪声、随时间侵蚀。
    4. 玩家和怪"各打各的"。缺攻击吸附、双方顿帧、受击分级、身体碰撞。
    5. 泛光下特效过曝成白块。高动态颜色峰值控制在 2 到 3。
    6. 为了修一个按键问题加的"保险"反而造成新的按键问题。输入处理只做最少的事。
    7. 交付前才发现依赖外网、体积上百兆。打包脚本要在中期就建好。
    
  • README.md8.0 KBf803968a0eb7upstream ↗
    <div align="center">
    
    <img src="media/icon.png" width="96" alt="雾锁山门">
    
    # 歸藏 Game Skill
    
    **让 AI 从零做出一个能在浏览器里玩的 3D 动作游戏**
    
    [English](README.en.md) · 简体中文
    
    [![试玩演示](https://img.shields.io/badge/试玩演示-雾锁山门-c9a45c?style=for-the-badge)](https://op7418.github.io/guizang-game-skill/)
    [![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=for-the-badge)](LICENSE)
    [![Stars](https://img.shields.io/github/stars/op7418/guizang-game-skill?style=for-the-badge&color=e9dcae)](https://github.com/op7418/guizang-game-skill/stargazers)
    
    <a href="https://op7418.github.io/guizang-game-skill/"><img src="media/demo.gif" width="720" alt="雾锁山门战斗演示"></a>
    
    *上面这段是演示游戏《雾锁山门》里的实机画面。[点这里直接玩](https://op7418.github.io/guizang-game-skill/),电脑和手机都能打开,不用安装。*
    
    </div>
    
    ---
    
    ## 这是什么
    
    一个给 AI 编程助手(Claude Code、Codex 等)用的 Skill。装上之后,对它说"做一个武侠题材的俯视角 3D 动作游戏",它会按一套走通过的流程去做:先问清楚你要什么,接上你手头的素材生成工具,自己推进画面、自己截图核对,最后把游戏打包成一个网页文件。
    
    Skill 里写的不是理论,是我用 Fable 5.2 花一个下午做出《雾锁山门》的过程中踩过的坑,和最后留下来的做法。那次大约 6 小时、4.5 亿 Token(其中一部分是 Opus 5.5 跑的测试),很多都花在了返工和试错上。这个 Skill 的目的就是让你和你的 AI 少走这些弯路。
    
    ## 演示游戏:雾锁山门
    
    <table>
    <tr>
    <td width="38%"><img src="media/cover.jpg" alt="标题画面"></td>
    <td>
    
    一个仙侠题材的俯视角 3D 动作游戏:一个场景、一段小怪遭遇战、一场 Boss 战,有剧情和配音。**所有创意都是 AI 自己定的**,我只说了要做国风仙侠。
    
    - **画面**:大片随风起伏的草,分层的雾、雪和远山,覆水石台上的反光。渲染流程是在 three.js 上自己搭的,只用兼容性最好的 WebGL,所以手机、电脑、小程序类容器里都能跑
    - **角色与场景**:5 个带骨骼的 3D 角色、2 把武器、12 种场景道具、5 种掉落物。先用即梦出设定图,再用 Tripo 转成模型,提示词都是 AI 自己写的
    - **战斗**:三段连招、闪避、格挡、弹反、处决,还有饮药、御剑和大招"万剑归宗"。Boss 有二阶段、起身过场和台词
    - **声音**:8 条配音、配乐、环境音和音效
    - **体积**:原始素材将近 100MB,打包后是一个约 33MB 的 HTML,里面包含全部模型、贴图、音乐和配音
    
    </td>
    </tr>
    </table>
    
    <table>
    <tr>
    <td><img src="media/shot_combo.jpg" alt="连招"></td>
    <td><img src="media/shot_skill.jpg" alt="剑诀"></td>
    <td><img src="media/shot_ult.jpg" alt="万剑归宗"></td>
    </tr>
    <tr>
    <td align="center">三段连招</td>
    <td align="center">剑诀</td>
    <td align="center">万剑归宗</td>
    </tr>
    </table>
    
    演示的三种形态,都是同一份源码打出来的:
    
    | 形态 | 说明 |
    |---|---|
    | [在线版](https://op7418.github.io/guizang-game-skill/) | 先渲染出场景再边跑边加载;手机有触屏摇杆和按钮;设置里可以调画质、换高清材质、改按键 |
    | 单文件版 | 一个约 33MB 的 HTML,没有任何网络请求 |
    | 小程序容器版 | 按小红书小工具的限制(不能联网、不能用 WASM、包体 10MiB)单独构建,约 8MiB |
    
    ## 这个 Skill 帮你做什么
    
    直接让 AI"做个 3D 游戏",通常会得到一个方块灰模、手感发飘、要自己搭环境才能跑的东西。装上这个 Skill 之后:
    
    1. **开工前先问清楚**。参考、视角、氛围、范围,以及你手头有哪些素材工具和多少额度。它不会闷头写一个方块模型出来,上来就把你给的工具接上
    2. **自己验证,不用你反复试**。第一天就装好自测工具:逐帧推进画面、直达某一关的网址参数、F3 诊断面板。它自己截图核对,再告诉你哪些看过、哪些只是没报错
    3. **战斗手感有章可循**。出招前摇和后摇、命中顿帧、分级击退、格挡与弹反、敌人轮流进攻而不是一拥而上、闪避能打断动作。打击感从哪来,都写进去了
    4. **一份踩坑清单**。方向键卡住、预设动画把角色甩离原地、泛光过曝、镜头被屋顶挡住、打包后角色缩小一半……每条都有症状、原因和做法
    5. **三种打包方式**。把很大的模型和素材压到很小:单个 HTML、先出画面再加载的静态站点、受限容器的离线包
    
    ## 安装
    
    把这个仓库的链接发给你的 AI,让它安装即可。或者手动:
    
    ```bash
    git clone https://github.com/op7418/guizang-game-skill ~/.claude/skills/guizang-game-skill
    ```
    
    Codex 等其它工具,克隆到它们各自的 skills 目录。
    
    然后直接说需求,比如:
    
    ```
    做一个武侠题材的俯视角网页 3D 动作游戏,一个场景、一波小怪、一个 Boss。
    我有 Tripo 和即梦可以用。
    ```
    
    ## 需要准备
    
    | 东西 | 用途 | 没有的话 |
    |---|---|---|
    | Node.js 18+ | 本地服务器和打包 | 必需 |
    | [Tripo](https://www.tripo3d.ai/) | 图片转 3D 模型、骨骼绑定 | 改用免费模型和程序化几何体,画面会打折扣 |
    | [即梦](https://jimeng.jianying.com/) 或其它出图工具 | 角色设定图、图标、题字、配音 | 改用免费素材 |
    | [Suno](https://suno.com/) | 配乐 | Skill 会写好提示词给你,或用程序生成的配乐 |
    
    素材工具对最终效果影响很大。我一开始让它直接用文字生成模型,质量很差;改成"先出设定图,再转 3D"之后上了一个大档次。
    
    ## 流程
    
    ```
    调研与规划 → 设定与素材 → 动作 → 手感与特效 → 声音与打包
    ```
    
    1. **调研与规划**:读参考、查这类游戏的做法,写调研文档和分阶段计划
    2. **设定与素材**:世界观、角色设定图、图转 3D、骨骼绑定
    3. **动作**:平台给的预设动作不多,其余用程序算出每个姿势里手脚的位置
    4. **手感与特效**:按战斗手感清单逐项做,特效走"网格 + 着色器"而不是堆粒子
    5. **声音与打包**:音效、配音、配乐,然后压缩并打成单文件
    
    ## 目录
    
    | 路径 | 内容 |
    |---|---|
    | [`SKILL.md`](SKILL.md) | 整体流程和每个阶段的检查点 |
    | [`references/assets.md`](references/assets.md) | 素材生成与免费素材来源 |
    | [`references/characters-animation.md`](references/characters-animation.md) | 角色、骨骼与动画 |
    | [`references/combat-feel.md`](references/combat-feel.md) | 战斗手感 |
    | [`references/vfx-ui-audio.md`](references/vfx-ui-audio.md) | 特效、界面与声音 |
    | [`references/pitfalls.md`](references/pitfalls.md) | 踩坑清单 |
    | [`references/packaging.md`](references/packaging.md) | 体积优化、单文件打包、在线托管、手机与受限容器 |
    | [`scripts/`](scripts) | 可直接复用的输入处理、本地服务器、三种打包脚本 |
    
    ## 先说清楚的事
    
    - **它不是一句话出成品**。《雾锁山门》我试玩了 7 轮,每轮提 5 到 10 个问题。我不懂做游戏,只会说"动作很僵硬""打击感很差",AI 会把这些话翻译成专业做法去查、去改。你仍然需要来回试玩提意见
    - **几件事我会坚持让 AI 做**:给它参考视频;要求"先调研再动手";别让它自己造轮子,把现成的素材工具接上
    - **Skill 目前只在一个项目上完整走过一遍**,另做过一次计划层面的对照测试。它能让方向少走弯路,不保证成品质量
    
    ## 许可
    
    - **Skill 本身**(本仓库 `main` 分支的文档与脚本):[AGPL-3.0](LICENSE)
    - **演示游戏《雾锁山门》的内容**(美术、模型、配音、配乐、文案,位于 `gh-pages` 分支):© 2026 歸藏,保留所有权利。欢迎试玩和分享链接,未经许可请勿转载、改名再发布或商用
    
    ## 作者
    
    [歸藏](https://x.com/op7418)。觉得有用的话点个 Star,也欢迎把你做出来的游戏发给我看。
    
  • scripts/build_minitool.mjs17 KB15cc805766b3upstream ↗
    // Build the Xiaohongshu mini-tool package: node tools/build_mini.mjs   (run from game/)  ->  dist/mini/ and dist/wusuo-minitool.zip
    // The container allows no network requests (fetch / XHR), no WASM, no module or inline scripts, and only web file types
    // (html css js json png jpg gif webp svg woff), 10 MiB for the whole zip. So:
    //   - models: simplified, textures pulled out as .webp files, geometry + animation as base64 inside data/*.js (classic scripts, loaded on demand)
    //   - audio: decoded with Web Audio from base64 in data/*.js (no media elements, no fetch); recorded music is left out, the synth score plays instead
    //   - code: one classic ES2017 script; every `fetch` in the bundle is rewritten to a local lookup, the meshopt (WASM) decoder is stubbed out
    import fs from 'node:fs'; import path from 'node:path'; import { execFileSync } from 'node:child_process';
    import { NodeIO } from '@gltf-transform/core'; import { ALL_EXTENSIONS, KHRMeshQuantization } from '@gltf-transform/extensions';
    import { textureCompress, dedup, prune, weld, simplify, resample } from '@gltf-transform/functions'; import { MeshoptSimplifier } from 'meshoptimizer'; import sharp from 'sharp'; import { build } from 'esbuild';
    
    const OUT = 'dist/mini', ZIP = 'dist/wusuo-minitool.zip'; fs.rmSync(OUT, { recursive: true, force: true }); for (const d of ['assets/m', 'assets/tex', 'assets/ui', 'assets/fx', 'data']) fs.mkdirSync(path.join(OUT, d), { recursive: true });
    await MeshoptSimplifier.ready; const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
    const J = (f) => JSON.parse(fs.readFileSync(f, 'utf8')); const log = (...a) => console.log(...a); const kb = (n) => (n / 1024).toFixed(0) + 'K';
    const IDX = {}; let nData = 0; const big = [];
    function dataFile(name, entries) { const f = name + '.js'; let s = ''; for (const [k, v] of Object.entries(entries)) { IDX[k] = f; s += `__D(${JSON.stringify(k)},${JSON.stringify(v)});\n`; if (v.b && v.b.length * 0.75 > 1048576) big.push(k + ' ' + kb(v.b.length * 0.75)); } fs.writeFileSync(path.join(OUT, 'data', f), s); nData += s.length; return s.length; }
    
    async function glb(rel, { tex = 512, tris = 4000, animOnly = false } = {}) {
      const d = await io.read('assets/' + rel), root = d.getRoot(), id = 'm' + Object.keys(IDX).length;
      if (animOnly) for (const n of root.listNodes()) { n.setMesh(null); n.setSkin(null); }
      // animation diet: scale tracks are all 1 (and harmful, see chars.js); translation tracks that never leave the rest pose say nothing
      for (const a of root.listAnimations()) for (const ch of a.listChannels()) { const p = ch.getTargetPath(), n = ch.getTargetNode(), sm = ch.getSampler(); let drop = p === 'scale';
        if (p === 'translation' && n) { const o = sm.getOutput(), r = n.getTranslation(), e = [0, 0, 0]; drop = true; for (let i = 0; i < o.getCount() && drop; i++) { o.getElement(i, e); if (Math.abs(e[0] - r[0]) + Math.abs(e[1] - r[1]) + Math.abs(e[2] - r[2]) > 2e-4) drop = false; } }
        if (drop) { a.removeChannel(ch); ch.dispose(); if (!sm.listParents().some((x) => x.propertyType === 'AnimationChannel')) { a.removeSampler(sm); sm.dispose(); } } }
      await d.transform(dedup(), resample());
      // long clips (idle loops, the long hurt take) keep every second key: 15 keys a second is plenty for slow motion, and it halves the biggest buffers
      for (const an of root.listAnimations()) for (const sm of new Set(an.listChannels().map((c) => c.getSampler()))) { const inp = sm.getInput(), out = sm.getOutput(), n = inp.getCount(); if (n < 100 || inp.getMax([])[0] < 3) continue; const es = out.getElementSize(), keep = []; for (let i = 0; i < n; i += 2) keep.push(i); if (keep[keep.length - 1] !== n - 1) keep.push(n - 1);
        const ti = new Float32Array(keep.length), to = new Float32Array(keep.length * es), e = []; keep.forEach((k, i) => { ti[i] = inp.getScalar(k); out.getElement(k, e); for (let c = 0; c < es; c++) to[i * es + c] = e[c]; }); sm.setInput(d.createAccessor().setType('SCALAR').setArray(ti).setBuffer(root.listBuffers()[0])); sm.setOutput(d.createAccessor().setType(out.getType()).setArray(to).setBuffer(root.listBuffers()[0])); }
      if (!animOnly) { let t = 0; for (const m of root.listMeshes()) for (const pr of m.listPrimitives()) t += (pr.getIndices()?.getCount() ?? pr.getAttribute('POSITION').getCount()) / 3; const ratio = Math.min(1, tris / t);
        if (ratio < 0.95) await d.transform(weld(), simplify({ simplifier: MeshoptSimplifier, ratio, error: 0.08, lockBorder: false })); }
      for (const m of root.listMeshes()) for (const pr of m.listPrimitives()) { pr.setAttribute('TANGENT', null); pr.setAttribute('COLOR_0', null); pr.setAttribute('TEXCOORD_1', null); }
      // pack normals, UVs and skin weights into normalised integers (plain glTF, no decoder needed). Positions stay float: quantising them rescales the mesh and broke skinned characters in the other build.
      { let used = false; const conv = (pr, sem, Arr, norm) => { const a = pr.getAttribute(sem); if (!a || a.getComponentType() !== 5126) return; const src = a.getArray(), es = a.getElementSize(), out = new Arr(src.length), max = Arr === Int8Array ? 127 : Arr === Uint8Array ? 255 : 65535;
          if (sem === 'TEXCOORD_0') { for (const v of src) if (v < 0 || v > 1) return; }
          if (sem === 'WEIGHTS_0') { for (let i = 0; i < src.length; i += es) { let t = 0; const q = []; for (let c = 0; c < es; c++) { q[c] = Math.round(src[i + c] * 255); t += q[c]; } let m = 0; for (let c = 1; c < es; c++) if (q[c] > q[m]) m = c; q[m] += 255 - t; for (let c = 0; c < es; c++) out[i + c] = Math.max(0, q[c]); } }
          else for (let i = 0; i < src.length; i++) out[i] = Math.round(Math.max(Arr === Int8Array ? -1 : 0, Math.min(1, src[i])) * max);
          pr.setAttribute(sem, d.createAccessor().setType(a.getType()).setArray(out).setNormalized(true).setBuffer(a.getBuffer())); if (sem !== 'WEIGHTS_0') used = true; };
        for (const m of root.listMeshes()) for (const pr of m.listPrimitives()) { conv(pr, 'NORMAL', Int8Array); conv(pr, 'TEXCOORD_0', Uint16Array); conv(pr, 'WEIGHTS_0', Uint8Array); }
        if (used) d.createExtension(KHRMeshQuantization).setRequired(true); }
      await d.transform(prune({ keepLeaves: true, keepAttributes: false }), textureCompress({ encoder: sharp, targetFormat: 'webp', resize: [tex, tex], quality: 78 }));
      root.listTextures().forEach((t, i) => t.setURI(`${id}_${i}.webp`)); root.listBuffers().forEach((b) => b.setURI(id + '.bin'));
      const { json, resources } = await io.writeJSON(d, { basename: id }); let bin = Buffer.alloc(0), img = 0;
      for (const [uri, data] of Object.entries(resources)) { if (uri.endsWith('.bin')) bin = Buffer.from(data); else { fs.writeFileSync(path.join(OUT, 'assets/m', uri), data); img += data.length; } }
      for (const im of json.images || []) im.uri = 'assets/m/' + im.uri; delete json.buffers[0].uri;
      let nt = 0; for (const m of root.listMeshes()) for (const pr of m.listPrimitives()) nt += (pr.getIndices()?.getCount() ?? 0) / 3;
      dataFile(id, { ['assets/' + rel]: { j: json, b: bin.toString('base64') } }); return `${kb(bin.length)} bin, ${kb(img)} img, ${Math.round(nt)} tris`;
    }
    // ---- models
    const chars = J('assets/chars.json'), props = J('assets/props.json'), loot = J('assets/loot.json');
    const TRI = { hero: 8000, boss: 8000, walker: 5500, caster: 5500, spear: 5500 }, PT = { gate: 6000, hall: 5000, shrine: 4500, tree: 3000, rock: 1500, statue: 2500, lantern: 2000, pillar: 1500, censer: 2000, stele: 1500, post: 1200, beast: 2500 };
    for (const [k, c] of Object.entries(chars)) { if (k === 'weapons') { for (const [w, f] of Object.entries(c)) log('weapon', w, await glb(f, { tex: 256, tris: 1500 })); continue; }
      log(k, await glb(c.files[0], { tex: 512, tris: TRI[k] || 6000 }), '| anim', c.files[1] ? await glb(c.files[1], { animOnly: true }) : '-'); }
    for (const [k, f] of Object.entries(props)) log('prop', k, await glb(f, { tex: k === 'gate' || k === 'hall' ? 512 : 256, tris: PT[k] || 2000 }));
    for (const [k, f] of Object.entries(loot)) log('loot', k, await glb(f, { tex: 128, tris: 700 }));
    dataFile('manifest', { 'assets/chars.json': { j: chars }, 'assets/props.json': { j: props }, 'assets/loot.json': { j: loot } });
    // ---- images stay ordinary files
    for (const f of fs.readdirSync('assets/tex').filter((f) => /\.jpg$/.test(f))) fs.writeFileSync(path.join(OUT, 'assets/tex', f), await sharp('assets/tex/' + f).resize(512, 512, { fit: 'inside' }).jpeg({ quality: 76 }).toBuffer());
    fs.writeFileSync(path.join(OUT, 'assets/fx/ink.jpg'), await sharp('assets/fx/ink.jpg').resize(1024, 1024, { fit: 'inside' }).jpeg({ quality: 78 }).toBuffer());
    for (const f of fs.readdirSync('assets/ui')) if (/\.(png|jpg)$/.test(f)) fs.writeFileSync(path.join(OUT, 'assets/ui', f), f === 'title.png' ? await sharp('assets/ui/title.png').resize(900, null, { withoutEnlargement: true }).png({ palette: true, colours: 48 }).toBuffer() : /^icon|^i_/.test(f) ? await sharp('assets/ui/' + f).resize(160, 160).jpeg({ quality: 80 }).toBuffer() : fs.readFileSync('assets/ui/' + f));
    // ---- audio: mono, low bitrate, base64 for decodeAudioData
    const tmp = path.join(OUT, '_t.mp3'); const enc = (src, br) => { execFileSync('ffmpeg', ['-y', '-v', 'error', '-i', src, '-ac', '1', '-b:a', br, tmp]); const b = fs.readFileSync(tmp); fs.unlinkSync(tmp); return b.toString('base64'); };
    { const e = {}; for (const f of fs.readdirSync('assets/sfx').filter((f) => f.endsWith('.mp3'))) e['assets/sfx/' + f] = { b: enc('assets/sfx/' + f, '48k') }; log('sfx', kb(dataFile('sfx', e))); }
    { const e = {}; for (const f of fs.readdirSync('assets/voice').filter((f) => f.endsWith('.mp3'))) e['assets/voice/' + f] = { b: enc('assets/voice/' + f, '40k') }; log('voice', kb(dataFile('voice', e))); }
    for (const n of ['explore', 'combat', 'boss']) if (fs.existsSync(`assets/music/${n}.mp3`)) log('music', n, kb(dataFile('mu_' + n, { [`assets/music/${n}.mp3`]: { b: enc(`assets/music/${n}.mp3`, '36k') } })));
    if (fs.existsSync('assets/music/ambient.mp3')) log('ambient', kb(dataFile('amb', { 'assets/music/ambient.mp3': { b: enc('assets/music/ambient.mp3', '40k') } })));
    // ---- code: classic script, ES2017, no fetch / WASM / dynamic import
    const AUTHOR = '/* 雾锁山门 · 歸藏作品 · © 2026 歸藏 Guizang · 未经许可不得转载、改名再发布或商用 · built by AI with guizang-game-skill */';
    const RUNTIME = `(function(){var M={},W={},L={},IDX=${JSON.stringify(IDX)};function k(u){return String(u).replace(/^\\.\\//,'').split('?')[0]}
    window.__D=function(key,v){M[key]=v;var w=W[key];if(w){delete W[key];for(var i=0;i<w.length;i++)w[i][0](v)}};
    function get(u){var key=k(u);return new Promise(function(res,rej){if(M[key])return res(M[key]);var f=IDX[key];if(!f)return rej(new Error('not packed: '+key));(W[key]=W[key]||[]).push([res,rej]);if(L[f])return;L[f]=1;var s=document.createElement('script');s.src='./data/'+f;s.onerror=function(){for(var q in W)if(IDX[q]===f){var w=W[q];delete W[q];for(var i=0;i<w.length;i++)w[i][1](new Error('load failed: '+f))}};document.head.appendChild(s)})}
    function b64(s){var bin=atob(s),n=bin.length,u=new Uint8Array(n);for(var i=0;i<n;i++)u[i]=bin.charCodeAt(i);return u.buffer}
    window.__MINI={get:get,b64:b64};
    window.__lf=function(u){return get(u).then(function(v){return{ok:true,status:200,json:function(){return Promise.resolve(v.j)},arrayBuffer:function(){return Promise.resolve(b64(v.b))},text:function(){return Promise.resolve(JSON.stringify(v.j))}}},function(){return{ok:false,status:404,json:function(){return Promise.reject(new Error('404'))},arrayBuffer:function(){return Promise.reject(new Error('404'))},text:function(){return Promise.reject(new Error('404'))}}})};
    window.__CFG={touch:true,links:false,settings:false,grass:26000,pixels:2.0e6,shadow:1024,quality:{ao:false,steps:8},trees:12,rocks:30};
    if(typeof globalThis==='undefined')window.globalThis=window;
    if(!Array.prototype.flat)Array.prototype.flat=function(d){d=d===undefined?1:d;return this.reduce(function(a,v){return a.concat(Array.isArray(v)&&d>0?v.flat(d-1):[v])},[])};
    if(!Array.prototype.flatMap)Array.prototype.flatMap=function(f,t){return this.map(f,t).flat()};
    if(!Object.fromEntries)Object.fromEntries=function(it){var o={};Array.from(it).forEach(function(e){o[e[0]]=e[1]});return o};
    if(!String.prototype.replaceAll)String.prototype.replaceAll=function(a,b){return typeof a==='string'?this.split(a).join(b):this.replace(a,b)};
    if(!Element.prototype.closest)Element.prototype.closest=function(s){var e=this;while(e&&e.nodeType===1){if(e.matches(s))return e;e=e.parentElement}return null};
    if(!window.queueMicrotask)window.queueMicrotask=function(f){Promise.resolve().then(f)};
    })();`;
    const r = await build({ entryPoints: ['src/game.js'], bundle: true, format: 'iife', minify: true, write: false, target: ['es2017', 'chrome61'], legalComments: 'none', charset: 'utf8',
      define: { fetch: '__lf', createImageBitmap: 'undefined', __NOFS__: 'true' }, alias: { three: './vendor/three/build/three.module.js' },
      plugins: [{ name: 'mini', setup(b) { b.onResolve({ filter: /^three\/addons\// }, (a) => /meshopt_decoder/.test(a.path) ? { path: 'meshopt-stub', namespace: 'stub' } : { path: path.resolve('vendor/three/jsm', a.path.slice('three/addons/'.length)) });
        b.onLoad({ filter: /.*/, namespace: 'stub' }, () => ({ contents: 'export const MeshoptDecoder = { supported: false, ready: Promise.resolve() };', loader: 'js' })); } }] });
    /* this package carries no outbound or social links at all, not even as text */
    const js = AUTHOR + '\n' + RUNTIME + '\n' + r.outputFiles[0].text.replace(/\s*·?\s*https:\/\/x\.com\/op7418/g, ''); fs.writeFileSync(path.join(OUT, 'game.js'), js);
    // ---- html: no inline or module scripts, no outbound links, CSS a Chrome 61 engine can read
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/<script type="importmap">[\s\S]*?<\/script>\n?/, ''); const i0 = html.indexOf('<script type="module">'), i1 = html.indexOf('</script>', i0) + 9; html = html.slice(0, i0) + '<script src="./game.js"></script>' + html.slice(i1);
    html = html.replace(/<a ([^>]*)>/g, (m, at) => '<span ' + at.replace(/\s*(href|target|rel)="[^"]*"/g, '') + '>').replace(/<\/a>/g, '</span>').replace(/ ↗/g, '').replace('这个游戏由 AI 用 guizang-game-skill 做成 · 看它是怎么做的', '这个游戏由 AI 用 guizang-game-skill 做成').replace(/https:\/\/github\.com\/op7418\/guizang-game-skill/g, 'guizang-game-skill(GitHub: op7418)').replace(/\s*\(https:\/\/x\.com\/op7418\)/g, '').replace(/\s*https:\/\/x\.com\/op7418/g, '');
    html = html.replace(/(src|href)="assets\//g, '$1="./assets/').replace(/url\(assets\//g, 'url(./assets/');
    const first = (args) => { let d = 0, cur = '', out = []; for (const c of args) { if (c === '(') d++; if (c === ')') d--; if (c === ',' && d === 0) { out.push(cur.trim()); cur = ''; } else cur += c; } out.push(cur.trim()); return out; };
    html = html.replace(/<style>([\s\S]*?)<\/style>/, (m, css) => { css = css.replace(/inset:\s*0\s*;/g, 'top:0; right:0; bottom:0; left:0;').replace(/inset:\s*(-?[\d.]+px)\s+(-?[\d.]+px)\s*;/g, 'top:$1; bottom:$1; left:$2; right:$2;');
      css = css.replace(/([\w-]+):([^;{}]*\b(?:min|clamp)\([^;{}]*);/g, (d, prop, val) => { let fb = val, g = 0; while (/\b(min|clamp)\(/.test(fb) && g++ < 6) fb = fb.replace(/\b(min|clamp)\(((?:[^()]|\([^()]*\))*)\)/, (x, fn, a) => { const p = first(a); return fn === 'min' ? p[0] : p[1]; }); return `${prop}:${fb}; ${prop}:${val};`; });
      css += '\n  /* Chrome 61 has no flex gap */ .toast { margin-bottom:8px; } #baglist b { margin-left:24px; }\n'; return '<style>' + css + '</style>'; });
    fs.writeFileSync(path.join(OUT, 'index.html'), html);
    // ---- static gates
    const bad = []; const scan = (name, txt, pats) => { for (const p of pats) { const m = txt.match(p); if (m) bad.push(`${name}: ${m[0]}`); } };
    scan('game.js', js, [/\bfetch\s*\(/, /XMLHttpRequest/, /WebAssembly/, /new Function\s*\(/, /\beval\s*\(/, /new (Shared)?Worker\s*\(/, /\bimport\s*\(/, /requestFullscreen/, /window\.open\s*\(/, /navigator\.(clipboard|geolocation|serviceWorker)/, /devicemotion|deviceorientation/i, /https?:\/\/(?!www\.w3\.org)[\w.-]+\/[^\s"'`)]*\.(js|css|png|jpg|glb|mp3|woff2?)/]);
    scan("game.js", js, [/x\.com\/|twitter\.com/i]); scan("index.html", html, [/x\.com\/|twitter|@op7418/i]); scan('index.html', html, [/<script(?![^>]*\bsrc=)[^>]*>/, /type="module"/, /\son\w+="/, /target="_blank"/, /<iframe|<object|<base /, /(src|href)="https?:/, /url\(https?:/, /javascript:/]);
    const types = new Set(); const walk = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { const f = path.join(d, e.name); if (e.isDirectory()) walk(f); else types.add(path.extname(f).toLowerCase()); } }; walk(OUT);
    const okT = new Set(['.html', '.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.woff', '.woff2', '.json']); for (const t of types) if (!okT.has(t)) bad.push('file type not allowed: ' + t);
    fs.rmSync(ZIP, { force: true }); execFileSync('zip', ['-q', '-r', '-9', path.resolve(ZIP), '.', '-x', '*.DS_Store'], { cwd: OUT });
    log('\ncode', kb(js.length), '| data scripts', kb(nData), '| zip', (fs.statSync(ZIP).size / 1048576).toFixed(2), 'MiB', '| file types', [...types].join(' '));
    if (big.length) log('base64 over 1 MiB:', big.join(', ')); log(bad.length ? 'STATIC GATE FAILED:\n  ' + bad.join('\n  ') : 'static gate: clean');
    
  • scripts/build_single_html.mjs8.9 KB1ba570fe3ff0upstream ↗
    // Build a single self-contained HTML (dist/wusuo.html) and a static site (dist/site/): node tools/build.mjs   (run from game/)
    // 1. shrink assets (textures -> webp at a sane size, strip meshes from animation-only files, meshopt geometry, re-encode music)
    // 2. bundle the modules with esbuild, 3. inline everything as data URLs into dist/wusuo.html
    import fs from 'node:fs'; import path from 'node:path'; import { execFileSync } from 'node:child_process';
    import { NodeIO } from '@gltf-transform/core'; import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
    import { textureCompress, dedup, prune, meshopt, reorder } from '@gltf-transform/functions'; import { EXTMeshoptCompression } from '@gltf-transform/extensions'; import { MeshoptEncoder } from 'meshoptimizer'; import sharp from 'sharp'; import { build } from 'esbuild';
    
    const OUT = 'dist', OPT = OUT + '/opt'; fs.mkdirSync(OPT, { recursive: true }); await MeshoptEncoder.ready;
    const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.encoder': MeshoptEncoder });
    const J = (f) => JSON.parse(fs.readFileSync(f, 'utf8')); const A = {}; let raw = 0;
    const SITE = OUT + '/site';          /* the same shrunk assets as separate files, for static hosting (GitHub Pages): the page can draw before they finish downloading */
    fs.rmSync(SITE, { recursive: true, force: true });
    const put = (key, buf, mime) => { A[key] = `data:${mime};base64,` + buf.toString('base64'); raw += buf.length; const o = path.join(SITE, key); fs.mkdirSync(path.dirname(o), { recursive: true }); fs.writeFileSync(o, buf); };
    const cached = async (key, src, make) => { const o = path.join(OPT, key.replace(/[\/]/g, '__')); if (!fs.existsSync(o) || fs.statSync(o).mtimeMs < fs.statSync(src).mtimeMs) fs.writeFileSync(o, await make()); return fs.readFileSync(o); };
    const NOGEO = process.argv.includes('--no-meshopt');
    
    async function glb(rel, { tex = 1024, animOnly = false, geo = true, skinned = false, hd = false } = {}) {
      const src = 'assets/' + rel; const buf = await cached(rel + (animOnly ? '.anim' : '') + '.' + tex + (geo && !NOGEO ? (skinned ? '.mf' : '.mo') : ''), src, async () => {
        const d = await io.read(src); if (animOnly) for (const n of d.getRoot().listNodes()) { n.setMesh(null); n.setSkin(null); }
        await d.transform(dedup(), prune({ keepLeaves: true, keepAttributes: true }), textureCompress({ encoder: sharp, targetFormat: 'webp', resize: [tex, tex], quality: 82 }));
        /* skinned characters: meshopt-pack the buffers but do NOT quantise. Quantisation rescales the mesh and parks the inverse on the armature, so the packed game measured a different body height and preset clips (which carry scale tracks) shrank the character */
        if (geo && !NOGEO && !animOnly && skinned) { await d.transform(reorder({ encoder: MeshoptEncoder })); d.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE }); }
        else if (geo && !NOGEO && !animOnly) await d.transform(meshopt({ encoder: MeshoptEncoder, level: 'medium' }));
        return Buffer.from(await io.writeBinary(d)); });
      if (hd) { const o = path.join(SITE, 'assets-hd', rel); fs.mkdirSync(path.dirname(o), { recursive: true }); fs.writeFileSync(o, buf); hdBytes += buf.length; return buf.length; }          /* the sharper set exists only in the hosted site, loaded when the player asks for it */
      put('assets/' + rel, buf, 'model/gltf-binary'); return buf.length;
    }
    let hdBytes = 0; const log = (...a) => console.log(...a); const mb = (n) => (n / 1e6).toFixed(2) + 'MB';
    // ---- models
    const chars = J('assets/chars.json'), props = J('assets/props.json'), loot = fs.existsSync('assets/loot.json') ? J('assets/loot.json') : {};
    for (const [k, c] of Object.entries(chars)) { if (k === 'weapons') { for (const f of Object.values(c)) log('weapon', f.split('/')[1], mb(await glb(f, { tex: 1024 }))); continue; }
      log(k, mb(await glb(c.files[0], { tex: 1536, skinned: true })), 'anim', mb(c.files[1] ? await glb(c.files[1], { animOnly: true }) : 0)); }
    for (const [k, f] of Object.entries(props)) log('prop', k, mb(await glb(f, { tex: k === 'gate' || k === 'hall' || k === 'tree' ? 1536 : 1024 })));
    for (const [k, f] of Object.entries(loot)) log('loot', k, mb(await glb(f, { tex: 512 })));
    for (const f of ['chars.json', 'props.json', 'loot.json']) if (fs.existsSync('assets/' + f)) put('assets/' + f, fs.readFileSync('assets/' + f), 'application/json');
    // ---- optional high-resolution set for the hosted site: same files, textures twice the edge length (everything the URL switch redirects must exist here too)
    for (const [k, c] of Object.entries(chars)) { if (k === 'weapons') { for (const f of Object.values(c)) await glb(f, { tex: 2048, hd: true }); continue; } await glb(c.files[0], { tex: 2048, skinned: true, hd: true }); if (c.files[1]) await glb(c.files[1], { animOnly: true, hd: true }); }
    for (const [k, f] of Object.entries(props)) await glb(f, { tex: 2048, hd: true }); for (const [k, f] of Object.entries(loot)) await glb(f, { tex: 512, hd: true });
    for (const f of fs.readdirSync('assets/tex').filter((f) => /\.jpg$/.test(f))) { const o = path.join(SITE, 'assets-hd/tex', f); fs.mkdirSync(path.dirname(o), { recursive: true }); const b = await cached('texhd_' + f, 'assets/tex/' + f, () => sharp('assets/tex/' + f).resize(2048, 2048, { fit: 'inside' }).jpeg({ quality: 84 }).toBuffer()); fs.writeFileSync(o, b); hdBytes += b.length; }
    log('hd set', mb(hdBytes));
    // ---- textures, ui, audio
    for (const f of fs.readdirSync('assets/tex').filter((f) => /\.jpg$/.test(f))) put('assets/tex/' + f, await cached('tex_' + f, 'assets/tex/' + f, () => sharp('assets/tex/' + f).resize(1024, 1024, { fit: 'inside' }).jpeg({ quality: 80 }).toBuffer()), 'image/jpeg');
    put('assets/fx/ink.jpg', fs.readFileSync('assets/fx/ink.jpg'), 'image/jpeg');
    for (const f of fs.readdirSync('assets/ui')) if (/\.(png|jpg)$/.test(f)) put('assets/ui/' + f, f === 'title.png' ? await cached('ui_title', 'assets/ui/title.png', () => sharp('assets/ui/title.png').png({ palette: true, colours: 64 }).toBuffer()) : fs.readFileSync('assets/ui/' + f), f.endsWith('png') ? 'image/png' : 'image/jpeg');
    for (const f of fs.readdirSync('assets/sfx').filter((f) => f.endsWith('.mp3'))) put('assets/sfx/' + f, fs.readFileSync('assets/sfx/' + f), 'audio/mpeg');
    for (const dir of ['music', 'voice']) if (fs.existsSync('assets/' + dir)) for (const f of fs.readdirSync('assets/' + dir).filter((f) => f.endsWith('.mp3'))) {
      const src = `assets/${dir}/${f}`; put(src, dir === 'voice' ? fs.readFileSync(src) : await cached(dir + '_' + f, src, () => { const o = path.join(OPT, 'tmp_' + f); execFileSync('ffmpeg', ['-y', '-v', 'error', '-i', src, '-ac', '2', '-b:a', '88k', o]); const b = fs.readFileSync(o); fs.unlinkSync(o); return b; }), 'audio/mpeg'); }
    log('assets raw', mb(raw), 'files', Object.keys(A).length);
    // ---- code
    const r = await build({ entryPoints: ['src/game.js'], bundle: true, format: 'esm', minify: true, write: false, target: 'es2022', legalComments: 'none',
      alias: { three: './vendor/three/build/three.module.js' }, plugins: [{ name: 'addons', setup(b) { b.onResolve({ filter: /^three\/addons\// }, (a) => ({ path: path.resolve('vendor/three/jsm', a.path.slice('three/addons/'.length)) })); } }] });
    const js = r.outputFiles[0].text; log('code', mb(js.length));
    // ---- html
    let html = fs.readFileSync('index.html', 'utf8');
    { const i0 = html.indexOf('<script type="module">'), i1 = html.indexOf('</script>', i0) + 9; const site = html.replace(/<script type="importmap">[\s\S]*?<\/script>/, '<meta name="hd-assets" content="assets-hd">');
      const j0 = site.indexOf('<script type="module">'), j1 = site.indexOf('</script>', j0) + 9; const tag = 'game.' + (await import('node:crypto')).createHash('md5').update(js).digest('hex').slice(0, 8) + '.js';
      fs.writeFileSync(SITE + '/' + tag, js); fs.writeFileSync(SITE + '/index.html', site.slice(0, j0) + `<script type="module" src="${tag}"></script>` + site.slice(j1)); fs.writeFileSync(SITE + '/.nojekyll', '');
      const sz = (d) => fs.readdirSync(d, { withFileTypes: true }).reduce((n, e) => n + (e.isDirectory() ? sz(path.join(d, e.name)) : fs.statSync(path.join(d, e.name)).size), 0); log('wrote', SITE, mb(sz(SITE)), 'code', tag); }
    html = html.replace(/<script type="importmap">[\s\S]*?<\/script>/, '').replace(/assets\/ui\/[\w.]+/g, (m) => A[m] || m);
    const shim = `window.__A=${JSON.stringify(A)};(()=>{const A=window.__A,k=u=>String(u).replace(/^\\.\\//,'').split('?')[0],f=window.fetch.bind(window);window.fetch=(u,o)=>{if(typeof u!=='string')return f(u,o);const key=k(u);return A[key]?f(A[key]):key.startsWith('assets/')?Promise.resolve(new Response('',{status:404})):f(u,o)}})();`;
    const i0 = html.indexOf('<script type="module">'), i1 = html.indexOf('</script>', i0) + 9;
    html = html.slice(0, i0) + '<script>' + shim.replace(/<\/script/g, '<\\/script') + '</script>\n<script type="module">' + js.replace(/<\/script/g, '<\\/script') + '</script>' + html.slice(i1);
    fs.writeFileSync(OUT + '/wusuo.html', html); log('wrote', OUT + '/wusuo.html', mb(fs.statSync(OUT + '/wusuo.html').size));
    
  • scripts/input.js2.9 KBceb091386ae7upstream ↗
    // Keyboard and mouse state that survives lost key-up events, plus an F3 panel for reporting input problems.
    // Usage: import { keys, pressed, mouse, endFrame, debugPanel } from './input.js';  call endFrame() once per frame.
    export const keys = new Set(), pressed = new Set(), mouse = { x: 0, y: 0 };
    const OPP = { KeyW: 'KeyS', KeyS: 'KeyW', KeyA: 'KeyD', KeyD: 'KeyA' }; let log = [];
    const note = (s) => { log.push(s); log = log.slice(-8); };
    addEventListener('keydown', (e) => {
      if (e.isComposing || e.keyCode === 229) return;                                   // input method is composing: not ours
      if (/^(Meta|Alt|Control)/.test(e.code)) { keys.clear(); return; }                 // shortcuts swallow key-ups: start clean
      if (e.metaKey || e.altKey || e.ctrlKey) return;
      if (!e.repeat) { note('↓' + e.code); if (OPP[e.code]) keys.delete(OPP[e.code]); } // pressing a direction drops a phantom opposite
      if (!keys.has(e.code)) pressed.add(e.code); keys.add(e.code);
      if (e.code === 'Space' || e.code === 'Tab') e.preventDefault();
    });
    addEventListener('keyup', (e) => { note('↑' + e.code); keys.delete(e.code); if (/^(Meta|Alt|Control)/.test(e.code)) keys.clear(); });
    for (const ev of ['blur', 'focus', 'pagehide']) addEventListener(ev, () => { note('[' + ev + ']'); keys.clear(); });
    document.addEventListener('visibilitychange', () => keys.clear());
    addEventListener('mousemove', (e) => { if (!(e.buttons & 2)) keys.delete('RMB'); mouse.x = e.clientX / innerWidth * 2 - 1; mouse.y = -(e.clientY / innerHeight) * 2 + 1; });
    addEventListener('mousedown', (e) => { if (e.button === 0) pressed.add('LMB'); if (e.button === 2) { pressed.add('RMB'); keys.add('RMB'); } });
    addEventListener('mouseup', (e) => { if (e.button === 2) keys.delete('RMB'); });
    addEventListener('contextmenu', (e) => e.preventDefault());
    export function endFrame() { pressed.clear(); }
    // Shift is deliberately not in the modifier list: games use it as a sprint key, and clearing on it would kill movement.
    // Do NOT infer releases from missing auto-repeat events (the OS repeats only the most recently pressed key),
    // and do not poll document.hasFocus() to clear keys (unreliable inside embedded browsers).
    
    // F3 toggles a small panel; pass a function returning extra lines (state, speed, distance to the boundary...).
    export function debugPanel(extra = () => '') {
      const d = document.createElement('div'); d.style.cssText = 'position:fixed;left:8px;top:60px;z-index:99;font:11px ui-monospace,Menlo,monospace;color:#9fe0c0;background:rgba(0,0,0,.55);padding:6px 8px;white-space:pre;display:none;pointer-events:none'; document.body.appendChild(d);
      addEventListener('keydown', (e) => { if (e.code === 'F3') { e.preventDefault(); d.style.display = d.style.display === 'none' ? 'block' : 'none'; } }, true);
      return () => { if (d.style.display !== 'none') d.textContent = `held: ${[...keys].join(' ') || '-'}\nfocus: ${document.hasFocus()}\n${extra()}\nrecent: ${log.join(' ')}`; };
    }
    
  • scripts/serve.mjs1.0 KB3523a974fba3upstream ↗
    // Tiny static server for local play: node game/serve.mjs
    import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url';
    const root = path.dirname(fileURLToPath(import.meta.url)); const port = +process.env.PORT || 5173;
    const T = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.glb': 'model/gltf-binary', '.png': 'image/png', '.jpg': 'image/jpeg', '.css': 'text/css' };
    http.createServer((q, s) => {
      let p = decodeURIComponent(q.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html'; const f = path.join(root, p);
      if (!f.startsWith(root)) { s.writeHead(403); return s.end(); }
      fs.readFile(f, (e, d) => { if (e) { s.writeHead(404); return s.end('not found'); } s.writeHead(200, { 'content-type': T[path.extname(f)] || 'application/octet-stream', 'cache-control': 'no-store' }); s.end(d); });
    }).listen(port, '127.0.0.1', () => console.log('serving ' + root + ' on http://localhost:' + port));
    
  • references/assets.md3.4 KB03727defa60aupstream ↗
    # 素材:模型、图片、配音、配乐
    
    ## 总原则
    - 先问用户有哪些生成工具和免费素材库可用,先读工具的帮助和报价命令。
    - 氛围要统一:先出一批设定图(角色、场景分区、道具总览、界面风格),所有后续素材照着它们做。图片便宜,多出几张。
    - 每个素材脚本都要可续跑:记录提交编号和状态,失败后重跑不重复扣费。
    
    ## 3D 模型(Tripo 一类的图生 3D)
    1. **设定图**:图片模型出"单独一件物体、完整入画、纯浅灰无缝背景、均匀棚拍光、无投影无文字无人物、**没有任何光效粒子特效**"。带特效的图会被建成实体面片。
    2. **图生 3D**:道具用便宜档模型加面数上限(道具约 5000–8000 面),角色用多视图加绑骨。
    3. **角色需要三视图**(正、侧、背),而且要检查侧面图是不是真的正侧面。
    4. 小物件(掉落物、武器)单独生成,不要指望它们长在角色模型上还能动。
    5. 生成的模型**朝向不固定**,不能假设面朝 +Z。角色按左右髋骨位置算朝向,武器按包围盒最长轴对齐。
    
    参考花费(因平台而异,仅供量级参考):道具每个约 30 积分;角色多视图约 120、绑骨约 25、每个预设动作约 10。
    
    ## 贴图和免费素材
    - 地面、石头、泥土用 CC0 材质库(例如 Poly Haven)的整套贴图(颜色、法线、粗糙度)。
    - 植被用实例化网格自己铺(十几万丛草没问题),不要一棵棵摆模型。
    
    ## 图片(界面素材)
    - 技能图标:一次出一排同风格的圆形图标,黑底,之后裁切。补图标时把风格描述原样复用。
    - 标题字:出一张带书法标题的海报,按亮度阈值把字抠出来当透明图层,叠在实时场景上。
    - **不要用生成图当血条**。血条、进度条用代码画(见 `vfx-ui-audio.md`),贴图血条一眼就显得廉价。
    - 生成的装饰框经常风格跑偏(要国风却出了西式恶魔风),不合适就不用。
    
    ## 配音
    - 优先找平台的**专用配音模型**(按文字描述音色的那种)。实测每条约 12 积分;同样的事走视频模型约每 12 秒 240 积分。
    - 提示词格式:`音色:<年龄、性别、身份、共鸣、语速、情绪>。无背景音乐,无环境音。台词:<台词>`。先生成一条,检查时长确认模型只念了台词、没把描述念出来。
    - 生成的原始音量可能很低。处理顺序是**先把峰值拉到 -2dB,再裁首尾静音**;反过来会把轻声的台词当静音裁掉。
    - 字幕文本到语音文件做一张映射表,说话时把配乐压低。
    
    ## 配乐和环境音
    - 让用户用音乐模型(例如 Suno)生成,你提供提示词:探索、小怪战、Boss 战各一首,写清楚乐器、调式、速度、"纯器乐、无人声、可无缝循环"。
    - 代码里预留文件位(`assets/music/explore.mp3` 等),有文件就用、没有就退回到代码生成的简单配乐,三首之间按战斗状态交叉淡入。
    - 有了录制的环境音就关掉合成的风声,不要叠在一起。
    
    ## 音效
    - 用 CC0 音效包(例如 OpenGameArt),记录来源。挥剑、命中、金属碰撞、怪物叫声、石头碎裂各准备 3 个以上变体,播放时随机挑并微调音高。
    - 合成音只用来补缺(提示音、低频冲击)。不要把"火球"类采样当成火苗声循环播,会变成滋啦滋啦的噪音。
    
  • references/characters-animation.md2.9 KBe317533e8c79upstream ↗
    # 角色与动作
    
    ## 接入生成的角色模型
    - 载入后先摆回绑定姿势,量包围盒算缩放,把脚底对到地面。
    - 朝向:用左右大腿骨的世界位置求"右方向",叉乘出"前方向",得到模型需要补的偏航角。
    - 记下骨骼名和静止姿态(世界位置、世界旋转),后面所有动作都基于它。
    
    - 碰撞半径和判定范围写在数据里,不要从模型尺寸推:换模型不应该改变手感。
    
    ## 平台预设动作(走、跑、受击、倒地)
    - **预设动作自带位移**。只把根骨骼的位置轨道清零是错的:髋骨的父节点通常有倾斜,要先变换到模型空间,把水平分量钉在静止值,保留上下起伏,再变换回去。症状是"角色被甩到脚下光圈外一米""看起来一直往一边走"。
    - 每个预设动作的朝向可能和绑定姿势差 90 度,载入时逐个测量并记下来,播放时补回去。
    - 只用来取动作的那份文件,打包时可以去掉里面的网格和贴图(见 `packaging.md`)。
    
    ## 自己做招式:不要猜关节角度
    猜欧拉角一定会得到扭曲的姿势。可靠的做法:
    
    - 在**角色空间**里写姿势:+Y 向上,+Z 向前,单位米,右手在 -X。
    - 每个关键姿势指定:髋的位移、脊柱和头的转角、**手的目标位置**、**剑的指向**、**脚的落点**。
    - 手臂和腿用两段骨骼解算(给一个肘、膝的朝向提示),手腕再转到让剑指向目标方向。
    - 把关键姿势烘焙成动画片段,这样可以和预设动作一样交叉淡入。
    - 做一个**数值探针**:打印某一帧各关节相对角色根的位置,用数字核对"手是不是在肩膀前面""脚是不是在地上",再配一个单独的展示页近景截图。
    
    ## 让动作有分量
    一招至少五个关键姿势:起手 → **蓄势停顿**(比起手更深一点,停 0.08 秒左右)→ 快速挥出(用四次方缓出)→ **随势过冲** → 把武器收回待机姿势。只有"起手、挥出、回位"三拍的动作看起来就是僵的。
    
    - 起止姿势用战斗待机姿势,不要用别的姿势,否则连招之间会跳。
    - 判定帧(伤害生效的时间段)要和挥出的那一拍对齐,改了关键帧就要同步改判定表。
    - 大体型角色起身、倒地要专门做:头先动,重心压到支撑物上,腿发力,上身最后跟上。两个差别很大的姿势之间不要用 0.1 秒的淡入硬切,看起来像"折叠展开"。
    
    ## 待机与武器
    - 非战斗待机是自然站姿,武器在背上;出手前有拔剑;脱战几秒后收剑。一直端着武器站着,用户会说僵。
    - 武器模型挂在手骨下的一个节点上,另做一个背部挂点,切换时换父节点。
    - 格挡姿势武器要贴近身体斜架,伸得太远会显得假。
    
    ## 没做但值得做
    宽袖、长发、披风跟着骨骼硬动会显得死。有余力加弹簧骨骼。
    
  • references/combat-feel.md4.0 KBa28c327d04aeupstream ↗
    # 战斗:打击感、交互、镜头
    
    目标是"和怪打得有来有回",不是割草。下面每一条都是为了让玩家和敌人的动作互相影响。
    
    ## 让攻击真的打中
    - **攻击吸附**:出手时在瞄准线附近选最近的敌人(距离加角度偏差加权),转向它,并滑步到"刚好够得着"的距离。每帧把剩余滑步距离和"到目标的距离减去站位"取小,这样永远不会冲过头。俯视角 3D 距离感不准,没有吸附就会一直擦着敌人过去。
    - **身体有体积**:玩家和敌人互相推开,闪避和飞行状态除外。
    
    ## 命中反馈
    - **顿帧按角色做,不做全局**:命中时攻击方和受击方各自定格几帧(轻击约 0.06–0.09 秒,重击约 0.1–0.13 秒),受击方加抖动,其余敌人照常行动。全局减速会让整个场面发黏。
    - 顿帧期间的输入要缓冲(下一段攻击、闪避、反击),不然玩家会觉得按键被吃。
    - **击退和硬直分级**:轻击小退,重击大退;高韧性敌人被轻击只晃一下,每隔几下才硬直。
    - 火花出在接触点并沿挥砍方向飞,不要出在敌人中心向四周散。
    
    ## 格挡、弹反、反击
    - 按住格挡:正面有效,按伤害扣体力,体力打空破防。范围技(砸地、落雷、地面喷发)不可格挡,逼玩家用闪避。
    - 弹反:举剑后约 0.24 秒内接住,不耗体力,对方长硬直,对 Boss 涨破势条。
    - **格挡成功后开一个反击窗口**(约 0.85 秒,弹反后更长):脚下亮环、按键图标提示,点攻击键触发处决动作(瞬移到身前、短暂慢镜头、大伤害、放一道剑气)。这是"有来有回"里最爽的一环。
    - 打断:在敌人抬手后半段命中它,直接破招,长硬直加伤害加成。
    - 闪避穿过本来会命中的攻击:短暂慢动作,回资源。
    
    ## 闪避优先级最高
    闪避要能打断出招(任意时刻)、施法、格挡、喝药,也能切断顿帧。只有受击硬直和大招期间不能闪。
    
    ## 怪物
    - **少而耐打**:每波三四个,血量够挨四五下。八个一刀一个的怪会变成割草。
    - **同一时间只有一个近战出手**,其余在外圈游走。
    - 给每种怪一个"会回应玩家"的行为:二连击、架开轻击后立刻反击、远程读条后的弹幕和地面预警。
    - 一定要有远程怪,而且它的弹幕可以被砍掉。
    - 敌人的预警要有足够的反应时间,并且预警图形本身要做成特效(见 `vfx-ui-audio.md`)。
    
    ## 难度
    先调到自己的自动测试脚本"只会乱按攻击"也能撑一阵。第一版几乎总是太难:降敌人伤害、加玩家血量和受击后的无敌时间,比削弱敌人行为更安全。
    
    ## 镜头
    - 缩放范围锁窄(例如 0.95–1.3 倍),不要随距离大幅拉近拉远。
    - **给焦点加缰绳**:焦点离主角最多三四米。Boss 战里把焦点往 Boss 偏一点可以,但主角必须始终在画面中间一带。
    - 鼠标对镜头的牵引要很小。
    - 过场镜头结束时,目标位置直接设成游戏镜头的位置,等它几乎到位再交还控制,并且交还后跟随速度从慢渐快。否则会有一下跳切。
    - 镜头位置每帧和地形高度取大,避免钻进山体。
    - 挡在镜头和主角之间的高大物体(门楼、树、柱子、亭子)自动变半透明:算物体到"镜头—主角"连线的水平距离,小于半径就淡出。
    
    ## 场地
    - 战斗区域用"若干圆的平滑并集加噪声边缘",不要规整的圆。场内放有碰撞的石头、断柱、树做分割。
    - 相邻障碍物的圆形碰撞叠在一起会形成凹角挂住人,连成一排的障碍用一条胶囊形碰撞。
    - **关闭一块可走区域前**(例如 Boss 开场封住来路),先把主角放到确定安全的位置。否则他可能被留在一小块不连通的区域里动不了。
    - 做一个全图扫描测试:网格取点,八个方向各推进几十帧,再从停下的位置试能不能离开,用来确认没有卡死点。
    
  • references/packaging.md6.9 KBc2317fb34c6aupstream ↗
    # 压缩并打包成单个 HTML
    
    目标:一个双击就能打开、不需要服务器和网络的 HTML。实战结果:资源从约 98MB 压到约 21MB,成品约 30MB。
    
    配套脚本 `scripts/build_single_html.mjs` 是那次项目用的原样脚本,按你的目录和清单文件改一下就能用。依赖:`@gltf-transform/core`、`@gltf-transform/extensions`、`@gltf-transform/functions`、`meshoptimizer`、`sharp`、`esbuild`,以及系统里的 `ffmpeg`。
    
    ## 体积都在哪
    生成的模型每个带一张 4096 的贴图(3MB 以上)加两三兆几何数据;角色还各有一份"只为取动作"的重复文件。所以:
    
    1. **贴图**:缩到 1024(主角、Boss、大建筑 1536,掉落物 512),转 WebP。这一步省得最多。
    2. **只用来取动作的文件**:把所有节点上的网格和蒙皮引用清掉再裁剪,只留骨骼节点和动画。裁剪时要保留叶子节点,否则骨骼会被当成空节点删掉。
    3. **几何**:meshopt 压缩。运行时给模型加载器挂上对应的解码器(开发环境挂上也无害)。
    4. **地面贴图**:缩到 1024。
    5. **配乐**:重编码到 88kbps 左右。
    6. 压缩结果按"源文件修改时间"做缓存,重复打包只要几秒。
    
    ## 怎么内嵌
    - 用 esbuild 把入口模块打成一个压缩过的模块脚本,把 `three` 和扩展模块的引用解析到项目里的本地副本。
    - 所有资源转成 data URL,放进一个全局表 `window.__A = { "assets/...": "data:..." }`。
    - 两处接管:
      - 包一层 `fetch`:路径在表里就改取 data URL;以 `assets/` 开头但不在表里的返回 404(可选资源不存在时不报错)。
      - 给 three 的默认加载管理器设网址改写函数,贴图和模型加载器就都走这张表。
    - HTML 里的 `<img src>` 和样式里的 `url(...)` 在打包时直接替换成 data URL。
    - 内嵌脚本里的 `</script` 要转义。
    
    ## 验证
    - 打开成品,确认**网络请求数为 0**(过滤掉 data URL 后列出资源条目)。
    - 至少进一场战斗,确认角色、动作、贴图、界面图标、声音都在。几何压缩带量化,理论上可能影响蒙皮,逐个角色看一眼。
    - 让用户在自己机器上双击打开验证一次;自动化浏览器工具不一定能打开本地文件路径。
    
    ## 在线托管:先出画面,再加载
    
    单文件适合发给人;挂到网上(GitHub Pages 之类)时改用多文件站点,否则访客要等整个文件下完才看到东西。`build_single_html.mjs` 的同一批压缩产物另写一份到 `dist/site/`,代码单独一个带哈希的 js。
    
    启动顺序按"需要什么才能画出第一帧"来排,而不是全部 `await` 完再开渲染循环:
    
    1. HTML 里直接放标题图和进度条,脚本没到也有东西看。
    2. 天空、地面、草、天气这些纯代码的东西先建好,等地表贴图到了就淡入并开始渲染循环(单独一个不依赖角色的 `pre()` 帧函数,镜头缓慢游移)。
    3. 场景模型和角色同时下载。场景模型到齐就摆放,用一秒从地面长出来,由近到远错开,掩盖突然出现。
    4. 角色到齐后切换到正式的帧函数,再显示"点击开始"。
    5. 音乐等到点击开始之后再取。
    
    进度条按文件数走即可(`loadGLB` 里计数),每到一个文件显示一行文案,用队列保证每行至少停留 0.17 秒,否则本地加载时一闪而过。文案可以贴合题材,旁边用小字写真实在做的事("立山门 · 山门模型"),既有趣又不骗人。
    
    实测参考:22MB 站点,限速约 20Mbps 时,脚本到达后约 1 秒出第一帧,全部就绪约 10 秒;在此期间画面一直在动。
    
    ## 带骨骼的角色不要做网格量化
    
    `meshopt()` 默认会量化顶点:把网格缩放到整数范围,再把反向缩放放到骨架节点上。静态摆件没问题,带骨骼的角色会出两个错:按包围盒算身高的代码量到的是另一个空间的尺寸;平台预设动画每个节点都带"缩放 = 1"的轨道,一播放就把那个补偿缩放抹掉,角色当场缩小。症状是"开发版正常,打包版一跑动人就变小"或"Boss 只有一半高"。
    
    做法:角色只做 `reorder` 加 `EXT_meshopt_compression`(不调用 `quantize`),体积比量化大三四成,但行为与未打包版一致。加载动画时顺手丢掉 `.scale` 轨道。
    
    打包后必须逐个角色对比开发版和打包版的同一组数字(头部高度、根节点缩放、跑动时手脚摆幅),不能只看"能进游戏、没报错"。
    
    ## 手机与受限容器(小程序、小工具类平台)
    
    触屏适配放在游戏本体里,所有构建共用:
    - 左半屏按下的位置出现浮动摇杆,直接给移动向量加模拟量;技能图标本身变成右下角的按钮,按住类(格挡、冲刺)在 `pointerup / pointercancel / pointerleave` 都要松开。
    - 触屏模式下忽略鼠标事件,否则每次点摇杆都会触发一次"左键攻击"。
    - 手机没有鼠标指向:瞄准点取最近的敌人,其次摇杆方向,再次角色朝向。
    - 竖屏横向视野太窄,把镜头视角从 36° 放到 50° 左右并稍微拉远;血条挪到顶部,底部留给拇指。
    - 安全区不要写 `var(--x, env(...))`:旧内核不认识 `env()`,整条声明在计算时失效且不会回退到上一条。用脚本把值解析成普通长度写进自定义属性。
    - 绘制缓冲区按像素预算封顶(`min(dpr, 1.5, sqrt(预算 / (宽×高)))`),掉帧时依次降分辨率、关阴影、关泛光、减草;页面隐藏时停循环,处理 `webglcontextlost`,不支持 WebGL 2 时给出说明而不是白屏。
    
    平台容器常见的硬限制和对应做法(以小红书小工具为例,其它平台先读它自己的规范):
    
    | 限制 | 做法 |
    |---|---|
    | 不能 `fetch` / XHR | 打包时把 `fetch` 整体改写成本地查表函数(esbuild `define`),数据放进按需插入的经典脚本 |
    | 只允许网页常规文件类型(没有 .glb / .mp3) | 模型拆成 glTF JSON + base64 缓冲区放进 .js,运行时在内存里拼成 GLB 交给解析器;贴图抽成独立 .webp;音频用 base64 交给 `decodeAudioData` |
    | 不能用 WASM | 不用 meshopt / Draco 解码器;用构建期减面 + 把法线、UV、权重存成归一化整数(位置保持浮点) |
    | 脚本必须外置、不能是模块 | esbuild `format: 'iife'`,`target: ['es2017','chrome61']`,HTML 里只留一个 `<script src>` |
    | 包体上限(10MiB) | 角色减到一万面以内、贴图 512、长动画隔帧抽样、音乐降到单声道低码率 |
    | three.js 的 GLTFLoader 会用 `createImageBitmap` + fetch 读贴图 | 打包时把 `createImageBitmap` 定义成 `undefined`,让它退回 `<img>` 加载 |
    
    打包脚本末尾加一道静态扫描(禁用 API 的字样、内联脚本、外链、不允许的文件类型),不通过就不出包。浏览器里能跑不代表容器里能跑,交付时要写明哪些只在浏览器验证过。
    
  • references/pitfalls.md3.3 KBf3d6f9f460bfupstream ↗
    # 踩坑清单(按症状查)
    
    ## 游戏打不开、一直"载入中"、点击没反应
    - **先看浏览器控制台**,不要先猜网络。最常见的是脚本语法错误导致入口模块根本没执行。
    - 如果代码是"一行很长"的风格,**行尾不能加 `//` 注释**,它会吞掉同一行后面的代码。用 `/* */`。
    - `node --check 文件.js` 对带 `import` 的模块文件可能查不出错。用 `node --input-type=module --check < 文件.js`。
    - 不要依赖外网加载库。把 three.js 和用到的扩展模块放进项目里。
    
    ## 角色一直往一边走、身体不在脚下光圈上
    预设动作的根位移没去干净。见 `characters-animation.md`。
    
    ## 按键相关(这一类最容易越修越坏)
    - **松手后角色还在走 / 贴墙卡住几秒**:某个方向键的松开事件丢了(按住 Cmd 或 Alt 时、切窗口时都会丢),那个键一直留在"按住"集合里。
      - 有效的修法:按下一个方向键时,把它的反方向键从集合里删掉;任何修饰键按下或松开、窗口失焦或重新聚焦时清空集合。
      - 清空规则里的修饰键只包括 Cmd、Alt、Ctrl,**不要把 Shift 算进去**:Shift 常被用作冲刺或飞行键,算进去会让按 Shift 时方向键全部失效。
      - **不要**用"没收到按键重复事件"来推断松键。系统只对最后按下的那个键发重复事件,先按住的键会被误杀,表现为"按着突然停""同时按两个键只走一个方向"。
      - **不要**每帧轮询窗口是否有焦点来清空按键,在内嵌浏览器里这个值不可靠。
    - 抓不到原因时,加一个调试面板(例如按 F3):显示当前按住的键、角色状态、速度、离边界距离、焦点、最近八次按键事件。让用户在出问题时截图。**一张截图就能分清是按键丢了还是逻辑问题**。
    - 鼠标右键按住的状态要在鼠标移动事件里用 `buttons` 重新同步。
    
    ## 贴墙、进场后动不了
    - 关闭可走区域时把人留在了孤岛上。见 `combat-feel.md` 的"场地"。
    - 碰撞解不开时退回上一帧位置,永远不接受一个非法位置。
    
    ## 画面
    - 特效一片白:泛光过曝,降颜色峰值。
    - 草叶被拉成长条:弯曲量要除以实例的水平缩放。
    - 镜头钻进山体或被建筑挡死:见 `combat-feel.md` 的"镜头"。
    - 过场结束镜头跳一下:过场终点没有对齐游戏镜头。
    - 给透明度做过渡的遮罩在后台标签页里不走时间,自动测试截到黑屏不代表坏了,查计算后的样式值。
    
    ## 测试
    - 标签页隐藏时不渲染,要用手动推进帧的钩子。
    - 逐帧推进后截图偶尔是旧画面,以状态数值为准。
    - 测试脚本里用定时器的逻辑(例如延迟释放)要改成按游戏时间判断,否则手动推进时不触发。
    - 自动测试页会出声,默认静音,测完切回标题页。
    - 你和用户可能共用同一个浏览器标签页,你在里面导航会打断用户。
    
    ## 流程
    - 用户提供了生成工具却不用,自己拼素材 → 整版被推翻。
    - 没看参考就开工 → 整版被推翻。
    - 说"完成了"但没实际看过 → 用户一打开就发现问题,信任下降。
    - 生成工具低于确认阈值时会直接扣费不询问,批量提交前自己先算总数。
    
  • references/vfx-ui-audio.md4.1 KB025128b2826aupstream ↗
    # 特效、掉落物、界面、音量
    
    ## 渲染底座(先把它搭好,后面所有东西才显得贵)
    半浮点场景缓冲加深度图 → 环境光遮蔽 → 采样阴影图的体积雾(点光源带光晕)→ 多级泛光 → 调色(色调映射、分离色调、暗角)→ 抗锯齿和轻微颗粒。夜景配一盏冷色主光加若干暖色点光。
    
    天气用"跟随镜头的盒子里循环的粒子":雪(点精灵)、贴地薄雾和风线(实例化面片),全图都有天气但只模拟镜头附近。标题画面直接显示实时场景。地面着色器里加一层成片的积雪(噪声控制分布,积水和陡坡上没有),第一版通常盖得太满,要调薄。
    
    ## 技能特效:常规流程
    1. **先定节奏**:蓄力 → 爆发 → 残留和消散。只有"啪一下"的特效没有分量。
    2. **三样材料**:网格决定形状和轨迹,噪声给细节,着色器做滚动、侵蚀、调色。
    3. **不要用一张贴图盖在面片上**。那是用户说"死板、廉价"的直接原因。
    4. 爆发时核心极亮、边缘柔和;大招的范围和层次最多,普通攻击收着。
    
    具体做法:
    - **剑气**:环形扇面网格,沿弧长的坐标做"扫过"(一个头部位置加拖尾衰减),沿半径做刃形剖面(外缘一条亮芯、向内快速衰减、两端收尖),滚动噪声做条纹,随时间提高侵蚀阈值让它碎掉。下面再垫一层普通混合的深色墨迹,存活更久。下劈类招式把同一个网格竖起来。
    - **法阵**:全部在片元着色器里画——同心环、旋转的符文带(极坐标分格加哈希选笔画)、反向旋转的多边形、从中心向外展开的揭示。
    - **落剑**:用真的剑形网格(菱形截面剑身、剑尖、护手、剑柄),斜向插入,身后跟一条彗星状拖尾,落地有地裂贴花和冲击环,停留后按噪声向上溶解。
    - **预警图形也是特效**:扇形里放向外流动的条纹,直线预警做成收尖的刃形,一条亮线表示进度。不要纯色矩形和纯色圆。
    - **持续存在的东西**(弹幕、光柱)用便宜的交叉面片加滚动噪声。
    - 武器在出招时发光,持剑时有少量上飘的光点。走动时脚下扬起雪尘并留下会淡掉的脚印。
    
    **泛光很强,颜色峰值控制在 2 到 3**。第一版特效几乎一定过曝成一片白,要连调两三轮亮度。
    
    粒子用一个固定容量的环形缓冲就够。注意点精灵的尺寸公式,默认往往只有两三个像素。
    
    ## 掉落物
    - 击杀蹦出建模的小物件(先抛起再落地),落地瞬间出提示音。
    - 品质分档,一眼可辨:光圈大小、光柱高度和粗细、音高和时长都不同;最高档有冲天光柱、落地冲击环、周期性脉冲。
    - 提示音要能盖过战斗声:用敲钟式的多泛音,稀有的更高更长。
    - 靠近自动吸取,然后变成光点沿弧线飞进屏幕角落的背包图标,图标弹一下。物品要有实际作用。
    - 第一版光柱一定太细太淡,至少做三层(亮芯、主体、宽的柔光)。
    
    ## 界面
    - **血条用代码画**:斜切端头的细框、渐变填充、亮色前沿、刻度、延迟掉血条。贴图血条会被直接说"像一张贴图"。
    - 技能栏用同一批生成的图标,带按键标注、冷却遮罩、资源不足变灰、大招充能环。
    - 目标提示、Boss 名、横幅用衬线或楷体,字距拉开,尺寸克制。
    - 过场时隐藏界面(注意别用行内样式把这条规则盖掉)。
    - 载入完成前不要显示"点击开始"。
    
    ## 文案
    平实、具体、少。不要招式名喊话,不要破折号加感叹的旁白,不要"第二阶段"式的横幅。一句交代目的的开场白,Boss 说两三句和剧情有关的短句,就够了。
    
    ## 音量
    - 配乐和环境音默认要比你以为的小很多(配乐大约是音效的三分之一),否则会盖住音效。
    - 格挡、弹反这类"确认成功"的声音要最响最脆,叠两层采样加一层合成的金属泛音。
    - 说话时把配乐压低。
    - 合成噪声做风声时循环要长(几秒以上),太短会听出周期。
    
  • .gitignore30 Bbf561900b649upstream ↗
    .DS_Store
    node_modules/
    dist/
    
  • LICENSE34 KBfe6b9036ba18upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/cover.jpg164 KBba4f9493f3f8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/demo.gif7.2 MB2698c6c93e91upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/icon.png142 KB1781f2c826fbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/shot_combo.jpg53 KB551563b03adaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/shot_skill.jpg51 KBb0f8b259cd7dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • media/shot_ult.jpg67 KB2edac6b86714upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README.en.md8.6 KBe27473d23ca9upstream ↗
    <div align="center">
    
    <img src="media/icon.png" width="96" alt="Mist-Locked Gate">
    
    # Guizang Game Skill
    
    **Have your AI coding agent build a playable 3D action game for the browser, from nothing**
    
    English · [简体中文](README.md)
    
    [![Play the demo](https://img.shields.io/badge/Play_the_demo-Mist--Locked_Gate-c9a45c?style=for-the-badge)](https://op7418.github.io/guizang-game-skill/)
    [![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=for-the-badge)](LICENSE)
    [![Stars](https://img.shields.io/github/stars/op7418/guizang-game-skill?style=for-the-badge&color=e9dcae)](https://github.com/op7418/guizang-game-skill/stargazers)
    
    <a href="https://op7418.github.io/guizang-game-skill/"><img src="media/demo.gif" width="720" alt="Combat footage from Mist-Locked Gate"></a>
    
    *Real footage from the demo game, Mist-Locked Gate (雾锁山门). [Play it here](https://op7418.github.io/guizang-game-skill/) on a computer or a phone. Nothing to install. The game's text and voice are in Chinese.*
    
    </div>
    
    ---
    
    ## What this is
    
    A skill for AI coding agents (Claude Code, Codex and others). Install it, then say "make a top-down wuxia 3D action game", and the agent follows a workflow that has been walked end to end: it asks what you want, connects the asset tools you have, advances and screenshots the game by itself to check its own work, and packs the result into one web page.
    
    The skill is not theory. It is what went wrong, and what survived, while I built Mist-Locked Gate with Fable 5.2 in one afternoon: about 6 hours and 450 million tokens (some of them Opus 5.5 test runs), much of it spent on rework. The skill exists so that you and your agent skip that rework.
    
    ## The demo: Mist-Locked Gate
    
    <table>
    <tr>
    <td width="38%"><img src="media/cover.jpg" alt="Title screen"></td>
    <td>
    
    A top-down xianxia action game: one area, one mob encounter, one boss fight, with story and voice acting. **Every creative decision was the AI's.** All I said was "Chinese fantasy".
    
    - **Rendering**: a field of wind-blown grass, layered mist, snow and distant mountains, reflections on a flooded stone platform. The pipeline is hand-built on three.js and uses plain WebGL, so it runs on phones, desktops and inside restricted mini-app containers
    - **Characters and props**: 5 rigged 3D characters, 2 weapons, 12 kinds of props, 5 kinds of loot. Concept images first, then image-to-3D with Tripo. The AI wrote every prompt
    - **Combat**: a three-hit combo, dodge, guard, parry, riposte, plus healing, sword flight and an ultimate. The boss has a second phase, a rising cutscene and lines
    - **Sound**: 8 voiced lines, music, ambience and effects
    - **Size**: close to 100 MB of source assets, shipped as one HTML file of about 33 MB that contains every model, texture, track and voice line
    
    </td>
    </tr>
    </table>
    
    <table>
    <tr>
    <td><img src="media/shot_combo.jpg" alt="Combo"></td>
    <td><img src="media/shot_skill.jpg" alt="Sword art"></td>
    <td><img src="media/shot_ult.jpg" alt="Ultimate"></td>
    </tr>
    <tr>
    <td align="center">Three-hit combo</td>
    <td align="center">Sword art</td>
    <td align="center">Ultimate</td>
    </tr>
    </table>
    
    Three builds, all from the same source:
    
    | Build | What it is |
    |---|---|
    | [Hosted](https://op7418.github.io/guizang-game-skill/) | Draws the scene first and loads the rest while it runs. Touch stick and buttons on phones. Settings for quality, high-resolution textures and key bindings |
    | Single file | One HTML of about 33 MB that makes no network requests |
    | Mini-app container | Built separately for a container with no network, no WASM and a 10 MiB limit (Xiaohongshu mini tools). About 8 MiB |
    
    ## What the skill does for you
    
    Ask an agent to "make a 3D game" and you usually get grey boxes, floaty controls and a project you have to set up before it runs. With this skill installed:
    
    1. **It asks before it builds.** References, camera, mood, scope, which asset tools you have and how many credits. It connects those tools from the start instead of writing a box-model placeholder
    2. **It checks its own work.** Self-test tooling goes in on day one: frame-by-frame stepping, URL flags that jump straight to a stage, an F3 diagnostics panel. It takes its own screenshots and tells you what it looked at and what merely did not throw
    3. **Combat feel is written down.** Wind-up and recovery, hit-stop, tiered knockback, guard and parry, enemies that take turns instead of piling on, a dodge that cancels anything. Where "impact" comes from is spelled out
    4. **A list of known pitfalls.** Stuck direction keys, preset animations throwing the character off its spot, blown-out bloom, the camera buried in a roof, characters shrinking to half size after packing. Each with symptom, cause and fix
    5. **Three ways to ship.** Large models and assets squeezed small: a single HTML file, a static site that renders before it finishes loading, and an offline package for restricted containers
    
    ## Install
    
    Give your agent this repository's link and ask it to install the skill. Or by hand:
    
    ```bash
    git clone https://github.com/op7418/guizang-game-skill ~/.claude/skills/guizang-game-skill
    ```
    
    For Codex and other tools, clone into their own skills directory.
    
    Then just say what you want:
    
    ```
    Make a top-down wuxia 3D action game for the web: one area, one wave of enemies, one boss.
    I have Tripo and an image generator available.
    ```
    
    ## What you need
    
    | Thing | Used for | Without it |
    |---|---|---|
    | Node.js 18+ | Local server and packing | Required |
    | [Tripo](https://www.tripo3d.ai/) | Image-to-3D, rigging | Falls back to free models and procedural geometry. It will look worse |
    | An image generator (the demo used [Jimeng](https://jimeng.jianying.com/)) | Concept images, icons, title lettering, voice | Falls back to free assets |
    | [Suno](https://suno.com/) | Music | The skill writes the prompts for you, or uses generated music |
    
    Asset tools change the result more than anything else. I first let the agent generate models straight from text and they were poor. "Concept image first, then image-to-3D" was a different league.
    
    ## Workflow
    
    ```
    research and plan → setting and assets → animation → feel and effects → sound and packing
    ```
    
    1. **Research and plan**: read references, look up how this kind of game is made, write a research note and a staged plan
    2. **Setting and assets**: world, concept images, image-to-3D, rigging
    3. **Animation**: platforms provide few preset clips, so the rest is computed, placing hands and feet pose by pose
    4. **Feel and effects**: work through the combat-feel checklist. Effects are meshes and shaders, not piles of particles
    5. **Sound and packing**: effects, voice, music, then compress and pack into one file
    
    ## Contents
    
    | Path | What is in it |
    |---|---|
    | [`SKILL.md`](SKILL.md) | The whole workflow and the checkpoints of each stage |
    | [`references/assets.md`](references/assets.md) | Generating assets, sources of free ones |
    | [`references/characters-animation.md`](references/characters-animation.md) | Characters, rigs and animation |
    | [`references/combat-feel.md`](references/combat-feel.md) | Combat feel |
    | [`references/vfx-ui-audio.md`](references/vfx-ui-audio.md) | Effects, interface and sound |
    | [`references/pitfalls.md`](references/pitfalls.md) | Known pitfalls |
    | [`references/packaging.md`](references/packaging.md) | Size reduction, single-file packing, hosting, phones and restricted containers |
    | [`scripts/`](scripts) | Reusable input handling, local server and three build scripts |
    
    The skill's documents are written in Chinese. Current agents read them without trouble.
    
    ## Set your expectations
    
    - **It is not one prompt to a finished game.** I play-tested Mist-Locked Gate 7 times and reported 5 to 10 problems each round. I do not know game development, so my notes were things like "the movement is stiff" and "hits feel weak". The agent turns those into proper terms, looks them up and fixes them. You still have to play and give feedback
    - **Three things I insist on**: give it reference videos, tell it to research before it builds, and stop it from reinventing tools when a real asset tool is available
    - **The skill has been through one full project**, plus one plan-level comparison test. It keeps the direction right. It does not guarantee the result
    
    ## License
    
    - **The skill** (documents and scripts on the `main` branch): [AGPL-3.0](LICENSE)
    - **The demo game's content** (art, models, voice, music, writing, on the `gh-pages` branch): © 2026 Guizang, all rights reserved. Play it and share the link freely. Please do not re-host, rebrand or use it commercially without permission
    
    ## Author
    
    [Guizang (歸藏)](https://x.com/op7418). If this helped, a star is appreciated, and I would love to see the game you make with it.
    

Plain-text copy, no login: /skill-bundles/op7418-guizang-game-skill.md

// REPO STATS

308 stars
3 open issues
Last commit: 4d ago