feat: add offline Shanhe Puzzle mini tool
This commit is contained in:
+27
@@ -0,0 +1,27 @@
|
||||
# Dependencies, local tooling and caches
|
||||
node_modules/
|
||||
.codex/
|
||||
.claude/
|
||||
.skill/
|
||||
.cache/
|
||||
.vite/
|
||||
coverage/
|
||||
playwright-report/
|
||||
test-results/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.log
|
||||
*.skill
|
||||
.DS_Store
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Generated builds, ZIPs, reports, screenshots and local materials
|
||||
/artifacts/
|
||||
/dist/
|
||||
/data/
|
||||
|
||||
# Development research: only the map snapshot used by build-time audit is required
|
||||
/research/*
|
||||
!/research/china.json
|
||||
@@ -0,0 +1,110 @@
|
||||
# 山河拼图
|
||||
|
||||
参考用户提供的日本地图下落合并视频开发的小红书离线小工具。正式交付包含**省级版、地级版**;县级素材已备好,未进入游戏发布包。
|
||||
|
||||
项目独立存放于 `ProjectRednote/shanhe-puzzle/`。以下命令请在 `shanhe-puzzle` 目录执行。仓库仅跟踪源码、测试和构建脚本、依赖清单、本文档,以及运行和构建校验必需的地图数据。
|
||||
|
||||
## 立即预览和打包
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run dev
|
||||
# http://localhost:4173
|
||||
npm test
|
||||
npm run build
|
||||
npm run test:browser
|
||||
npm run test:results
|
||||
npm run test:interactions
|
||||
```
|
||||
|
||||
浏览器测试目前默认使用 macOS 已安装的 Google Chrome,路径见 `tests/browser.mjs`。构建要求 Python 3,以及官方 [minitool-zip-builder 1.8.0 Skill](https://fe-static.xhscdn.com/minitool/20261015161653/minitool-zip-builder-1.8.0.skill)。克隆后需将 Skill 解压到本地 `.codex/skills/minitool-zip-builder/`,该目录应直接包含 `SKILL.md`、`references/` 和 `scripts/`。本地工具、依赖、构建输出和报告均已忽略,不推送到代码库。所有运行依赖与地图随最终 ZIP 提供,无联网运行逻辑。
|
||||
|
||||
上传产物:`artifacts/shanhe-puzzle-xhs.zip`。根目录直接包含 `index.html`,不是项目源码压缩包。源代码在 `src/`,静态构建在 `dist/`。
|
||||
|
||||
**必须在创服平台模拟器、Android 真机扫码、iOS 真机扫码验证同一 ZIP。** 本地浏览器仅用于开发回归和视觉检查,不能替代小红书容器验收。Chrome 61 / Android 8.1 兼容性、CSS 兼容性及真机性能均未实测;原生发笔记、相册授权和保存需要真机验证。
|
||||
|
||||
本机预览服务监听 `127.0.0.1:4173`,可以在这台Mac的系统浏览器打开 `http://localhost:4173/`;与Codex内置浏览器使用同一个服务。当前已有服务时无需重复启动。
|
||||
|
||||
## 版本范围
|
||||
|
||||
- 省级版:全国 34 个省级行政区,各出现一次,合并为一个整体即通关。
|
||||
- 地级版:选择省或自治区,提供 27 个关卡、333 个地级行政区,包含地级市、自治州、地区、盟。
|
||||
- 排除县、区、县级市,以及济源、仙桃等省直辖县级单位。数据源会把部分县级单位标为 `city`,构建时进一步用行政区代码排除。
|
||||
- 北京、天津、上海、重庆、香港、澳门不设地级关卡;数据源暂缺台湾省地级边界,未生成对应地级关卡。
|
||||
- 本机县级原始边界位于 `data/raw/`,共 335 组、2840 个县级单元;预处理素材位于 `data/county-materials/`,另附独立素材 ZIP。这些开发素材全部保留本地,不进入 Git 或发布包。
|
||||
|
||||
## 玩法与得分
|
||||
|
||||
进入页选择省级 / 地级版、地区、四档下落速度和三档弹性,点击“开启这局旅程”后开局。独立的整屏游戏页底部提供“左晃 / 上晃 / 右晃”:左右支持按住,向上点击轻颠,也支持键盘 ← ↑ →。操作的是整个框和其中所有组合,没有单片拖动、旋转或加速。弹跳和倾斜有上限,松手后自动回正。
|
||||
|
||||
只有真实相邻关系、正确地理位置接近时才自动吸合。全部落下后仍可晃动,直到通关、稳定堆过红线超过 2.4 秒,或主动结束。顶部暂停 / 返回都打开暂停页,可继续、结束旅程、重新开局。结束旅程会保留成绩,即使零分或未通关也会生成图片;通关和判负自动生成。
|
||||
|
||||
省级海岛使用明确标注的“跨海连接”;地级版中因海域、未纳入本关的省直辖县等产生的间隔,使用明确标注的“隔区连接”。这两种连接都是游戏规则,不能当作陆地邻接关系。入口地图保留相对地理位置。
|
||||
|
||||
| 档位 | 出片间隔 | 重力参数 | 得分倍率 |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 佛系看山 | 8.5 秒 | 0.32 | ×1 |
|
||||
| 说走就走 | 6 秒 | 0.48 | ×1.5 |
|
||||
| 一路狂飙 | 4 秒 | 0.7 | ×2 |
|
||||
| 山河起飞 | 2.5 秒 | 1 | ×3 |
|
||||
|
||||
每次合并分数 = `(100 + 40 × (合并后块数 − 2)) × 连合系数 × 速度倍率 × 特殊连接系数`,四舍五入到整数。8.5 秒内再次合并视为连合,系数每次增加 0.25,从 1 起、最高 2;跨海和隔区连接额外乘 0.8。通关再奖 `1000 × 速度倍率`。三向晃动不限次数、不扣分。弹性不改变得分倍率。
|
||||
|
||||
弹性三档为“轻轻弹 / 蹦蹦跳 / 弹力全开”,碰撞恢复系数分别为 0.65 / 0.82 / 0.96,同时调整空气阻力、横向冲量和上抛上限。现在最低档对应上一版最高档;默认推荐“蹦蹦跳”,便于腾挪,“弹力全开”需要更好地控制节奏。省级、地级碎片均在上一版基础上线性再缩小 10%;地级仍比相同地图基准额外小 30%;组合过大时仍会全局等比缩放。
|
||||
|
||||
最佳纪录按“关卡 + 下落速度 + 弹性”分别保存,旧版纪录对应最低弹性。客户端 9.46.0+ 优先使用官方 Storage;含同步启动信息、异步回退、编译序号剥离及旧纪录迁移。旧环境回退到带异常处理的浏览器存储。
|
||||
|
||||
成绩页展示可分享的 750×1400 图片:本局得分、结束时实际容器画面、关卡、速度和弹性、用时、最大拼合 / 最佳连合,以及得分随分钟变化的曲线。曲线从零开始,记录实际得分时刻和结束时间,包含通关奖励,暂停不计时。不会用完整地图冒充未完成的结局。
|
||||
|
||||
“发小红书”在玩家点击后调用 `writeTempFile` + `postNote`,携带图片和成绩文案打开图文发布页,玩家可编辑、取消、确认发布;不会自动发布或声称审核成功。“保存成绩图”调用 `writeTempFile` + `saveImageToPhotosAlbum`。无 SDK、接口缺失、授权拒绝、取消或调用失败都有提示,不丢失成绩图;临时路径即用即弃。
|
||||
|
||||
当前[官方文档](https://miniapp-sandbox.xiaohongshu.com/minitool/doc#s3-3)支持分享已有视频,但未提供公开录屏 API;屏幕共享被禁用。因此本包不含自动录屏,可用手机系统录屏后自行分享。未使用未公开原生 bridge 或网页屏幕采集。
|
||||
|
||||
构建使用已随源码提供的 `src/maps.js`;`research/china.json` 是构建时地图完整性核对必需的源快照。其余 `research/` 文件和整个 `data/` 目录均不入库。下载与预处理脚本仅用于另行更新地图;重生成前需要准备 `research/areas.json` 等原始输入。
|
||||
|
||||
## 代码与数据
|
||||
|
||||
- `src/core.js`:相邻关系、地理位置与角度吸合判断、计分、纪录清洗。
|
||||
- `src/game.js`:Matter.js 刚体、出片、组合、胜负、速度、弹性、三向容器晃动、得分时间点和尺寸变化。
|
||||
- `src/app.js`:入口 / 游戏 / 成绩页切换、Canvas 绘制、三向输入、暂停与结束、原生 Storage、发笔记和相册导出。
|
||||
- `src/result.js`:真实结局快照与得分曲线的成绩图绘制。
|
||||
- `src/index.html`、`src/style.css`:单入口、响应式布局、安全区和 Chrome 61 样式基线。
|
||||
- `src/maps.js`:构建期简化的省级 / 地级真实轮廓与预计算连接图。
|
||||
- `scripts/download-maps.py`、`scripts/download-provinces.py`:仅开发期下载公开地图;后者有台湾省 404 的如实记录。
|
||||
- `scripts/prepare-maps.py`:简化轮廓、区分行政级别、预计算邻接,输出正式数据和独立县级素材。
|
||||
- `scripts/check.mjs`、`scripts/build.mjs`、`scripts/package.py`:ES2017 / 离线静态检查、官方 Skill 体积审计、ZIP 结构及完整性验证。
|
||||
- `tests/`:真实地图可通关性、错误边拒合、朝向一致性、计分、警戒线、整框惯性及入口 / 开局浏览器回归。
|
||||
|
||||
地图来源:阿里云 [DataV.GeoAtlas](https://datav.aliyun.com/portal/school/atlas/area_selector),2026-10-16 下载。数据可能落后于最新行政区划,已做游戏用轮廓简化,不能用于导航、测绘或行政区划查询。原始数据提供方条款继续适用,公开可下载不等于获得额外授权。视觉保留岛屿轮廓;物理碰撞对极小区域、退化或相交轮廓采用简化代理。
|
||||
|
||||
物理引擎 Matter.js 0.20.0、凹多边形分解 poly-decomp 0.3.0 随包本地提供,许可证见发布包 `licenses.json`。不用 AI、外部 SDK、远程字体、WASM、Worker、网络请求、剪贴板或文件下载能力。
|
||||
|
||||
## 检查记录
|
||||
|
||||
`artifacts/check-report.json` 是本地语法及资源预检,`artifacts/official-audit.txt` 是官方 Skill 1.8.0 的目录与 ZIP 审计结果,`artifacts/browser-report.json` 是本地浏览器开发回归,`artifacts/package-report.json` 提供包大小和 SHA-256。详细交付检查及待验证项目见 `artifacts/VALIDATION.md`。
|
||||
|
||||
## 容器晃动与碎片比例更新
|
||||
|
||||
棋盘改为较窄的开口实体容器,侧壁和底边清晰可见,红色警戒线位于顶部 78px。以 320×435 逻辑尺寸为例,全国开局缩放约 0.4995,相对最初约 0.215 的版本仍明显更大,本轮比上一版的0.555再缩小10%。保持各省之间真实比例,微小地区保持真实相对比例,同样通过框体晃动参与拼接。
|
||||
|
||||
晃动采用阻尼弹簧模型:容器位移和施加给所有碎片的惯性来自同一状态,并有 14px 的视觉位移限制。左右按钮和键盘左右键均可以持续按住,松开即停止继续施力。无需加速度计或设备运动 API。
|
||||
|
||||
较大组合超出容器可用空间时,全体碎片按相同比例缩小,保持地理相对比例、分数与队列,继续容纳完整地图。难度和拥堵由关卡形状、晃动、速度及弹性共同影响;本地模拟只用于排查物理问题,不能推断真机性能或玩家通关难度。
|
||||
|
||||
## 碰撞与晃动手感
|
||||
|
||||
碰撞采用160ms轻微压缩回弹、淡轮廓与180ms小接触点,明显弱于合并时的1600ms反馈。渲染形变不修改真实碰撞几何。左右轻摇仅在有支撑时颠起,上晃对框内全部组合施加一次向上冲量,420ms 冷却限制快速连点。颠起目标与上抛速度随弹性档位变化,但各档均有上限。最大倾角约 ±9.2°,水平和下落速度也受限,避免无限加速或飞出框。
|
||||
|
||||
`tests/shake-preview.mjs` 用真实左右操作和虚拟时钟采集碰撞反馈、速度与截图;`tests/results.mjs` 检查上晃、暂停主动结束、曲线和图片生成、模拟 SDK 参数和失败降级、自然判负及小型关卡真实通关的结算流程。均为本地开发回归,不能替代平台模拟器或真机验收。
|
||||
|
||||
`artifacts/bounce-probe.json`记录320×590逻辑尺寸下的实际物理峰值:单块正方形、一次上晃,四种速度分别测得轻弹33~37px、正常97~110px、强弹236~270px。真实地图组合、容器尺寸和接触情况会改变结果。
|
||||
|
||||
省级/地级有滑块过渡及水平滑动手势;弹性选项压缩回弹,普通按钮轻按,目的地和弹窗渐入。减少动态效果设置会关闭装饰动画与碰撞形变,保留游戏物理。`npm run test:interactions`覆盖滑动切换、推荐默认档、按钮动画和真实碰撞反馈。
|
||||
|
||||
## 手机布局与地图标签修正
|
||||
|
||||
入口和游戏页均按可见视口及安全区排版:在320×568、375×667、390×844以及740×390横屏检查一屏显示;小屏会缩减装饰地图和冗余文案,保留所有主要选择与开局按钮。省区选择采用27项网格,不再使用原生长下拉框,弹窗注明无地级数据的范围。
|
||||
|
||||
四档名称为“佛系看山 / 说走就走 / 一路狂飙 / 山河起飞”,速度与倍率参数保持原值。三个晃动按钮居中排版,成绩页同样一屏显示。游戏地图先绘制全部形状,再统一绘制标签;名称采用独立布局、边距约束、避让,以及小地区标签底色 / 引线,防止名称贴底被裁或被其他省份覆盖。
|
||||
|
||||
构建补回源数据的小离岛外环及独立海域线层,34省级代码、名称及外环数量均与保存的原始数据对比。台湾省14个源外环、香港9个、澳门2个、海南133个全部保留。详见`artifacts/MAP_AUDIT.md`,这不是标准地图审图结论。
|
||||
Generated
+580
@@ -0,0 +1,580 @@
|
||||
{
|
||||
"name": "shanhe-puzzle",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shanhe-puzzle",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"matter-js": "0.20.0",
|
||||
"poly-decomp": "0.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"acorn": "8.15.0",
|
||||
"esbuild": "0.25.12",
|
||||
"playwright": "1.56.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
|
||||
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
|
||||
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
|
||||
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
|
||||
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.25.12",
|
||||
"@esbuild/android-arm": "0.25.12",
|
||||
"@esbuild/android-arm64": "0.25.12",
|
||||
"@esbuild/android-x64": "0.25.12",
|
||||
"@esbuild/darwin-arm64": "0.25.12",
|
||||
"@esbuild/darwin-x64": "0.25.12",
|
||||
"@esbuild/freebsd-arm64": "0.25.12",
|
||||
"@esbuild/freebsd-x64": "0.25.12",
|
||||
"@esbuild/linux-arm": "0.25.12",
|
||||
"@esbuild/linux-arm64": "0.25.12",
|
||||
"@esbuild/linux-ia32": "0.25.12",
|
||||
"@esbuild/linux-loong64": "0.25.12",
|
||||
"@esbuild/linux-mips64el": "0.25.12",
|
||||
"@esbuild/linux-ppc64": "0.25.12",
|
||||
"@esbuild/linux-riscv64": "0.25.12",
|
||||
"@esbuild/linux-s390x": "0.25.12",
|
||||
"@esbuild/linux-x64": "0.25.12",
|
||||
"@esbuild/netbsd-arm64": "0.25.12",
|
||||
"@esbuild/netbsd-x64": "0.25.12",
|
||||
"@esbuild/openbsd-arm64": "0.25.12",
|
||||
"@esbuild/openbsd-x64": "0.25.12",
|
||||
"@esbuild/openharmony-arm64": "0.25.12",
|
||||
"@esbuild/sunos-x64": "0.25.12",
|
||||
"@esbuild/win32-arm64": "0.25.12",
|
||||
"@esbuild/win32-ia32": "0.25.12",
|
||||
"@esbuild/win32-x64": "0.25.12"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/matter-js": {
|
||||
"version": "0.20.0",
|
||||
"resolved": "https://registry.npmjs.org/matter-js/-/matter-js-0.20.0.tgz",
|
||||
"integrity": "sha512-iC9fYR7zVT3HppNnsFsp9XOoQdQN2tUyfaKg4CHLH8bN+j6GT4Gw7IH2rP0tflAebrHFw730RR3DkVSZRX8hwA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz",
|
||||
"integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.56.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
|
||||
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/poly-decomp": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/poly-decomp/-/poly-decomp-0.3.0.tgz",
|
||||
"integrity": "sha512-hWeBxGzPYiybmI4548Fca7Up/0k1qS5+79cVHI9+H33dKya5YNb9hxl0ZnDaDgvrZSuYFBhkCK/HOnqN7gefkQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "shanhe-puzzle",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "山河拼图 · 离线中国行政区下落合并小游戏",
|
||||
"scripts": {
|
||||
"dev": "node scripts/serve.mjs",
|
||||
"build": "node scripts/build.mjs",
|
||||
"check": "node scripts/check.mjs",
|
||||
"test": "node --test tests/*.test.cjs",
|
||||
"test:browser": "node tests/browser.mjs",
|
||||
"test:results": "node tests/results.mjs",
|
||||
"test:interactions": "node tests/interactions.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"matter-js": "0.20.0",
|
||||
"poly-decomp": "0.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.25.12",
|
||||
"acorn": "8.15.0",
|
||||
"playwright": "1.56.1"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
|
||||
const context={window:{}};vm.runInNewContext(fs.readFileSync('src/maps.js','utf8'),context);const data=context.window.MAP_DATA,level=data.levels[0],source=JSON.parse(fs.readFileSync('research/china.json','utf8'));
|
||||
const expected=['110000','120000','130000','140000','150000','210000','220000','230000','310000','320000','330000','340000','350000','360000','370000','410000','420000','430000','440000','450000','460000','500000','510000','520000','530000','540000','610000','620000','630000','640000','650000','710000','810000','820000'];
|
||||
assert.deepEqual(Array.from(level.regions,r=>r.id).sort(),expected.slice().sort());
|
||||
const regions=level.regions.map(r=>{const f=source.features.find(f=>String(f.properties.adcode)===r.id),raw=f.geometry.type==='MultiPolygon'?f.geometry.coordinates:[f.geometry.coordinates];assert.equal(r.name,f.properties.name);assert.equal(r.rings.length,raw.length,r.name+'不得丢弃独立外环');for(const ring of r.rings){assert.ok(ring.length>=3);assert.ok(ring.every(p=>p.length===2&&p.every(Number.isFinite)));let area=0;for(let i=0;i<ring.length;i++)area+=ring[i][0]*ring[(i+1)%ring.length][1]-ring[(i+1)%ring.length][0]*ring[i][1];assert.ok(Math.abs(area)>1e-10,r.name+'存在退化外环');}return {id:r.id,name:r.name,sourcePolygonCount:raw.length,packagedPolygonCount:r.rings.length};});
|
||||
const maritime=source.features.find(f=>f.properties.adcode==='100000_JD');assert.equal(level.decorations.length,maritime.geometry.coordinates.length);
|
||||
assert.ok(level.edges.some(e=>e[2]===1&&(level.regions[e[0]].id==='710000'||level.regions[e[1]].id==='710000')));
|
||||
const report={passed:true,provinceCount:34,regions,maritimeSegments:level.decorations.length,taiwanIncluded:true,hongKongIncluded:true,macaoIncluded:true,countyAndPrefectureLimitation:'台湾省地级轮廓接口404;无对应地级关卡。直辖市、港澳不设地级单元关卡。',scope:'验证34项名称/代码及源数据外环未丢失,不等于标准地图审图或所有最新区划/全部岛礁的独立权威核验。',mapContentReference:'https://www.gov.cn/gongbao/content/2023/content_5752310.htm'};
|
||||
fs.writeFileSync('artifacts/map-audit.json',JSON.stringify(report,null,2));console.log('地图核对通过:34省级行政区,含台湾/香港/澳门;全部源外环保留,海域线层'+level.decorations.length+'段。');
|
||||
@@ -0,0 +1,18 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {transform} from 'esbuild';
|
||||
import {execFileSync} from 'node:child_process';
|
||||
fs.rmSync('dist',{force:true,recursive:true});fs.mkdirSync('dist/vendor',{recursive:true});
|
||||
for(const name of ['index.html','style.css','maps.js'])fs.copyFileSync('src/'+name,'dist/'+name);
|
||||
for(const name of ['core.js','game.js','result.js','app.js']){const result=await transform(fs.readFileSync('src/'+name,'utf8'),{target:['chrome61'],minify:true,legalComments:'inline'});fs.writeFileSync('dist/'+name,result.code);}
|
||||
for(const name of ['matter.min.js','decomp.min.js'])fs.copyFileSync('src/vendor/'+name,'dist/vendor/'+name);
|
||||
// Include third-party notices in an allowed local asset, outside game UI.
|
||||
fs.writeFileSync('dist/licenses.json',JSON.stringify({matter:{version:'0.20.0',license:fs.readFileSync('node_modules/matter-js/LICENSE','utf8')},decomp:{version:'0.3.0',license:fs.readFileSync('node_modules/poly-decomp/LICENSE','utf8')},maps:{source:'DataV.GeoAtlas',url:'https://datav.aliyun.com/portal/school/atlas/area_selector',downloaded:'2026-10-16',note:'Public data; geographic outlines simplified for a game. Original provider terms apply.'}},null,2));
|
||||
execFileSync(process.execPath,['scripts/check.mjs'],{stdio:'inherit'});
|
||||
execFileSync(process.execPath,['scripts/audit-maps.cjs'],{stdio:'inherit'});
|
||||
fs.mkdirSync('artifacts',{recursive:true});const audit='.codex/skills/minitool-zip-builder/scripts/audit_artifact.py';
|
||||
if(!fs.existsSync(audit))throw Error('缺少用户指定官方 Skill,请先安装 1.8.0。');
|
||||
const dirAudit=execFileSync('python3',[audit,'dist'],{encoding:'utf8'});console.log('官方目录审计:'+dirAudit.trim());
|
||||
execFileSync('python3',['scripts/package.py'],{stdio:'inherit'});
|
||||
const zipAudit=execFileSync('python3',[audit,'artifacts/shanhe-puzzle-xhs.zip'],{encoding:'utf8'});console.log('官方 ZIP 审计:'+zipAudit.trim());
|
||||
fs.writeFileSync('artifacts/official-audit.txt','Skill version: 1.8.0\nDirectory: '+dirAudit+'ZIP: '+zipAudit);
|
||||
@@ -0,0 +1 @@
|
||||
const vm=require('vm'),fs=require('fs');const {Game}=require(process.cwd()+'/src/game.js');let box={window:{}};vm.runInNewContext(fs.readFileSync('src/maps.js','utf8'),box);let level=box.window.MAP_DATA.levels[0],results=[];for(let seed=1;seed<=5;seed++){let n=seed;let rng=()=>{n=(n*1664525+1013904223)>>>0;return n/4294967296};let g=new Game(level,320,435,3,()=>{},rng);let initial=g.scale;g.start();while(g.status==='playing'&&g.clock<110000)g.tick(1000/30);results.push({seed,scale:initial,dropped:g.dropped,status:g.status,seconds:Math.round(g.clock/1000),max:Math.max(...g.groups.map(x=>x.ids.length))});g.destroy();}fs.writeFileSync('artifacts/pressure-report.json',JSON.stringify({viewport:{width:320,height:435},speed:'山河起飞',input:'无操作',samples:results,note:'固定随机种子的本地物理模拟,不代表真机性能或用户通关难度'},null,2));console.log(results);
|
||||
@@ -0,0 +1,9 @@
|
||||
import fs from 'node:fs';import path from 'node:path';import {parse} from 'acorn';
|
||||
const issues=[];const root='dist';
|
||||
function walk(dir){return fs.readdirSync(dir,{withFileTypes:true}).flatMap(d=>d.isDirectory()?walk(path.join(dir,d.name)):[path.join(dir,d.name)]);}
|
||||
const files=walk(root),allowed=new Set(['.html','.css','.js','.json','.png','.jpg','.jpeg','.webp','.gif','.svg','.woff','.woff2']);
|
||||
for(const f of files){if(!allowed.has(path.extname(f)))issues.push('不允许的文件类型: '+f);if(path.basename(f).startsWith('.'))issues.push('隐藏文件: '+f);const source=fs.readFileSync(f,'utf8');if(f.endsWith('.js')){try{parse(source,{ecmaVersion:2017});}catch(e){issues.push('非 ES2017 语法: '+f+' '+e.message);}const banned=[/\beval\s*\(/,/\bnew\s+Function\s*\(/,/\bfetch\s*\(/,/\bXMLHttpRequest\b/,/\bWebAssembly\b/,/\bnew\s+(?:SharedWorker|Worker|WebSocket|EventSource)\s*\(/,/navigator\.(?:clipboard|geolocation)/,/requestFullscreen\s*\(/,/window\.open\s*\(/];for(const re of banned)if(re.test(source))issues.push('禁用能力 '+re+' '+f);}
|
||||
if(f.endsWith('.html')){for(const m of source.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi))if(m[1].trim())issues.push('内联脚本');if(/\son[a-z]+\s*=/i.test(source))issues.push('行内事件');if(/<meta[^>]+Content-Security-Policy|type=[\"']module[\"']/i.test(source))issues.push('自建CSP或模块脚本');if(/<(?:iframe|object|form)\b|javascript:|\sdownload[\s=>]/i.test(source))issues.push('禁止的 HTML 能力');for(const m of source.matchAll(/(?:src|href)="([^"#]+)"/g)){if(!m[1].startsWith('./'))issues.push('非相对本地资源: '+m[1]);else if(!fs.existsSync(path.join(root,m[1])))issues.push('缺失资源: '+m[1]);}}
|
||||
if(f.endsWith('.css')){for(const m of source.matchAll(/url\(([^)]+)\)/g))if(/https?:|\/\//.test(m[1]))issues.push('外部样式资源');const banned=[/[;{]\s*gap\s*:/,/\bclamp\(/,/\bcolor-mix\(/,/\bdvh\b/,/\baspect-ratio\s*:/];for(const re of banned)if(re.test(source))issues.push('无降级的现代 CSS '+re);}}
|
||||
if(files.filter(f=>f.endsWith('.html')).length!==1||!fs.existsSync(root+'/index.html'))issues.push('须有且仅有根目录 index.html 入口');
|
||||
const report={date:'2026-10-16',type:'本地预检(非官方 Skill 校验)',baseline:'Chrome 61 / ES2017',files:files.map(f=>({path:path.relative(root,f),bytes:fs.statSync(f).size})),issues,passed:!issues.length};fs.mkdirSync('artifacts',{recursive:true});fs.writeFileSync('artifacts/check-report.json',JSON.stringify(report,null,2));if(issues.length){console.error(issues);process.exit(1);}console.log('本地预检通过:'+files.length+' 个本地文件;ES2017 解析、离线资源、禁用 API 与入口结构检查通过。');
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Fetch public DataV build inputs only; game never requests the network."""
|
||||
import json, pathlib, urllib.request, time, concurrent.futures
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
areas=json.load(open(ROOT/'research/areas.json'))
|
||||
# Counties/urban districts are packaged per prefecture, municipalities at province level.
|
||||
parents={a['parent'] for a in areas if a['level']=='district'}
|
||||
entries=[a for a in areas if a['adcode'] in parents]
|
||||
raw=ROOT/'data/raw';raw.mkdir(exist_ok=True,parents=True)
|
||||
def fetch(a):
|
||||
p=raw/(str(a['adcode'])+'.json')
|
||||
if p.exists(): return
|
||||
url='https://geo.datav.aliyun.com/areas_v3/bound/%s_full.json'%a['adcode']
|
||||
for attempt in range(3):
|
||||
try:
|
||||
with urllib.request.urlopen(url,timeout=25) as r: data=r.read()
|
||||
d=json.loads(data)
|
||||
if not d.get('features'): raise ValueError('no features')
|
||||
p.write_bytes(data);return
|
||||
except Exception as e:
|
||||
if attempt==2:return {'code':a['adcode'],'name':a['name'],'reason':str(e)}
|
||||
time.sleep(.4)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
failed=[r for r in pool.map(fetch,entries) if r]
|
||||
(ROOT/'data/download-report.json').write_text(json.dumps({'requested':len(entries),'downloaded':len(list(raw.glob('*.json'))),'failed':failed},ensure_ascii=False,indent=2))
|
||||
print('Map download:',len(entries),'requested;',len(failed),'unavailable')
|
||||
print(json.dumps(failed,ensure_ascii=False))
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Fetch public DataV build inputs only; game never requests the network."""
|
||||
import json, pathlib, urllib.request, time, concurrent.futures
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
areas=json.load(open(ROOT/'research/areas.json'))
|
||||
# Counties/urban districts are packaged per prefecture, municipalities at province level.
|
||||
parents={a['adcode'] for a in areas if a['level']=='province'}
|
||||
entries=[a for a in areas if a['adcode'] in parents]
|
||||
raw=ROOT/'data/provinces-raw';raw.mkdir(exist_ok=True,parents=True)
|
||||
def fetch(a):
|
||||
p=raw/(str(a['adcode'])+'.json')
|
||||
if p.exists(): return
|
||||
url='https://geo.datav.aliyun.com/areas_v3/bound/%s_full.json'%a['adcode']
|
||||
for attempt in range(3):
|
||||
try:
|
||||
with urllib.request.urlopen(url,timeout=25) as r: data=r.read()
|
||||
d=json.loads(data)
|
||||
if not d.get('features'): raise ValueError('no features')
|
||||
p.write_bytes(data);return
|
||||
except Exception as e:
|
||||
if attempt==2:return {'code':a['adcode'],'name':a['name'],'reason':str(e)}
|
||||
time.sleep(.4)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
failed=[r for r in pool.map(fetch,entries) if r]
|
||||
(ROOT/'data/province-download-report.json').write_text(json.dumps({'requested':len(entries),'downloaded':len(list(raw.glob('*.json'))),'failed':failed},ensure_ascii=False,indent=2))
|
||||
print('Map download:',len(entries),'requested;',len(failed),'unavailable')
|
||||
print(json.dumps(failed,ensure_ascii=False))
|
||||
@@ -0,0 +1,10 @@
|
||||
import pathlib,zipfile,json,hashlib
|
||||
root=pathlib.Path('dist');out=pathlib.Path('artifacts/shanhe-puzzle-xhs.zip')
|
||||
with zipfile.ZipFile(out,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
|
||||
for p in sorted(root.rglob('*')):
|
||||
if p.is_file():z.write(p,p.relative_to(root).as_posix())
|
||||
with zipfile.ZipFile(out) as z:
|
||||
assert 'index.html' in z.namelist()
|
||||
assert z.testzip() is None
|
||||
print('离线 ZIP:',out.resolve(),' | ',round(out.stat().st_size/1024),'KB')
|
||||
pathlib.Path('artifacts/package-report.json').write_text(json.dumps({'file':str(out),'bytes':out.stat().st_size,'sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'archiveIntegrity':'passed','rootEntry':'index.html'},indent=2))
|
||||
@@ -0,0 +1,121 @@
|
||||
import json, math, pathlib, collections
|
||||
ROOT=pathlib.Path(__file__).resolve().parent.parent
|
||||
AREAS=json.load(open(ROOT/'research/areas.json'));LOOKUP={a['adcode']:a for a in AREAS}
|
||||
def area(r):return abs(sum(r[i][0]*r[(i+1)%len(r)][1]-r[(i+1)%len(r)][0]*r[i][1] for i in range(len(r)))/2)
|
||||
def dist(p,a,b):
|
||||
dx,dy=b[0]-a[0],b[1]-a[1];n=dx*dx+dy*dy
|
||||
t=max(0,min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/n)) if n else 0
|
||||
return (p[0]-a[0]-t*dx)**2+(p[1]-a[1]-t*dy)**2
|
||||
def dp(p,eps):
|
||||
if len(p)<3:return p
|
||||
v,i=max((dist(p[k],p[0],p[-1]),k) for k in range(1,len(p)-1))
|
||||
if v<=eps*eps:return [p[0],p[-1]]
|
||||
return dp(p[:i+1],eps)[:-1]+dp(p[i:],eps)
|
||||
def project(p):return [p[0]*.82,-math.log(math.tan(math.pi/4+math.radians(p[1])/2))*180/math.pi*.82]
|
||||
def make_level(features,code,name,province):
|
||||
fs=[f for f in features if f.get('properties',{}).get('name') and f['properties'].get('adcode')]
|
||||
if len(fs)<2:return None
|
||||
reg=[];boundary=[]
|
||||
for f in fs:
|
||||
prop=f['properties'];g=f['geometry'];polys=g['coordinates'] if g['type']=='MultiPolygon' else [g['coordinates']]
|
||||
rings=[project_ring(p[0]) for p in polys if len(p[0])>=4]
|
||||
rings.sort(key=area,reverse=True)
|
||||
if not rings:continue
|
||||
main=rings[0];boundary.append({(round(x,3),round(y,3)) for r in rings for x,y in r})
|
||||
# Keep island geometry, simplify each independently; no invented boundaries.
|
||||
span=max(max(p[0] for p in main)-min(p[0] for p in main),max(p[1] for p in main)-min(p[1] for p in main))
|
||||
simple=[]
|
||||
for r in rings:
|
||||
localspan=max(max(p[0] for p in r)-min(p[0] for p in r),max(p[1] for p in r)-min(p[1] for p in r))
|
||||
eps=max(min(span*.005,localspan*.01),.00000001);q=dp(r,eps)
|
||||
while len(q)>90:eps*=1.4;q=dp(r,eps)
|
||||
if len(q)<4:q=r
|
||||
simple.append(q[:-1] if q[0]==q[-1] else q)
|
||||
cx=sum(x for x,y in main[:-1])/max(1,len(main)-1);cy=sum(y for x,y in main[:-1])/max(1,len(main)-1)
|
||||
reg.append({'id':str(prop['adcode']),'name':prop['name'],'rings':simple,'center':[cx,cy]})
|
||||
if len(reg)<2:return None
|
||||
edges=[]
|
||||
for i in range(len(reg)):
|
||||
for j in range(i):
|
||||
if len(boundary[i]&boundary[j])>=2:edges.append([j,i,0])
|
||||
# Join disconnected island components with explicit game-only sea routes.
|
||||
def components():
|
||||
groups=[{i} for i in range(len(reg))]
|
||||
for a,b,_ in edges:
|
||||
ga=next(g for g in groups if a in g);gb=next(g for g in groups if b in g)
|
||||
if ga is not gb:ga.update(gb);groups.remove(gb)
|
||||
return groups
|
||||
while len(components())>1:
|
||||
gs=components();candidates=[]
|
||||
for a in gs[0]:
|
||||
for g in gs[1:]:
|
||||
for b in g:
|
||||
pa,pb=reg[a]['center'],reg[b]['center'];candidates.append(((pa[0]-pb[0])**2+(pa[1]-pb[1])**2,a,b))
|
||||
_,a,b=min(candidates);edges.append([a,b,1])
|
||||
allp=[p for r in reg for ring in r['rings'] for p in ring]
|
||||
minx,miny=min(p[0] for p in allp),min(p[1] for p in allp);maxx,maxy=max(p[0] for p in allp),max(p[1] for p in allp)
|
||||
span=max(maxx-minx,maxy-miny);scale=1000/span
|
||||
for r in reg:
|
||||
r['center']=[round((r['center'][0]-minx)*scale,2),round((r['center'][1]-miny)*scale,2)]
|
||||
r['rings']=[[[round((x-minx)*scale,4),round((y-miny)*scale,4)] for x,y in ring] for ring in r['rings']]
|
||||
return {'id':str(code),'name':name,'province':str(province),'width':round((maxx-minx)*scale,2),'height':round((maxy-miny)*scale,2),'regions':reg,'edges':edges,'projection':[minx,miny,scale]}
|
||||
def project_ring(r):return [project(p) for p in r]
|
||||
levels=[]
|
||||
cn=json.load(open(ROOT/'research/china.json'));nation=make_level(cn['features'],100000,'中国 · 省级拼图',100000);levels.append(nation)
|
||||
for p in sorted((ROOT/'data/raw').glob('*.json')):
|
||||
code=int(p.stem);info=LOOKUP.get(code)
|
||||
if not info:continue
|
||||
fs=json.load(open(p)).get('features',[])
|
||||
# Do not turn city-level outlines into county puzzles.
|
||||
fs=[f for f in fs if f.get('properties',{}).get('level')=='district']
|
||||
prov=code if info['level']=='province' else info['parent']
|
||||
level=make_level(fs,code,info['name'],prov)
|
||||
if level:levels.append(level)
|
||||
provinces=[{'id':str(a['adcode']),'name':a['name']} for a in AREAS if a['level']=='province']
|
||||
result={'source':'DataV.GeoAtlas','downloadDate':'2026-10-16','provinces':provinces,'levels':levels}
|
||||
(ROOT/'data/county-materials').mkdir(parents=True,exist_ok=True)
|
||||
(ROOT/'data/county-materials/maps.js').write_text('window.MAP_DATA='+json.dumps(result,ensure_ascii=False,separators=(',',':'))+';\n')
|
||||
summary={'levels':len(levels),'countyLevels':len(levels)-1,'provincePieces':len(nation['regions']),'countyPieces':sum(len(l['regions']) for l in levels[1:]),'availableProvinces':len({l['province'] for l in levels[1:]}),'seaRoutes':sum(e[2] for l in levels for e in l['edges'])}
|
||||
(ROOT/'data/county-materials/summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2));print(summary)
|
||||
|
||||
# Formal release: only province and prefecture-level units, no county pieces.
|
||||
citylevels=[nation]
|
||||
excluded=[]
|
||||
for p in sorted((ROOT/'data/provinces-raw').glob('*.json')):
|
||||
code=int(p.stem);info=LOOKUP.get(code)
|
||||
if not info:continue
|
||||
fs=json.load(open(p)).get('features',[])
|
||||
cityfs=[f for f in fs if f.get('properties',{}).get('level')=='city' and int(f['properties'].get('adcode',0))%100==0]
|
||||
excluded.extend(f['properties']['name'] for f in fs if f not in cityfs)
|
||||
lv=make_level(cityfs,code,info['name'],code)
|
||||
if lv:
|
||||
# Missing county-only zones may disconnect prefectures: these are not land neighbors.
|
||||
for edge in lv['edges']:
|
||||
if edge[2]:edge[2]=2
|
||||
citylevels.append(lv)
|
||||
def inside(p,ring):
|
||||
x,y=p;hit=False
|
||||
for i,a in enumerate(ring):
|
||||
b=ring[(i+1)%len(ring)]
|
||||
if (a[1]>y)!=(b[1]>y) and x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0]:hit=not hit
|
||||
return hit
|
||||
for lv in citylevels:
|
||||
for r in lv['regions']:
|
||||
ring=r['rings'][0];minx,maxx=min(p[0] for p in ring),max(p[0] for p in ring);miny,maxy=min(p[1] for p in ring),max(p[1] for p in ring)
|
||||
candidates=[[minx+(maxx-minx)*i/14,miny+(maxy-miny)*j/14] for i in range(1,14) for j in range(1,14)]
|
||||
candidates=[p for p in candidates if inside(p,ring)]
|
||||
if candidates:r['label']=max(candidates,key=lambda p:min(dist(p,ring[k],ring[(k+1)%len(ring)]) for k in range(len(ring))))
|
||||
else:r['label']=r['center']
|
||||
r['label']=[round(v,3) for v in r['label']]
|
||||
# Preserve the source's unnamed maritime boundary features as a separate layer.
|
||||
minx,miny,scale=nation['projection'];decorations=[]
|
||||
for feature in cn['features']:
|
||||
if feature['properties'].get('adcode')=='100000_JD':
|
||||
geom=feature['geometry'];polys=geom['coordinates'] if geom['type']=='MultiPolygon' else [geom['coordinates']]
|
||||
for poly in polys:decorations.append([[round((project(p)[0]-minx)*scale,4),round((project(p)[1]-miny)*scale,4)] for p in poly[0]])
|
||||
nation['decorations']=decorations
|
||||
for lv in citylevels:lv.pop('projection',None)
|
||||
result={'source':'DataV.GeoAtlas','downloadDate':'2026-10-16','provinces':provinces,'levels':citylevels}
|
||||
(ROOT/'src/maps.js').write_text('window.MAP_DATA='+json.dumps(result,ensure_ascii=False,separators=(',',':'))+';\n')
|
||||
summary={'levels':len(citylevels),'prefectureLevels':len(citylevels)-1,'provincePieces':len(nation['regions']),'prefecturePieces':sum(len(l['regions']) for l in citylevels[1:]),'availableProvinces':len(citylevels)-1,'excludedCountyUnits':excluded,'countyMaterials':{'levels':len(levels)-1,'pieces':sum(len(l['regions']) for l in levels[1:]),'path':'data/county-materials/maps.js'}}
|
||||
(ROOT/'data/map-summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2));print('Release:',{k:v for k,v in summary.items() if k!='excludedCountyUnits'})
|
||||
@@ -0,0 +1,6 @@
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
const root=path.resolve(process.env.PREVIEW_DIR||'src');
|
||||
const mime={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.json':'application/json'};
|
||||
http.createServer((req,res)=>{let p;try{p=decodeURIComponent(new URL(req.url,'http://localhost').pathname);}catch{res.writeHead(400).end();return;}const file=path.resolve(root,'.'+(p==='/'?'/index.html':p));if(!file.startsWith(root+path.sep)){res.writeHead(403).end();return;}fs.readFile(file,(err,b)=>{if(err){res.writeHead(404).end('Not found');return;}res.writeHead(200,{'Content-Type':mime[path.extname(file)]||'application/octet-stream','Cache-Control':'no-store'});res.end(b);});}).listen(4173,'127.0.0.1',()=>console.log('山河拼图预览:http://localhost:4173'));
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
(function(){
|
||||
'use strict';
|
||||
var $=function(id){return document.getElementById(id);},data=window.MAP_DATA,C=window.PuzzleCore,Engine=window.PuzzleGame;
|
||||
var colors=['#c3d4b4','#e3c78f','#d2b5a5','#b5cbd0','#d2c69d','#b1c5a0','#d9bca6','#bdc7ac','#d7c5c5','#bfd0ba'];
|
||||
var provinceCode='330000',mode='province',speed=0,bounce=1,result=null,level=data.levels[0],game=null,screen='entry',records={},pausedByModal=false,toastTimer=null;
|
||||
var canvas=$('board'),ctx=canvas.getContext('2d'),w=0,h=0,dpr=1,miniTool=null,storageNative=false,storeReady=false,saveChain=Promise.resolve();
|
||||
var reducedMotion=typeof window.matchMedia==='function'?window.matchMedia('(prefers-reduced-motion: reduce)'):null,modeGesture=null,suppressModeClickUntil=0;
|
||||
var holdTimer=null,inputDirection=0,pointerDirection=0,keys={left:false,right:false},rafId=0,last=0,uiAt=0,lastLabelBoxes=[],labelObstacles=[];
|
||||
function motionAllowed(){return !reducedMotion||!reducedMotion.matches;}
|
||||
function pulseButton(button,kind){if(!button||button.disabled||!motionAllowed())return;button.classList.remove('tap-pop','bounce-pop');void button.offsetWidth;button.classList.add(kind||'tap-pop');}
|
||||
document.addEventListener('animationend',function(e){if(e.target.classList){e.target.classList.remove('tap-pop','bounce-pop');}});
|
||||
document.addEventListener('click',function(e){var button=e.target.closest&&e.target.closest('button');pulseButton(button,button&&(button.hasAttribute('data-bounce')||button.id==='up')?'bounce-pop':'tap-pop');});
|
||||
function toast(msg){$('toast').textContent=msg;$('toast').hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(function(){$('toast').hidden=true;},3200);}
|
||||
function version(options){return Number(options&&options.miniToolEnv&&options.miniToolEnv.buildVersion)||0;}
|
||||
var storePromise;
|
||||
function mergeRecords(a,b){Object.keys(b).forEach(function(k){a[k]=Math.max(a[k]||0,b[k]);});return a;}
|
||||
async function initStore(){var xhs=window.xhs;miniTool=xhs&&xhs.miniTool;var v=version(xhs&&xhs.launchOptions);if(!v&&miniTool&&typeof miniTool.getLaunchOptions==='function'){try{v=version(await miniTool.getLaunchOptions());}catch(e){v=0;}}
|
||||
storageNative=!!(Math.floor(v/1000)>=9460&&miniTool&&typeof miniTool.getStorage==='function'&&typeof miniTool.setStorage==='function');
|
||||
var old={};try{var legacy=window.localStorage.getItem('shanhe-records-v1');old=C.safeRecord(legacy?JSON.parse(legacy):{});}catch(e){}var loaded={};if(storageNative){try{var r=await miniTool.getStorage({key:'shanhe-records-v1'});loaded=C.safeRecord(r&&r.data?JSON.parse(r.data):{});}catch(e){}}else loaded=old;
|
||||
records=mergeRecords(mergeRecords(loaded,old),records);storeReady=true;if(storageNative&&Object.keys(old).length){try{await miniTool.setStorage({key:'shanhe-records-v1',data:JSON.stringify(records)});}catch(e){toast('旧纪录已在当前页面恢复,迁移保存暂不可用');}}updateUI();}
|
||||
function recordKey(){return level.id+':'+speed+(bounce?':'+bounce:'');}
|
||||
function saveRecord(){var key=recordKey();records[key]=Math.max(records[key]||0,game.score);updateUI();saveChain=saveChain.then(async function(){await storePromise;try{var serialized=JSON.stringify(records);if(storageNative)await miniTool.setStorage({key:'shanhe-records-v1',data:serialized});else window.localStorage.setItem('shanhe-records-v1',serialized);}catch(e){toast('本次纪录仅保留在当前页面,存储暂不可用');}});}
|
||||
function shortName(name){return name.replace(/特别行政区|维吾尔自治区|壮族自治区|回族自治区|自治区|省|市$/g,'');}
|
||||
function sizeCanvas(c,ww,hh){c.width=Math.round(ww*dpr);c.height=Math.round(hh*dpr);var context=c.getContext('2d');context.setTransform(dpr,0,0,dpr,0,0);return context;}
|
||||
|
||||
function layout(){
|
||||
dpr=Math.min(window.devicePixelRatio||1,2);
|
||||
var bodyStyle=window.getComputedStyle(document.body),padding=(parseFloat(bodyStyle.paddingTop)||0)+(parseFloat(bodyStyle.paddingBottom)||0);
|
||||
var viewport=window.visualViewport;var visibleHeight=viewport&&typeof viewport.height==='number'&&viewport.scale===1?Math.min(window.innerHeight,viewport.height):window.innerHeight;var available=Math.max(320,visibleHeight-padding);document.documentElement.style.setProperty('--game-height',available+'px');document.body.classList.toggle('compact-entry',available<700);document.body.classList.toggle('tiny-entry',available<540);
|
||||
if(screen==='entry'){drawReference();return;}if(screen==='result'){fitCard();return;}
|
||||
var r=canvas.getBoundingClientRect(),nw=Math.round(r.width),nh=Math.round(r.height);
|
||||
if(nw<1||nh<1)return;
|
||||
var changed=w!==nw||h!==nh;w=nw;h=nh;sizeCanvas(canvas,w,h);labelObstacles=['board-name','board-status'].map(function(id){var box=$(id).getBoundingClientRect();return {x:box.left-r.left-3,y:box.top-r.top-2,w:box.width+6,h:box.height+4};});var danger=document.querySelector('.danger-label').getBoundingClientRect();labelObstacles.push({x:danger.left-r.left-3,y:danger.top-r.top-2,w:danger.width+6,h:danger.height+4});
|
||||
if(game&&changed)game.resize(w,h);drawNext();if(game)draw();
|
||||
}
|
||||
function openModal(kicker,html,actions){
|
||||
stopInput();if(game&&game.status==='playing'){game.status='paused';pausedByModal=true;cancelAnimationFrame(rafId);rafId=0;}
|
||||
$('modal').classList.remove('province-picker-modal');$('modal-kicker').textContent=kicker;$('modal-content').innerHTML=html;$('modal-actions').innerHTML='';
|
||||
(actions||[]).forEach(function(a){var b=document.createElement('button');b.className=a.primary?'primary':'secondary';b.textContent=a.label;b.addEventListener('click',a.action);$('modal-actions').appendChild(b);});
|
||||
var d=$('modal');if(!d.hasAttribute('open')){if(typeof d.showModal==='function')d.showModal();else{d.setAttribute('open','');d.classList.add('modal-fallback');}}
|
||||
updateUI();
|
||||
}
|
||||
function closeModal(resume){$('province-picker').classList.remove('expanded');var d=$('modal');if(typeof d.close==='function')d.close();else{d.removeAttribute('open');d.classList.remove('modal-fallback');}if(pausedByModal&&resume!==false&&game&&game.status==='paused'){game.status='playing';last=0;schedule();}pausedByModal=false;updateUI();}
|
||||
$('modal').addEventListener('cancel',function(e){e.preventDefault();closeModal();});$('close-modal').addEventListener('click',function(){closeModal();});
|
||||
function start(){
|
||||
stopInput();result=null;lastLabelBoxes=[];if(game)game.destroy();game=null;screen='game';document.body.classList.add('is-playing');$('entry-screen').hidden=true;$('result-screen').hidden=true;$('game-screen').hidden=false;window.scrollTo(0,0);
|
||||
$('board-status').textContent='左右轻摇 / 向上轻颠,晃动整个框';$('tank').style.transform='translateX(0px)';layout();
|
||||
game=new Engine.Game(level,w,h,speed,onGameEvent,null,bounce);game.start();last=0;drawNext();updateUI();schedule();
|
||||
}
|
||||
function showEntry(){stopInput();cancelAnimationFrame(rafId);rafId=0;if(game)game.destroy();game=null;lastLabelBoxes=[];screen='entry';document.body.classList.remove('is-playing');$('game-screen').hidden=true;$('result-screen').hidden=true;$('entry-screen').hidden=false;result=null;$('tank').style.transform='translateX(0px)';window.scrollTo(0,0);updateUI();layout();}
|
||||
function finishJourney(){closeModal(false);if(game)game.finish();}
|
||||
function askBack(){pause();}
|
||||
function pause(){if(!game||screen!=='game'||$('modal').hasAttribute('open'))return;if(game.endReason){showResult();return;}openModal('TAKE A BREATH','<h2>山河等你回来</h2><p>'+level.name+' · '+Engine.SPEEDS[speed].name+' · '+Engine.BOUNCES[bounce].name+'</p><p>暂停不计时。随时结束,也能带走这一程的成绩图。</p>',[{label:'继续游戏',primary:true,action:function(){closeModal();}},{label:'结束旅程',action:finishJourney},{label:'重新开局',action:function(){closeModal(false);start();}}]);}
|
||||
function onGameEvent(type,detail){
|
||||
if(type==='spawn'){drawNext();if(game.queue.length===0)$('board-status').textContent='碎片已全部落下 · 继续晃动容器';}
|
||||
else if(type==='merge')$('board-status').textContent=(detail.sea===1?'跨海连接':detail.sea===2?'隔区连接':'边缘吻合')+(game.chain>1?' · '+game.chain+' 连合':'');
|
||||
else if(type==='zoom')$('board-status').textContent='拼合区域变大 · 视野自动缩放';
|
||||
else if(type==='end'){stopInput();saveRecord();showResult();}
|
||||
updateUI();
|
||||
}
|
||||
function updateUI(){
|
||||
var key=recordKey(),best=records[key],config=Engine.SPEEDS[speed];$('entry-screen').classList.toggle('city-mode',mode==='city');var destination=data.levels.find(function(l){return l.id===provinceCode;});$('province-name').textContent=destination?destination.name:'浙江省';$('province-count').textContent=(destination?destination.regions.length:11)+' 个地级单元';
|
||||
$('entry-best').textContent=best?best.toLocaleString('zh-CN'):'—';$('journey-count').textContent=level.regions.length+' 块山河';$('map-caption').textContent=level.name+' · '+level.regions.length+' 块等你拼完整';
|
||||
$('city-select-panel').hidden=mode!=='city';$('city-note').textContent='27 个省区可选 · 仅拼地级市、自治州、地区、盟';
|
||||
$('multiplier').textContent='得分 ×'+config.multiplier;var comments=['慢慢来,也能看见山河','找到自己的拼图节奏','眼疾手快,山河相逢','留给地理高手的挑战'];$('speed-note').textContent=config.interval/1000+' 秒落下一块 · '+comments[speed];
|
||||
document.querySelectorAll('[data-mode]').forEach(function(b){var selected=b.getAttribute('data-mode')===mode;b.classList.toggle('selected',selected);b.setAttribute('aria-pressed',String(selected));});
|
||||
var modeTabs=document.querySelector('.mode-tabs');
|
||||
modeTabs.addEventListener('pointerdown',function(e){if(screen==='entry'&&e.isPrimary!==false)modeGesture={x:e.clientX,y:e.clientY,id:e.pointerId};});
|
||||
document.addEventListener('pointerup',function(e){if(!modeGesture||modeGesture.id!==e.pointerId)return;var dx=e.clientX-modeGesture.x,dy=e.clientY-modeGesture.y;modeGesture=null;if(screen==='entry'&&Math.abs(dx)>35&&Math.abs(dx)>Math.abs(dy)*1.3){mode=dx<0?'city':'province';suppressModeClickUntil=performance.now()+350;selectLevel();}});
|
||||
document.addEventListener('pointercancel',function(){modeGesture=null;});
|
||||
document.querySelectorAll('[data-speed]').forEach(function(b){var selected=Number(b.getAttribute('data-speed'))===speed;b.classList.toggle('selected',selected);b.setAttribute('aria-pressed',String(selected));});
|
||||
document.querySelectorAll('[data-bounce]').forEach(function(b){var selected=Number(b.getAttribute('data-bounce'))===bounce;b.classList.toggle('selected',selected);b.setAttribute('aria-pressed',String(selected));});
|
||||
var playable=!!game&&game.status==='playing';$('left').disabled=!playable;$('right').disabled=!playable;$('up').disabled=!playable;$('pause').disabled=!game;
|
||||
if(!game)return;
|
||||
$('score').textContent=game.score.toLocaleString('zh-CN');$('merged').textContent=game.groups.reduce(function(n,g){return Math.max(n,g.ids.length);},0);$('total').textContent=level.regions.length;
|
||||
$('game-title').textContent=level.name+(mode==='city'?' · 地级拼图':'');$('game-speed').textContent=config.name+' · '+Engine.BOUNCES[bounce].name+' · ×'+config.multiplier;$('board-name').textContent='山河容器 · 碰撞后自动回正';
|
||||
$('progress-label').textContent='已落下 '+game.dropped+' / '+level.regions.length+' 块'+(game.maxChain>1?' · 最佳 '+game.maxChain+' 连合':'');
|
||||
}
|
||||
function polygon(context,ring,transform){context.beginPath();ring.forEach(function(p,i){var q=transform(p);if(i===0)context.moveTo(q.x,q.y);else context.lineTo(q.x,q.y);});context.closePath();}
|
||||
function drawPiece(context,region,id,transform,opts){opts=opts||{};context.save();context.fillStyle=opts.ghost?'rgba(110,142,83,.10)':colors[id%colors.length];context.strokeStyle=opts.impact?'#96a47e':opts.physical?'#819778':'#fffdf2';context.lineWidth=opts.impact?1.65:opts.physical?1.4:1.25;if(opts.physical){context.shadowColor='rgba(42,62,46,.15)';context.shadowOffsetY=2;context.shadowBlur=3;}region.rings.forEach(function(r){polygon(context,r,transform);context.fill();context.stroke();});if(opts.label){context.shadowColor='transparent';context.shadowOffsetY=0;context.shadowBlur=0;var p=transform(region.center);var name=mode==='province'?shortName(region.name):region.name;var size=opts.font||10;context.font='500 '+size+'px -apple-system,"PingFang SC",sans-serif';context.textAlign='center';context.textBaseline='middle';context.strokeStyle='rgba(255,254,244,.88)';context.lineWidth=2.5;context.strokeText(name,p.x,p.y);context.fillStyle='#486044';context.fillText(name,p.x,p.y);}context.restore();}
|
||||
function staticTransform(ww,hh,padding){var sc=Math.min((ww-padding*2)/level.width,(hh-padding*2)/level.height),ox=(ww-level.width*sc)/2,oy=(hh-level.height*sc)/2;return function(p){return {x:p[0]*sc+ox,y:p[1]*sc+oy};};}
|
||||
function drawDecorations(context,transform){if(!level.decorations)return;context.save();context.fillStyle='#a1ad95';context.strokeStyle='#a1ad95';context.lineWidth=.5;level.decorations.forEach(function(ring){polygon(context,ring,transform);context.fill();context.stroke();});context.restore();}
|
||||
function renderLabels(context,items,ww,hh,fontSize,obstacles){
|
||||
var placed=[],offsets=[[0,0],[0,-18],[0,18],[-24,-12],[24,-12],[-24,12],[24,12],[0,-36],[0,36],[-45,0],[45,0],[-45,-25],[45,-25]];
|
||||
context.save();context.font='500 '+fontSize+'px -apple-system,"PingFang SC",sans-serif';context.textAlign='center';context.textBaseline='middle';
|
||||
items.sort(function(a,b){return Number(a.tiny)-Number(b.tiny);}).forEach(function(item){
|
||||
var lines=item.name.length>7?[item.name.slice(0,Math.ceil(item.name.length/2)),item.name.slice(Math.ceil(item.name.length/2))]:[item.name];
|
||||
var width=Math.max.apply(null,lines.map(function(line){return context.measureText(line).width;}))+10,height=lines.length*(fontSize+2)+5,best=null,bestCost=Infinity;
|
||||
offsets.forEach(function(o){var x=Math.max(width/2+4,Math.min(ww-width/2-4,item.anchor.x+o[0])),y=Math.max(height/2+4,Math.min(hh-height/2-5,item.anchor.y+o[1]));var box={x:x-width/2,y:y-height/2,w:width,h:height,cx:x,cy:y};var cost=Math.hypot(x-item.anchor.x,y-item.anchor.y)*.25;placed.forEach(function(p){var overlap=Math.max(0,Math.min(p.x+p.w,box.x+box.w)-Math.max(p.x,box.x))*Math.max(0,Math.min(p.y+p.h,box.y+box.h)-Math.max(p.y,box.y));cost+=overlap*15;});(obstacles||[]).forEach(function(p){cost+=Math.max(0,Math.min(p.x+p.w,box.x+box.w)-Math.max(p.x,box.x))*Math.max(0,Math.min(p.y+p.h,box.y+box.h)-Math.max(p.y,box.y))*25;});if(cost<bestCost){bestCost=cost;best=box;}});
|
||||
var detached=item.tiny||Math.hypot(best.cx-item.anchor.x,best.cy-item.anchor.y)>10;
|
||||
if(detached){context.strokeStyle='rgba(105,133,86,.65)';context.lineWidth=.8;context.beginPath();context.moveTo(Math.max(1,Math.min(ww-1,item.anchor.x)),Math.max(1,Math.min(hh-1,item.anchor.y)));context.lineTo(best.cx,best.cy);context.stroke();context.fillStyle='rgba(255,254,245,.94)';context.fillRect(best.x,best.y,best.w,best.h);context.strokeStyle='rgba(170,187,149,.7)';context.strokeRect(best.x+.5,best.y+.5,best.w-1,best.h-1);}
|
||||
context.lineWidth=2.5;context.strokeStyle='rgba(255,254,244,.95)';context.fillStyle='#486044';lines.forEach(function(line,index){var y=best.cy+(index-(lines.length-1)/2)*(fontSize+2);context.strokeText(line,best.cx,y);context.fillText(line,best.cx,y);});best.name=item.name;placed.push(best);
|
||||
});context.restore();return placed;
|
||||
}
|
||||
function drawReference(){var c=$('reference'),ww=c.clientWidth||500,hh=c.clientHeight||240,con=sizeCanvas(c,ww,hh);con.clearRect(0,0,ww,hh);var trans=staticTransform(ww,hh-18,8);level.regions.forEach(function(r,i){drawPiece(con,r,i,trans,{label:false});});drawDecorations(con,trans);if(level.id==='100000'&&hh>110){var important=level.regions.filter(function(r){return ['710000','810000','820000'].indexOf(r.id)>=0;}).map(function(r){return {name:shortName(r.name),anchor:trans(r.label||r.center),tiny:true};});renderLabels(con,important,ww,hh-18,8);}}
|
||||
function drawNext(){var c=$('next'),ww=c.clientWidth||64,hh=c.clientHeight||46,con=sizeCanvas(c,ww,hh);con.clearRect(0,0,ww,hh);if(!game||!game.queue.length){$('next-name').textContent=game?'已全部落下':'—';return;}var id=game.queue[0],r=level.regions[id],ring=r.rings[0],xs=ring.map(function(p){return p[0];}),ys=ring.map(function(p){return p[1];}),minx=Math.min.apply(null,xs),maxx=Math.max.apply(null,xs),miny=Math.min.apply(null,ys),maxy=Math.max.apply(null,ys),sc=Math.min((ww-8)/(maxx-minx),(hh-6)/(maxy-miny));drawPiece(con,{rings:[ring],center:r.center},id,function(p){return {x:(p[0]-(minx+maxx)/2)*sc+ww/2,y:(p[1]-(miny+maxy)/2)*sc+hh/2};},{});$('next-name').textContent=shortName(r.name);}
|
||||
function contactTransform(g){
|
||||
var left=g.hitUntil-game.clock,active=left>0&&motionAllowed(),progress=1-Math.max(0,left)/Engine.CONTACT_MS;
|
||||
var wave=active?Math.sin(progress*Math.PI*2)*Math.pow(1-progress,2)*.025*g.hitStrength:0,vertical=Math.abs(g.hitNormal.y)>=Math.abs(g.hitNormal.x);
|
||||
var sx=1+wave*(vertical?.55:-1),sy=1+wave*(vertical?-1:.55),center=g.body.position;
|
||||
return function(p){var q=game.worldPoint(g,p);return {x:center.x+(q.x-center.x)*sx,y:center.y+(q.y-center.y)*sy};};
|
||||
}
|
||||
function draw(){if(!game)return;ctx.clearRect(0,0,w,h);ctx.fillStyle='#f1f2e9';ctx.fillRect(0,0,w,h);ctx.fillStyle='#d8decd';for(var x=15;x<w;x+=22)for(var y=16;y<h;y+=22){ctx.beginPath();ctx.arc(x,y,.65,0,Math.PI*2);ctx.fill();}ctx.strokeStyle=game.overflow>0?'#bd3e42':'#d46e70';ctx.setLineDash([4,5]);ctx.beginPath();ctx.moveTo(0,Engine.DANGER_Y);ctx.lineTo(w,Engine.DANGER_Y);ctx.stroke();ctx.setLineDash([]);
|
||||
var labels=[];game.groups.forEach(function(g){var trans=contactTransform(g);g.ids.forEach(function(i){var r=level.regions[i];drawPiece(ctx,r,i,trans,{label:false,physical:true,impact:motionAllowed()&&g.hitUntil>game.clock});var points=r.rings[0].map(trans),xs=points.map(function(p){return p.x;}),ys=points.map(function(p){return p.y;}),rw=Math.max.apply(null,xs)-Math.min.apply(null,xs),rh=Math.max.apply(null,ys)-Math.min.apply(null,ys);labels.push({name:mode==='province'?shortName(r.name):r.name,anchor:trans(r.label||r.center),tiny:rw<32||rh<25});});if(g.ids.length===level.regions.length)drawDecorations(ctx,trans);});
|
||||
lastLabelBoxes=renderLabels(ctx,labels,w,h,Math.max(9,Math.min(12,12*Math.sqrt(game.zoom))),labelObstacles);
|
||||
if(motionAllowed())game.impacts.forEach(function(f){var life=Math.max(0,(f.until-game.clock)/Engine.SPARK_MS),radius=1.5+(1-life)*(2+f.strength*2);ctx.save();ctx.globalAlpha=life*.38;ctx.strokeStyle='#b8a779';ctx.lineWidth=1;ctx.beginPath();ctx.arc(f.x,f.y,radius,0,Math.PI*2);ctx.stroke();for(var i=0;i<2;i++){var angle=i*Math.PI+.7;ctx.beginPath();ctx.moveTo(f.x+Math.cos(angle)*(radius+1),f.y+Math.sin(angle)*(radius+1));ctx.lineTo(f.x+Math.cos(angle)*(radius+3),f.y+Math.sin(angle)*(radius+3));ctx.stroke();}ctx.restore();});
|
||||
game.fx.forEach(function(f){ctx.save();ctx.globalAlpha=Math.min(1,(f.until-game.clock)/500);ctx.textAlign='center';ctx.font='500 12px sans-serif';ctx.fillStyle='#557642';ctx.fillText(f.text,Math.max(70,Math.min(w-70,f.x)),f.y-28-(1600-f.until+game.clock)*.018);ctx.restore();});
|
||||
}
|
||||
function schedule(){if(!rafId&&!document.hidden&&game)rafId=requestAnimationFrame(frame);}
|
||||
function frame(t){rafId=0;if(!game||screen!=='game')return;if(!last)last=t;game.tick(t-last);last=t;if(screen!=='game')return;$('tank').style.transform='translate('+game.shake.offset.toFixed(2)+'px,'+game.shake.y.toFixed(2)+'px)';$('tank').classList.toggle('impact',game.wallHitUntil>game.clock);draw();if(t-uiAt>120){uiAt=t;updateUI();}if(game.status==='playing')schedule();}
|
||||
function stopInput(){clearInterval(holdTimer);holdTimer=null;inputDirection=0;pointerDirection=0;keys.left=false;keys.right=false;$('left').classList.remove('pressed');$('right').classList.remove('pressed');}
|
||||
function refreshInput(){var direction=pointerDirection||((keys.right?1:0)-(keys.left?1:0));if(!game||game.status!=='playing')direction=0;if(direction===inputDirection)return;clearInterval(holdTimer);holdTimer=null;inputDirection=direction;$('left').classList.toggle('pressed',direction<0);$('right').classList.toggle('pressed',direction>0);if(direction){game.nudge(direction);holdTimer=setInterval(function(){if(game&&game.status==='playing')game.nudge(direction);else stopInput();},150);}}
|
||||
function bindDirection(id,direction){var b=$(id);b.addEventListener('pointerdown',function(e){if(b.disabled)return;e.preventDefault();pointerDirection=direction;if(typeof b.setPointerCapture==='function')b.setPointerCapture(e.pointerId);refreshInput();});function release(){if(pointerDirection===direction){pointerDirection=0;refreshInput();}}['pointerup','pointercancel','lostpointercapture'].forEach(function(type){b.addEventListener(type,release);});b.addEventListener('click',function(e){if(e.detail===0&&game&&game.status==='playing')game.nudge(direction);});}
|
||||
bindDirection('left',-1);bindDirection('right',1);$('up').addEventListener('click',function(){if(game)game.nudgeUp();});
|
||||
document.addEventListener('keydown',function(e){if(screen!=='game'||$('modal').hasAttribute('open'))return;if(e.key===' '){e.preventDefault();if(!e.repeat)pause();return;}if(e.key==='ArrowUp'){e.preventDefault();if(!e.repeat&&game){if(game.nudgeUp())pulseButton($('up'),'bounce-pop');}return;}if(e.key!=='ArrowLeft'&&e.key!=='ArrowRight')return;e.preventDefault();if(e.repeat)return;keys[e.key==='ArrowLeft'?'left':'right']=true;refreshInput();});
|
||||
document.addEventListener('keyup',function(e){if(e.key==='ArrowLeft'||e.key==='ArrowRight'){keys[e.key==='ArrowLeft'?'left':'right']=false;refreshInput();}});
|
||||
document.addEventListener('pointerdown',function(){document.body.classList.add('using-pointer');});document.addEventListener('keydown',function(e){if(e.key==='Tab')document.body.classList.remove('using-pointer');});$('start').addEventListener('click',start);$('pause').addEventListener('click',pause);$('back').addEventListener('click',askBack);
|
||||
function openProvincePicker(){
|
||||
openModal('PICK A DESTINATION','<h2>这局,拼哪里?</h2><div id="province-grid" class="province-grid" role="group" aria-label="选择省区"></div><p class="picker-note">直辖市、港澳没有地级关卡;台湾省暂缺地级轮廓数据。省级版包含全部 34 个省级行政区。</p>');$('modal').classList.add('province-picker-modal');$('province-picker').classList.add('expanded');
|
||||
data.levels.slice(1).forEach(function(l){var button=document.createElement('button');button.type='button';button.textContent=shortName(l.name);button.setAttribute('data-province',l.id);button.setAttribute('aria-pressed',String(l.id===provinceCode));button.className=l.id===provinceCode?'selected':'';button.addEventListener('click',function(){provinceCode=l.id;selectLevel();closeModal();});$('province-grid').appendChild(button);});
|
||||
}
|
||||
function selectLevel(){level=mode==='province'?data.levels[0]:(data.levels.find(function(l){return l.id===provinceCode;})||data.levels[1]);updateUI();layout();}
|
||||
document.querySelectorAll('[data-mode]').forEach(function(b){b.addEventListener('click',function(){if(screen!=='entry'||performance.now()<suppressModeClickUntil)return;mode=b.getAttribute('data-mode');selectLevel();});});
|
||||
var modeTabs=document.querySelector('.mode-tabs');
|
||||
modeTabs.addEventListener('pointerdown',function(e){if(screen==='entry'&&e.isPrimary!==false)modeGesture={x:e.clientX,y:e.clientY,id:e.pointerId};});
|
||||
document.addEventListener('pointerup',function(e){if(!modeGesture||modeGesture.id!==e.pointerId)return;var dx=e.clientX-modeGesture.x,dy=e.clientY-modeGesture.y;modeGesture=null;if(screen==='entry'&&Math.abs(dx)>35&&Math.abs(dx)>Math.abs(dy)*1.3){mode=dx<0?'city':'province';suppressModeClickUntil=performance.now()+350;selectLevel();}});
|
||||
document.addEventListener('pointercancel',function(){modeGesture=null;});
|
||||
document.querySelectorAll('[data-speed]').forEach(function(b){b.addEventListener('click',function(){if(screen!=='entry')return;speed=Number(b.getAttribute('data-speed'));updateUI();});});document.querySelectorAll('[data-bounce]').forEach(function(b){b.addEventListener('click',function(){if(screen!=='entry')return;bounce=Number(b.getAttribute('data-bounce'));updateUI();});});$('province-picker').addEventListener('click',openProvincePicker);
|
||||
$('rules-button').addEventListener('click',function(){openModal('HOW TO PLAY','<h2>轻摇轻颠,拼一片山河</h2><ol><li><b>先选旅程,再开一局。</b>选择省级 / 地级版、地区、下落速度和弹性,点击开始。</li><li><b>晃动整个框。</b>按住左晃或右晃,点击中间上晃轻颠,也可使用键盘 ← ↑ →;框体左右晃动,所有碎片受到惯性影响。</li><li><b>相邻的边自动吸合。</b>碎片碰撞时会轻微弹跳、翻动,停稳后自动回正;只有真实相邻地区按正确方位接触时才合并。把所有碎片拼为一个整体即可通关。</li></ol><div class="rules-score">合并基础分:100 + 40 ×(合并后块数 − 2)<br>8.5 秒内连合,每次系数 +0.25,最高 ×2。<br>速度倍率:佛系看山 ×1 / 说走就走 ×1.5 / 一路狂飙 ×2 / 山河起飞 ×3。<br>跨海 / 隔区连接 ×0.8;通关再奖 1000 × 速度倍率。<br>三向晃动不限次数、不扣分;弹性不改变得分倍率,最佳纪录按速度和弹性分别保存。</div><p>弹性推荐“蹦蹦跳”,方便腾挪;“轻轻弹”偏沉稳,“弹力全开”需要控制节奏。稳定堆过顶部红线超过 2.4 秒,本局结束;也可随时从暂停页结束并生成成绩图。省级离岛和地级间隔分别标记为跨海、隔区连接。</p>');});
|
||||
$('data-button').addEventListener('click',function(){openModal('MAP NOTES','<h2>关于这片山河</h2><p>轮廓来源:阿里云 DataV.GeoAtlas 公开行政区数据,2026-10-16 下载,随包离线提供。轮廓已为游戏做简化,所有源数据外环及独立海域线段随包保留。</p><p>省级版包含 34 块;地级版提供 27 个省区关卡、333 个地级单元,包含地级市、自治州、地区、盟,不含县和县级市。直辖市、港澳不设地级关卡;数据源暂缺台湾省地级轮廓。</p><p>岛屿及未纳入的省直辖县造成的间隔,使用明确标记的跨海 / 隔区连接。地图仅供游戏示意,不用于测绘、导航或区划查询。</p><p>纪录仅在本地保存,存储失败不影响游玩。</p>');});
|
||||
function fitCard(){var box=$('result-card').parentNode,r=box.getBoundingClientRect(),sc=Math.max(.01,Math.min((r.width-22)/750,(r.height-22)/1400));$('result-card').style.width=Math.floor(750*sc)+'px';$('result-card').style.height=Math.floor(1400*sc)+'px';}
|
||||
function showResult(){
|
||||
stopInput();cancelAnimationFrame(rafId);rafId=0;draw();
|
||||
var snapshot=document.createElement('canvas');snapshot.width=canvas.width;snapshot.height=canvas.height;snapshot.getContext('2d').drawImage(canvas,0,0);
|
||||
result={reason:game.endReason||game.status,score:game.score,levelName:level.name,speed:speed,bounce:bounce,speedName:Engine.SPEEDS[speed].name,bounceName:Engine.BOUNCES[bounce].name,elapsed:game.clock,dropped:game.dropped,total:level.regions.length,largest:game.groups.reduce(function(n,g){return Math.max(n,g.ids.length);},0),maxChain:game.maxChain,history:game.history.map(function(p){return {ms:p.ms,score:p.score};})};
|
||||
window.PuzzleResult.render($('result-card'),result,snapshot);snapshot.width=0;snapshot.height=0;
|
||||
screen='result';$('game-screen').hidden=true;$('entry-screen').hidden=true;$('result-screen').hidden=false;$('result-title').textContent=window.PuzzleResult.title(result.reason);window.scrollTo(0,0);layout();
|
||||
}
|
||||
var exporting=false;
|
||||
async function exportCard(share){
|
||||
if(!result||exporting)return;var api=window.xhs&&window.xhs.miniTool,method=share?'postNote':'saveImageToPhotosAlbum';
|
||||
if(!api||typeof api[method]!=='function'){toast(share?'请在小红书小工具内打开笔记发布页':'请在小红书小工具内保存成绩图');return;}
|
||||
exporting=true;$('share-note').disabled=true;$('save-card').disabled=true;
|
||||
var card=result;
|
||||
try{var path=$('result-card').toDataURL('image/png');if(typeof api.writeTempFile==='function'){var out=await api.writeTempFile({data:path});if(!out||!out.filePath)throw Error('临时文件不可用');path=out.filePath;}
|
||||
if(share){await api.postNote({title:'我的山河拼图旅程',content:'这一程,山河相遇。'+card.levelName+',得分 '+card.score+';下落速度:'+card.speedName+';弹性:'+card.bounceName+';游玩 '+window.PuzzleResult.duration(card.elapsed)+'。来晃一晃,拼出你的山河! #山河拼图',pageType:'photo_publish',mediaInfo:{image_resources:[{url:path}]}});}
|
||||
else{await api.saveImageToPhotosAlbum({filePath:path});toast('成绩图已保存到相册');}
|
||||
}catch(e){toast(share?'分享未完成,可再次打开笔记发布页':'未能保存,请检查相册授权后重试');}
|
||||
finally{exporting=false;$('share-note').disabled=false;$('save-card').disabled=false;}
|
||||
}
|
||||
$('share-note').addEventListener('click',function(){exportCard(true);});$('save-card').addEventListener('click',function(){exportCard(false);});$('replay').addEventListener('click',start);$('result-back').addEventListener('click',showEntry);
|
||||
window.addEventListener('resize',layout);if(window.visualViewport&&typeof window.visualViewport.addEventListener==='function')window.visualViewport.addEventListener('resize',layout);window.addEventListener('blur',function(){stopInput();pause();});
|
||||
document.addEventListener('visibilitychange',function(){if(document.hidden){stopInput();pause();cancelAnimationFrame(rafId);rafId=0;}else{last=0;if(game&&game.status==='playing')schedule();}});
|
||||
layout();updateUI();storePromise=initStore();
|
||||
// Read-only development diagnostics: interaction is exclusively through the tank controls.
|
||||
window.shanheDebug={state:function(){return {screen:screen,status:game?game.status:'entry',score:game?game.score:0,level:level.id,speed:speed,bounce:bounce,bounceName:Engine.BOUNCES[bounce].name,history:game?game.history.map(function(p){return {ms:p.ms,score:p.score};}):[],elapsed:game?game.clock:0,result:result,shakeY:game?game.shake.y:0,dropped:game?game.dropped:0,remaining:game?game.queue.length:level.regions.length,groups:game?game.groups.length:0,shakeCount:game?game.shakeCount:0,shakeOffset:game?game.shake.offset:0,scale:game?game.scale:0,initialScale:game?game.initialScale:0,zoom:game?game.zoom:1,width:w,height:h,collisionCount:game?game.collisionCount:0,impactCount:game?game.impacts.length:0,contactPulse:game?game.groups.filter(function(g){return g.hitUntil>game.clock;}).length:0,labels:lastLabelBoxes.map(function(b){return {name:b.name,x:b.x,y:b.y,w:b.w,h:b.h};}),regions:game?game.groups.map(function(g){return {ids:g.ids.slice(),x:g.body.position.x,y:g.body.position.y,angle:g.body.angle,vx:g.body.velocity.x,vy:g.body.velocity.y};}):[]};}};
|
||||
})();
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.PuzzleCore=factory();})(typeof window!=='undefined'?window:this,function(){
|
||||
'use strict';
|
||||
function rotate(p,a){var c=Math.cos(a),s=Math.sin(a);return {x:p.x*c-p.y*s,y:p.x*s+p.y*c};}
|
||||
function angleDelta(a,b){var d=(a-b)%(Math.PI*2);if(d>Math.PI)d-=Math.PI*2;if(d< -Math.PI)d+=Math.PI*2;return d;}
|
||||
function linked(a,b,edges){for(var i=0;i<edges.length;i++){var e=edges[i];if((a.indexOf(e[0])>=0&&b.indexOf(e[1])>=0)||(a.indexOf(e[1])>=0&&b.indexOf(e[0])>=0))return e;}return null;}
|
||||
function canSnap(a,b,edges,tolerance){var edge=linked(a.ids,b.ids,edges);if(!edge||Math.abs(angleDelta(a.angle,b.angle))>.24)return null;var d=Math.hypot(a.tx-b.tx,a.ty-b.ty);return d<=tolerance?{edge:edge,distance:d}:null;}
|
||||
function mergePoints(size,chain,speed,sea){return Math.round((100+40*(size-2))*(1+Math.min(chain-1,4)*.25)*speed*(sea?.8:1));}
|
||||
function shuffle(a,rng){var b=a.slice();rng=rng||Math.random;for(var i=b.length-1;i>0;i--){var j=Math.floor(rng()*(i+1));var t=b[i];b[i]=b[j];b[j]=t;}return b;}
|
||||
function safeRecord(v){if(!v||typeof v!=='object'||Array.isArray(v))return {};var out={};Object.keys(v).forEach(function(k){if(/^\d+:[0-3](?::[0-2])?$/.test(k)&&typeof v[k]==='number'&&isFinite(v[k])&&v[k]>=0)out[k]=Math.floor(v[k]);});return out;}
|
||||
return {rotate:rotate,angleDelta:angleDelta,linked:linked,canSnap:canSnap,mergePoints:mergePoints,shuffle:shuffle,safeRecord:safeRecord};
|
||||
});
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory(require('matter-js'),require('./core.js'),require('poly-decomp'));else root.PuzzleGame=factory(root.Matter,root.PuzzleCore,root.decomp);})(typeof window!=='undefined'?window:this,function(M,C,decomp){
|
||||
'use strict';M.Common.setDecomp(decomp);
|
||||
var DANGER_Y=78,CONTACT_MS=160,SPARK_MS=180;
|
||||
var MAX_TILT=.16,MAX_X_SPEED=7.2,MAX_FALL_SPEED=9;
|
||||
function baseScale(level,w,h){var maxw=0,maxh=0;level.regions.forEach(function(r){var minx=Infinity,miny=Infinity,maxx=-Infinity,maxy=-Infinity;r.rings.forEach(function(ring){ring.forEach(function(p){minx=Math.min(minx,p[0]);maxx=Math.max(maxx,p[0]);miny=Math.min(miny,p[1]);maxy=Math.max(maxy,p[1]);});});maxw=Math.max(maxw,maxx-minx);maxh=Math.max(maxh,maxy-miny);});var city=String(level.id)!=='100000';return Math.min((w-20)*1.85/level.width,(w-20)*.9/maxw,(h-DANGER_Y-20)*.82/maxh)*(city?.70:1)*.90;}
|
||||
var SPEEDS=[{name:'佛系看山',interval:8500,gravity:.32,multiplier:1},{name:'说走就走',interval:6000,gravity:.48,multiplier:1.5},{name:'一路狂飙',interval:4000,gravity:.7,multiplier:2},{name:'山河起飞',interval:2500,gravity:1,multiplier:3}];
|
||||
var BOUNCES=[{name:'轻轻弹',restitution:.65,hop:2.15,rise:90,air:.022,push:1,maxX:7.2,friction:.22,scatter:0},{name:'蹦蹦跳',restitution:.82,hop:6,rise:250,air:.012,push:1.22,maxX:9.5,friction:.16,scatter:2.6},{name:'弹力全开',restitution:.96,hop:14,rise:540,air:.006,push:1.7,maxX:13,friction:.10,scatter:5}];
|
||||
function Game(level,width,height,speed,emit,rng,bounce){
|
||||
this.bounceIndex=BOUNCES[bounce]?bounce:0;this.bounce=BOUNCES[this.bounceIndex];this.history=[{ms:0,score:0}];this.endReason=null;this.lastUp=-1000;this.level=level;this.w=width;this.h=height;this.speed=SPEEDS[speed];this.emit=emit||function(){};this.rng=rng||Math.random;this.scale=baseScale(level,width,height);this.initialScale=this.scale;this.zoom=1;this.shake={offset:0,velocity:0,y:0,vy:0};this.shakeCount=0;this.engine=M.Engine.create({enableSleeping:true});this.engine.gravity.y=this.speed.gravity;this.groups=[];this.queue=C.shuffle(level.regions.map(function(_,i){return i;}),this.rng);this.score=0;this.chain=0;this.maxChain=0;this.merges=0;this.dropped=0;this.clock=0;this.lastMerge=-99999;this.nextAt=0;this.overflow=0;this.status='ready';this.fx=[];this.impacts=[];this.collisionCount=0;this.wallHitUntil=0;
|
||||
var self=this;M.Events.on(this.engine,'collisionStart',function(e){self.onContacts(e.pairs,true);});M.Events.on(this.engine,'collisionActive',function(e){self.onContacts(e.pairs,false);});
|
||||
this.walls=[M.Bodies.rectangle(width/2,height+25,width+100,50,{isStatic:true}),M.Bodies.rectangle(-25,height/2,50,height*4,{isStatic:true}),M.Bodies.rectangle(width+25,height/2,50,height*4,{isStatic:true})];M.Composite.add(this.engine.world,this.walls);
|
||||
}
|
||||
Game.prototype.pose=function(g){var r=C.rotate({x:g.center.x,y:g.center.y},g.body.angle);return {ids:g.ids,angle:g.body.angle,tx:g.body.position.x-r.x,ty:g.body.position.y-r.y};};
|
||||
Game.prototype.worldPoint=function(g,p){var pose=this.pose(g),r=C.rotate({x:p[0]*this.scale,y:p[1]*this.scale},pose.angle);return {x:r.x+pose.tx,y:r.y+pose.ty};};
|
||||
Game.prototype.createGroup=function(ids,pose){var self=this,parts=[];
|
||||
ids.forEach(function(id){var region=self.level.regions[id];region.rings.forEach(function(ring,ri){var vs=ring.map(function(p){return {x:p[0]*self.scale,y:p[1]*self.scale};});if(vs.length<3||M.Vertices.area(vs)<.8)return;var coords=vs.map(function(v){return [v.x,v.y];});decomp.removeDuplicatePoints(coords,.01);decomp.removeCollinearPoints(coords,.01);if(coords.length<3)return;vs=coords.map(function(p){return {x:p[0],y:p[1]};});if(!decomp.isSimple(coords))vs=M.Vertices.hull(vs);var center=M.Vertices.centre(vs);var b=M.Bodies.fromVertices(center.x,center.y,[vs],{friction:self.bounce.friction,frictionStatic:.38,restitution:self.bounce.restitution,slop:.1},true,.5,1,.01);if(b){if(b.parts.length>1)parts=parts.concat(b.parts.slice(1));else parts.push(b);}});
|
||||
if(!parts.length||region.rings.every(function(r){return M.Vertices.area(r.map(function(p){return {x:p[0]*self.scale,y:p[1]*self.scale};}))<.8;}))parts.push(M.Bodies.circle(region.center[0]*self.scale,region.center[1]*self.scale,4));});
|
||||
var body=M.Body.create({parts:parts,friction:this.bounce.friction,frictionStatic:.38,restitution:this.bounce.restitution,frictionAir:this.bounce.air,slop:.1,sleepThreshold:75});M.Body.setInertia(body,body.inertia*2);var g={ids:ids.slice(),body:body,center:{x:body.position.x,y:body.position.y},born:this.clock,supportedUntil:-1,lastHop:-1000,hitUntil:0,hitStrength:0,hitNormal:{x:0,y:1}};
|
||||
M.Body.rotate(body,pose.angle,{x:0,y:0});M.Body.translate(body,{x:pose.tx,y:pose.ty});body.plugin.puzzleGroup=g;M.Composite.add(this.engine.world,body);this.groups.push(g);return g;};
|
||||
Game.prototype.start=function(){if(this.status!=='ready')return;this.status='playing';this.spawn();};
|
||||
Game.prototype.spawn=function(){if(!this.queue.length)return;var id=this.queue.shift(),r=this.level.regions[id],angle=0;var x=this.w*(.25+this.rng()*.5),y=20;var g=this.createGroup([id],{angle:angle,tx:x-r.center[0]*this.scale,ty:y-r.center[1]*this.scale});var b=g.body.bounds;if(b.min.x<10)M.Body.translate(g.body,{x:10-b.min.x,y:0});if(b.max.x>this.w-10)M.Body.translate(g.body,{x:this.w-10-b.max.x,y:0});if(b.min.y<8)M.Body.translate(g.body,{x:0,y:8-b.min.y});this.dropped++;this.nextAt=this.clock+this.speed.interval;this.emit('spawn',g);};
|
||||
Game.prototype.merge=function(a,b,edge){var pa=this.pose(a),pb=this.pose(b);var anchor=a.ids.length>=b.ids.length?a:b;var pose=anchor===a?pa:pb;var ids=a.ids.concat(b.ids);
|
||||
M.Composite.remove(this.engine.world,a.body);M.Composite.remove(this.engine.world,b.body);this.groups=this.groups.filter(function(g){return g!==a&&g!==b;});var g=this.createGroup(ids,pose);this.chain=this.clock-this.lastMerge<=8500?this.chain+1:1;this.maxChain=Math.max(this.maxChain,this.chain);this.lastMerge=this.clock;this.merges++;var points=C.mergePoints(ids.length,this.chain,this.speed.multiplier,edge[2]);this.score+=points;this.recordScore();this.fx.push({x:g.body.position.x,y:g.body.position.y,text:(edge[2]===1?'跨海连接 ':edge[2]===2?'隔区连接 ':'合并成功 ')+ '+'+points,until:this.clock+1600});this.fitGroup(g);this.emit('merge',{group:g,points:points,sea:edge[2]});
|
||||
if(ids.length===this.level.regions.length){this.score+=Math.round(1000*this.speed.multiplier);this.complete('won');}return g;};
|
||||
Game.prototype.tryMerges=function(){for(var i=0;i<this.groups.length;i++)for(var j=0;j<i;j++){var a=this.groups[i],b=this.groups[j];var plan=C.canSnap(this.pose(a),this.pose(b),this.level.edges,22);if(plan){this.merge(a,b,plan.edge);return true;}}return false;};
|
||||
Game.prototype.tick=function(dt){if(this.status!=='playing')return;dt=Math.min(dt,100);this.clock+=dt;this.accumulator=(this.accumulator||0)+dt;while(this.accumulator>=1000/60){this.stepShake(1000/60);M.Engine.update(this.engine,1000/60);this.limitMotion();this.accumulator-=1000/60;}for(var k=0;k<4;k++)if(!this.tryMerges())break;
|
||||
if(this.status!=='playing')return;
|
||||
if(this.queue.length&&this.clock>=this.nextAt)this.spawn();
|
||||
var crowded=this.groups.some(function(g){return this.clock-g.born>5000&&g.body.bounds.min.y<DANGER_Y&&g.body.speed<1.4;},this);this.overflow=crowded?this.overflow+dt:Math.max(0,this.overflow-dt*2);if(this.overflow>2400){this.complete('lost');}
|
||||
this.impacts=this.impacts.filter(function(f){return f.until>this.clock;},this);
|
||||
this.fx=this.fx.filter(function(f){return f.until>this.clock;},this);};
|
||||
Game.prototype.clamp=function(g){var b=g.body.bounds,dx=0,dy=0;if(b.min.x<4)dx=4-b.min.x;else if(b.max.x>this.w-4)dx=this.w-4-b.max.x;if(b.min.y<4)dy=4-b.min.y;else if(b.max.y>this.h-4)dy=this.h-4-b.max.y;M.Body.translate(g.body,{x:dx,y:dy});};
|
||||
// The tank moves on a damped spring. Its acceleration drives the bodies in
|
||||
// the opposite direction in tank-local coordinates; visual and physics share it.
|
||||
Game.prototype.nudge=function(direction){
|
||||
if(this.status!=='playing')return false;
|
||||
var previous=this.shake.velocity;this.shake.velocity=Math.max(-.6,Math.min(.6,this.shake.velocity+(direction<0?-.38:.38)));var impulse=(this.shake.velocity-previous)*1000/60;
|
||||
this.groups.forEach(function(g,index){
|
||||
var supported=g.body.isSleeping||g.supportedUntil>=this.clock;M.Sleeping.set(g.body,false);var variation=(Math.sin((g.ids[0]+1)*12.9898+(this.shakeCount+1)*7.23)+1)/2,weight=1/(1+(g.ids.length-1)*.12);
|
||||
var vx=g.body.velocity.x-impulse*(.65+variation*.2)*weight*this.bounce.push,vy=g.body.velocity.y;
|
||||
// A short toss only on support/landing. Holding cannot repeatedly boost airborn pieces.
|
||||
if(supported&&this.clock-g.lastHop>500&&g.body.bounds.min.y>8){var height=Math.min((14+variation*14)*this.bounce.hop*weight,this.riseLimit()*.92),acceleration=this.speed.gravity*1000/60*1000/60*.001;vy=Math.min(vy,-Math.sqrt(2*acceleration*height));g.lastHop=this.clock;}
|
||||
M.Body.setVelocity(g.body,{x:Math.max(-this.bounce.maxX,Math.min(this.bounce.maxX,vx)),y:vy});
|
||||
var tilt=(variation-.5)*.014-direction*.005;M.Body.setAngularVelocity(g.body,Math.max(-.02,Math.min(.02,g.body.angularVelocity+tilt*weight)));
|
||||
},this);this.shakeCount++;return true;
|
||||
};
|
||||
// Score events retain the exact active-play time; pauses never advance the clock.
|
||||
Game.prototype.recordScore=function(){var last=this.history[this.history.length-1];if(last.ms===this.clock){last.score=this.score;return;}this.history.push({ms:this.clock,score:this.score});};
|
||||
Game.prototype.complete=function(reason){if(this.endReason)return false;this.endReason=reason;this.status=reason==='stopped'?'ended':reason;this.recordScore();this.emit('end',{won:reason==='won',reason:reason});return true;};
|
||||
Game.prototype.finish=function(){if(this.status!=='playing'&&this.status!=='paused')return false;return this.complete('stopped');};
|
||||
// The upward kick moves the whole tank and tosses every group, with a cooldown
|
||||
// and a fixed rise cap so repeated taps cannot lift pieces out of the container.
|
||||
Game.prototype.riseLimit=function(){return Math.min(this.bounce.rise,Math.max(32,this.h*.62));};
|
||||
Game.prototype.nudgeUp=function(){if(this.status!=='playing'||this.clock-this.lastUp<420)return false;this.lastUp=this.clock;this.shake.vy=-.48;this.groups.forEach(function(g){M.Sleeping.set(g.body,false);var weight=1/(1+(g.ids.length-1)*.12),supported=g.supportedUntil>=this.clock||g.body.speed<.2,acc=this.speed.gravity*.001*Math.pow(1000/60,2),height=Math.min((supported?24:10)*this.bounce.hop*weight,this.riseLimit()*.92),scatter=Math.sin((g.ids[0]+1)*7.7+this.shakeCount*2.3)*this.bounce.scatter*weight;M.Body.setVelocity(g.body,{x:Math.max(-this.bounce.maxX,Math.min(this.bounce.maxX,g.body.velocity.x+scatter)),y:Math.min(g.body.velocity.y,-Math.sqrt(2*acc*height))});g.lastHop=this.clock;},this);this.shakeCount++;return true;};
|
||||
Game.prototype.onContacts=function(pairs,started){
|
||||
pairs.forEach(function(pair){
|
||||
var a=pair.bodyA.parent||pair.bodyA,b=pair.bodyB.parent||pair.bodyB,ga=a.plugin&&a.plugin.puzzleGroup,gb=b.plugin&&b.plugin.puzzleGroup;
|
||||
if(!ga&&!gb)return;
|
||||
var collision=pair.collision,normal=collision.normal;
|
||||
if(Math.abs(normal.y)>.35){if(ga&&(b.isStatic||b.position.y>a.position.y))ga.supportedUntil=this.clock+55;if(gb&&(a.isStatic||a.position.y>b.position.y))gb.supportedUntil=this.clock+55;}
|
||||
if(!started)return;
|
||||
var relative=Math.hypot(a.velocity.x-b.velocity.x,a.velocity.y-b.velocity.y);
|
||||
if(relative<.8)return;
|
||||
var fresh=false;[ga,gb].forEach(function(g){if(g&&g.hitUntil<=this.clock){g.hitUntil=this.clock+CONTACT_MS;g.hitNormal={x:normal.x,y:normal.y};g.hitStrength=Math.min(1,relative/6);fresh=true;}},this);if(!fresh)return;
|
||||
this.collisionCount++;if(a.isStatic||b.isStatic)this.wallHitUntil=this.clock+CONTACT_MS;
|
||||
var contacts=collision.supports||[],point=contacts[0]||{x:(a.position.x+b.position.x)/2,y:(a.position.y+b.position.y)/2};
|
||||
this.impacts.push({x:Math.max(3,Math.min(this.w-3,point.x)),y:Math.max(3,Math.min(this.h-3,point.y)),strength:Math.min(1,relative/6),until:this.clock+SPARK_MS});if(this.impacts.length>20)this.impacts.shift();
|
||||
},this);
|
||||
};
|
||||
Game.prototype.limitMotion=function(){
|
||||
this.groups.forEach(function(g){var b=g.body,vx=Math.max(-this.bounce.maxX,Math.min(this.bounce.maxX,b.velocity.x)),vy=Math.max(-Math.sqrt(2*this.speed.gravity*.001*Math.pow(1000/60,2)*this.riseLimit()),Math.min(MAX_FALL_SPEED,b.velocity.y));
|
||||
var actual=M.Bounds.create(b.vertices);
|
||||
var dx=actual.min.x< -2?1-actual.min.x:actual.max.x>this.w+2?this.w-1-actual.max.x:0;
|
||||
var dy=actual.max.y>this.h+2?this.h-1-actual.max.y:actual.min.y< -6&&this.clock-g.born>200?-6-actual.min.y:0;
|
||||
if(dx){M.Body.translate(b,{x:dx,y:0});vx=-vx*.24;}if(dy){M.Body.translate(b,{x:0,y:dy});vy=dy<0?-Math.abs(vy)*.24:Math.max(0,vy);}
|
||||
M.Body.setVelocity(b,{x:vx,y:vy});
|
||||
// Real slight rocking, followed by a damped return north; never uncontrolled spinning.
|
||||
var angle=C.angleDelta(b.angle,0),turn=b.angularVelocity*.84-angle*.022;
|
||||
if(Math.abs(angle)>MAX_TILT){M.Body.setAngle(b,angle<0?-MAX_TILT:MAX_TILT);turn*=.2;}
|
||||
if(Math.abs(angle)<.0004&&Math.abs(turn)<.0002){M.Body.setAngle(b,0);turn=0;}
|
||||
M.Body.setAngularVelocity(b,Math.max(-.025,Math.min(.025,turn)));
|
||||
},this);
|
||||
};
|
||||
Game.prototype.stepShake=function(dt){
|
||||
var motion=this.shake,acceleration=-.00045*motion.offset-.022*motion.velocity;motion.velocity+=acceleration*dt;motion.offset+=motion.velocity*dt;if(Math.abs(motion.offset)>14){motion.offset=motion.offset<0?-14:14;motion.velocity*=.3;}
|
||||
if(Math.abs(motion.offset)<.015&&Math.abs(motion.velocity)<.001){motion.offset=0;motion.velocity=0;}
|
||||
var ay=-.0006*motion.y-.028*motion.vy;motion.vy+=ay*dt;motion.y+=motion.vy*dt;if(Math.abs(motion.y)>12){motion.y=motion.y<0?-12:12;motion.vy*=.3;}if(Math.abs(motion.y)<.015&&Math.abs(motion.vy)<.001){motion.y=0;motion.vy=0;}
|
||||
this.groups.forEach(function(g){if(Math.abs(acceleration)>.00003){M.Sleeping.set(g.body,false);M.Body.applyForce(g.body,g.body.position,{x:-acceleration*g.body.mass*.8*this.bounce.push,y:0});}},this);
|
||||
};
|
||||
Game.prototype.rescale=function(nextScale){
|
||||
var ratio=nextScale/this.scale,pivot={x:this.w/2,y:this.h-8};
|
||||
var saved=this.groups.map(function(g){return {group:g,pose:this.pose(g),vx:g.body.velocity.x,vy:g.body.velocity.y,born:g.born};},this);
|
||||
saved.forEach(function(s){M.Composite.remove(this.engine.world,s.group.body);},this);this.groups=[];this.scale=nextScale;this.zoom=this.scale/this.initialScale;
|
||||
saved.forEach(function(s){var pose={tx:pivot.x+(s.pose.tx-pivot.x)*ratio,ty:pivot.y+(s.pose.ty-pivot.y)*ratio,angle:s.pose.angle};var fresh=this.createGroup(s.group.ids,pose),g=s.group;g.body=fresh.body;g.body.plugin.puzzleGroup=g;g.center=fresh.center;g.born=s.born;this.groups[this.groups.indexOf(fresh)]=g;M.Body.setVelocity(g.body,{x:s.vx*ratio,y:s.vy*ratio});},this);
|
||||
};
|
||||
Game.prototype.fitGroup=function(g){var b=g.body.bounds;var factor=Math.min(1,(this.w-20)/(b.max.x-b.min.x),(this.h-DANGER_Y-24)/(b.max.y-b.min.y));if(factor<.999){this.rescale(this.scale*factor);this.emit('zoom',this.zoom);}
|
||||
b=g.body.bounds;var dx=b.min.x<10?10-b.min.x:b.max.x>this.w-10?this.w-10-b.max.x:0;var dy=b.max.y>this.h-10?this.h-10-b.max.y:b.min.y<DANGER_Y+8?DANGER_Y+8-b.min.y:0;
|
||||
if(dx||dy){this.groups.forEach(function(group){M.Body.translate(group.body,{x:dx,y:dy});});}
|
||||
};
|
||||
Game.prototype.resize=function(w,h){var oldw=this.w,oldh=this.h;var saved=this.groups.map(function(g){return {ids:g.ids,angle:g.body.angle,x:g.body.position.x/oldw,y:g.body.position.y/oldh,born:g.born};});this.groups.forEach(function(g){M.Composite.remove(this.engine.world,g.body);},this);this.walls.forEach(function(b){M.Composite.remove(this.engine.world,b);},this);this.groups=[];this.w=w;this.h=h;this.initialScale=baseScale(this.level,w,h);this.scale=this.initialScale*this.zoom;this.walls=[M.Bodies.rectangle(w/2,h+25,w+100,50,{isStatic:true}),M.Bodies.rectangle(-25,h/2,50,h*4,{isStatic:true}),M.Bodies.rectangle(w+25,h/2,50,h*4,{isStatic:true})];M.Composite.add(this.engine.world,this.walls);saved.forEach(function(s){var g=this.createGroup(s.ids,{tx:0,ty:0,angle:s.angle});M.Body.setPosition(g.body,{x:s.x*w,y:s.y*h});g.born=s.born;this.clamp(g);},this);};
|
||||
Game.prototype.destroy=function(){M.Events.off(this.engine);M.Composite.clear(this.engine.world,false);M.Engine.clear(this.engine);this.groups=[];};
|
||||
return {Game:Game,SPEEDS:SPEEDS,BOUNCES:BOUNCES,DANGER_Y:DANGER_Y,CONTACT_MS:CONTACT_MS,SPARK_MS:SPARK_MS,baseScale:baseScale,MAX_TILT:MAX_TILT,MAX_X_SPEED:MAX_X_SPEED,MAX_FALL_SPEED:MAX_FALL_SPEED};
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="theme-color" content="#f4f3ec">
|
||||
<title>山河拼图 · 把山河拼在一起</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<section id="entry-screen" class="entry-screen" aria-label="选择旅程">
|
||||
<header class="header"><div class="brand"><span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 32 32"><path d="M3 24 12 9l6 10 4-6 7 11Z" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="23" cy="8" r="2" fill="currentColor"/></svg></span><span>山河拼图<small>SHAN HE · MAP PUZZLE</small></span></div><button class="text-button" id="rules-button">玩法说明 ↗</button></header>
|
||||
<main class="entry-main">
|
||||
<div class="entry-story"><div class="eyebrow"><span></span> 一片一片,认识中国</div><h1>把山河,<br><em>拼在一起。</em></h1><p class="lead">晃动这个框,<br>让相邻的山河,在碰撞中相遇。</p><div class="entry-map"><canvas id="reference" width="960" height="700" aria-label="所选旅程的完整地图"></canvas><span id="map-caption">34 个省级行政区 · 等你拼完整</span></div><div class="entry-instruction"><span>←</span><p>左右轻摇,向上轻颠<br><strong>晃动整个容器,碎片自动吸合</strong></p><span>→</span></div></div>
|
||||
<section class="setup"><div class="section-title"><span class="eyebrow">CHOOSE YOUR JOURNEY</span><span>01</span></div><h2>选择你的旅程</h2><p class="setup-intro">从一片故乡,出发去看山河。</p>
|
||||
<div class="mode-tabs" role="group" aria-label="版本选择"><button data-mode="province" class="selected" aria-pressed="true">省级版 <small>拼中国</small></button><button data-mode="city" aria-pressed="false">地级版 <small>拼家乡</small></button></div>
|
||||
<div id="city-select-panel" hidden><button id="province-picker" class="province-picker" aria-haspopup="dialog"><span class="destination-mark" aria-hidden="true">⌖</span><span class="destination-copy"><small>本局目的地</small><strong id="province-name">浙江省</strong></span><span id="province-count" class="destination-count">11 个地级单元</span><span class="destination-arrow" aria-hidden="true">⌄</span></button><p id="city-note" class="field-note"></p></div>
|
||||
<div class="speed-heading"><label>下落速度</label><span id="multiplier">得分 ×1</span></div><div class="speed-options" role="group" aria-label="速度档位"><button data-speed="0" class="selected" aria-pressed="true"><span>01</span><strong>佛系看山</strong><small>8.5 秒 / 块</small></button><button data-speed="1" aria-pressed="false"><span>02</span><strong>说走就走</strong><small>6 秒 / 块</small></button><button data-speed="2" aria-pressed="false"><span>03</span><strong>一路狂飙</strong><small>4 秒 / 块</small></button><button data-speed="3" aria-pressed="false"><span>04</span><strong>山河起飞</strong><small>2.5 秒 / 块</small></button></div><p id="speed-note" class="field-note"></p>
|
||||
<div class="bounce-heading"><label>碰撞弹性</label><span>独立调节 · 不改变得分倍率</span></div><div class="bounce-options" role="group" aria-label="弹性档位"><button data-bounce="0" aria-pressed="false"><strong>轻轻弹</strong><small>沉稳慢摇</small></button><button data-bounce="1" class="selected" aria-pressed="true"><strong>蹦蹦跳</strong><small>推荐 · 好拼</small></button><button data-bounce="2" aria-pressed="false"><strong>弹力全开</strong><small>强力起飞</small></button></div>
|
||||
<div class="journey-summary"><div><span>这次要拼</span><strong id="journey-count">34 块山河</strong></div><div><span>本地最佳</span><strong id="entry-best">—</strong></div></div>
|
||||
<button id="start" class="primary start-button">开启这局旅程 <span>→</span></button><p class="start-note">选好后直接开局 · 晃动不限次数</p>
|
||||
</section></main>
|
||||
<footer><span>让地理变成一次相遇</span><button id="data-button" class="text-button">离线可玩 · 数据说明</button></footer>
|
||||
</section>
|
||||
<section id="game-screen" class="game-screen" hidden aria-label="山河拼图游戏">
|
||||
<div class="game-topbar"><button id="back" class="nav-button" aria-label="返回旅程选择">←</button><div><strong id="game-title">中国 · 省级拼图</strong><span id="game-speed">佛系看山 · 得分 ×1</span></div><button id="pause" class="nav-button" aria-label="暂停游戏">Ⅱ</button></div>
|
||||
<div class="game-hud"><div class="score"><span class="stat-label">本局得分</span><strong id="score">0</strong></div><div><span class="stat-label">最大拼合</span><strong><span id="merged">0</span><small> / <span id="total">34</span></small></strong></div><div class="next-inline"><canvas id="next" width="150" height="110" aria-label="下一个地区预览"></canvas><div><span class="stat-label">下一块</span><strong id="next-name">—</strong></div></div></div>
|
||||
<div class="tank-stage"><div class="board-wrap" id="tank"><canvas id="board" width="840" height="1120" aria-label="晃动容器中的地图碎片。使用左晃、上晃、右晃按钮或键盘方向键操作整个框。"></canvas><div class="board-tag"><span class="live-dot"></span><span id="board-name">山河容器</span></div><div class="danger-label">堆叠警戒线</div><div id="board-status" class="board-status" aria-live="polite"></div></div></div>
|
||||
<div class="game-progress"><span id="progress-label">已落下 0 / 34 块</span><span>左右轻摇,向上轻颠</span></div>
|
||||
<div class="controls" role="group" aria-label="容器晃动操作"><button id="left" aria-label="向左晃动整个容器"><span class="control-arrow" aria-hidden="true">←</span><span class="control-copy"><strong>左晃</strong><small>按住持续晃动</small></span></button><button id="up" aria-label="向上晃动整个容器"><span class="control-copy"><strong>↑ 上晃</strong><small>点击轻颠</small></span></button><button id="right" aria-label="向右晃动整个容器"><span class="control-copy"><strong>右晃</strong><small>按住持续晃动</small></span><span class="control-arrow" aria-hidden="true">→</span></button></div>
|
||||
</section>
|
||||
<section id="result-screen" class="result-screen" hidden aria-label="旅程成绩">
|
||||
<div class="result-topbar"><button id="result-back" class="text-button">← 选择旅程</button><span class="eyebrow">YOUR JOURNEY</span></div>
|
||||
<h2 id="result-title">这一程,山河相遇。</h2><p class="result-intro">结局已留在图中,带着这片山河去分享。</p>
|
||||
<div class="card-preview-wrap"><canvas id="result-card" width="750" height="1400" aria-label="成绩卡:得分、结局画面、速度与弹性、得分曲线"></canvas></div>
|
||||
<div class="result-actions"><button id="share-note" class="primary">发小红书 ↗</button><button id="save-card" class="secondary">保存成绩图</button><button id="replay" class="secondary">再来一局</button></div><p class="result-footnote">分享后可编辑笔记 · 确认后发布</p>
|
||||
</section>
|
||||
</div>
|
||||
<div id="toast" role="status" class="toast" hidden></div>
|
||||
<dialog id="modal"><div class="modal-top"><span class="eyebrow" id="modal-kicker">HOW TO PLAY</span><button id="close-modal" class="nav-button" aria-label="关闭弹窗">×</button></div><div id="modal-content"></div><div id="modal-actions"></div></dialog>
|
||||
<script src="./vendor/decomp.min.js"></script><script src="./vendor/matter.min.js"></script><script src="./maps.js"></script><script src="./core.js"></script><script src="./game.js"></script><script src="./result.js"></script><script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,31 @@
|
||||
(function(root){
|
||||
'use strict';
|
||||
function text(c,value,x,y,size,color,align){c.fillStyle=color||'#365c47';c.font=size+'px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif';c.textAlign=align||'left';c.fillText(String(value),x,y);}
|
||||
function duration(ms){var seconds=Math.floor(ms/1000);return Math.floor(seconds/60)+'分'+String(seconds%60)+'秒';}
|
||||
function minute(ms){return (ms/60000).toFixed(ms>=600000?0:2).replace(/\.00$/,'');}
|
||||
function title(reason){return reason==='won'?'这一片山河,完整了。':reason==='lost'?'山河未完,下次再会。':'这一程,山河相遇。';}
|
||||
function chart(c,history,elapsed,score){
|
||||
var x=100,y=1105,ww=550,hh=145,maxTime=Math.max(1000,elapsed),maxScore=Math.max(100,Math.ceil(score/100)*100);
|
||||
text(c,'每一步,都算数',58,1040,24);text(c,'得分随游玩时间变化 · 暂停不计时',58,1072,15,'#88917f');
|
||||
c.lineWidth=1;c.strokeStyle='#dfe4d5';
|
||||
for(var i=0;i<=2;i++){var yy=y+hh-hh*i/2;c.beginPath();c.moveTo(x,yy);c.lineTo(x+ww,yy);c.stroke();text(c,Math.round(maxScore*i/2),x-14,yy+5,14,'#89957d','right');}
|
||||
for(var j=0;j<=2;j++)text(c,minute(maxTime*j/2),x+ww*j/2,y+hh+26,14,'#89957d','center');
|
||||
text(c,'分钟',x+ww,y+hh+53,14,'#89957d','right');
|
||||
var points=history.map(function(p){return {x:x+ww*p.ms/maxTime,y:y+hh-hh*p.score/maxScore};});
|
||||
c.beginPath();points.forEach(function(p,i){if(i)c.lineTo(p.x,p.y);else c.moveTo(p.x,p.y);});c.lineTo(points[points.length-1].x,y+hh);c.lineTo(x,y+hh);c.closePath();c.fillStyle='rgba(126,159,96,.12)';c.fill();
|
||||
c.beginPath();points.forEach(function(p,i){if(i)c.lineTo(p.x,p.y);else c.moveTo(p.x,p.y);});c.strokeStyle='#5e8050';c.lineWidth=3;c.stroke();var end=points[points.length-1];c.beginPath();c.arc(end.x,end.y,5,0,Math.PI*2);c.fillStyle='#c98559';c.fill();
|
||||
}
|
||||
function render(canvas,result,snapshot){
|
||||
canvas.width=750;canvas.height=1400;var c=canvas.getContext('2d');c.fillStyle='#f4f3ec';c.fillRect(0,0,750,1400);
|
||||
text(c,'山河拼图',58,63,27);text(c,'SHAN HE · JOURNEY '+(result.reason==='won'?'COMPLETE':'DIARY'),692,62,12,'#89957d','right');
|
||||
text(c,title(result.reason),58,115,32);text(c,result.score.toLocaleString('zh-CN'),58,199,68);text(c,'本局得分',692,194,18,'#89957d','right');
|
||||
c.fillStyle='#e8eddf';c.fillRect(48,226,654,67);text(c,result.levelName+' · '+result.speedName,67,254,19);text(c,'弹性 '+result.bounceName+' / '+duration(result.elapsed)+' / 已落下 '+result.dropped+' 块',67,280,16,'#748867');
|
||||
// Copy the actual frozen tank, including its red line and unmerged pieces.
|
||||
c.fillStyle='#e8ece1';c.fillRect(48,316,654,655);var sc=Math.min(628/snapshot.width,625/snapshot.height),dw=snapshot.width*sc,dh=snapshot.height*sc,dx=(750-dw)/2,dy=331+(625-dh)/2;
|
||||
c.fillStyle='#7895a0';c.fillRect(dx-7,dy,dw+14,dh+9);c.drawImage(snapshot,dx,dy,dw,dh);
|
||||
text(c,'结束时的山河',69,999,17,'#7c8c70');text(c,'最大拼合 '+result.largest+' / '+result.total+' · 最佳 '+result.maxChain+' 连合',683,999,17,'#7c8c70','right');
|
||||
chart(c,result.history,result.elapsed,result.score);
|
||||
text(c,'把每一块远方,拼成自己的旅程。',375,1350,18,'#7f9071','center');text(c,'地图为游戏示意 · 轮廓来源 DataV.GeoAtlas',375,1380,12,'#9ca58f','center');
|
||||
}
|
||||
root.PuzzleResult={render:render,title:title,duration:duration};
|
||||
})(window);
|
||||
@@ -0,0 +1,44 @@
|
||||
:root{--paper:#f4f3ec;--card:#fffef9;--ink:#283d34;--muted:#88917f;--line:#dedfd3;--green:#365c47;--orange:#c98559}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.6 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none;padding-top:0;padding-top:var(--safe-area-inset-top,env(safe-area-inset-top,0px));padding-bottom:0;padding-bottom:var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))}
|
||||
button,select{font:inherit;color:inherit}button{cursor:pointer;touch-action:manipulation;border:0}button:disabled{cursor:default;opacity:.42}button:focus,select:focus{outline:2px solid var(--orange);outline-offset:3px}button:hover:not(:disabled){filter:brightness(.97)}[hidden]{display:none!important}.app{max-width:1180px;margin:0 auto;padding:0 46px}button{min-height:38px}.text-button{background:none;color:#7b8970;font-size:12px;padding:6px 0}.header{height:100px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand{display:flex;align-items:center;font-size:22px;font-weight:650;letter-spacing:3px}.brand-mark{display:block;width:44px;height:44px;padding:6px;background:var(--green);color:#f5f2d8;border-radius:12px;transform:rotate(-4deg);margin-right:13px}.brand-mark svg{width:100%;height:100%}.brand small{display:block;font-size:8px;letter-spacing:2px;color:#849180;margin-top:-2px}.eyebrow{font-size:9px;letter-spacing:2px;color:#7d8b75}.eyebrow>span{display:inline-block;width:5px;height:5px;border-radius:50%;background:#839b69;vertical-align:2px;margin-right:6px}
|
||||
.entry-main{display:grid;grid-template-columns:minmax(0,1fr) 370px;grid-column-gap:76px;align-items:center;min-height:690px;padding:42px 0 24px}.entry-story{position:relative;min-width:0}h1{font:700 50px/1.4 "Songti SC","STSong","Noto Serif CJK SC",serif;letter-spacing:2px;margin:14px 0 15px}h1 em{font-style:normal;color:#5d7956}.lead{font-size:13px;line-height:2;color:#87917c;letter-spacing:1px;margin:0}.entry-map{position:relative;height:290px;margin-top:-8px}.entry-map canvas{display:block;width:100%;height:100%}.entry-map>span{display:block;position:absolute;bottom:0;left:0;right:0;text-align:center;font-size:10px;color:#8d9b7d;letter-spacing:1px}.entry-instruction{display:flex;align-items:center;justify-content:center;margin-top:20px;color:#9baa8d}.entry-instruction>span{font-size:25px;font-weight:300}.entry-instruction p{margin:0 25px;text-align:center;font-size:9px;letter-spacing:1px}.entry-instruction strong{display:block;font-weight:400;color:#718564;font-size:11px;margin-top:2px}
|
||||
.setup{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:29px;box-shadow:0 8px 30px rgba(40,61,52,.04)}.section-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.section-title>span:last-child{font:10px monospace;color:#a1aa96}.setup h2{font:25px/1.5 serif;letter-spacing:1px;margin:0 0 5px}.setup-intro{font-size:11px;color:#9aa28e;margin:0 0 23px}.mode-tabs{display:flex;padding:4px;background:#eff1e7;border-radius:9px;margin-bottom:23px}.mode-tabs button{flex:1;background:none;border-radius:7px;padding:12px 2px;font-size:13px;color:#8c9583;min-height:64px}.mode-tabs small{display:block;font-size:9px;opacity:.8;margin-top:2px}.mode-tabs button.selected{background:#fffef9;color:#3e6046;box-shadow:0 2px 5px rgba(50,69,45,.05)}.field-label{font-size:11px;color:#78876a;display:block;margin-bottom:8px}select{width:100%;background:#fffef9;border:1px solid #dbe1cf;border-radius:7px;padding:11px 10px;font-size:12px}#city-select-panel{margin-bottom:21px}.field-note{font-size:9px;line-height:1.9;color:#9aa28f;margin:11px 0 0;min-height:17px}.speed-heading{display:flex;justify-content:space-between;font-size:11px;margin-bottom:12px}.speed-heading>span{font-size:10px;color:#a18964}.speed-options{display:flex}.speed-options button{width:25%;margin-right:5px;border:1px solid transparent;border-radius:7px;background:#f4f5ec;color:#8f9884;font-size:11px;display:flex;align-items:center;flex-direction:column;padding:9px 0}.speed-options button:last-child{margin-right:0}.speed-options i{height:21px;font:9px sans-serif;letter-spacing:-1px;display:flex;align-items:center;margin-bottom:3px}.speed-options button.selected{background:#e7eddc;border-color:#cbd7bb;color:#537343}.journey-summary{display:flex;justify-content:space-between;border-top:1px dashed #dfe4d4;padding-top:18px;margin-top:23px}.journey-summary>div:last-child{text-align:right}.journey-summary span{display:block;font-size:9px;letter-spacing:1px;color:#9ca58f}.journey-summary strong{font-size:15px;font-weight:500;color:#617b50;display:block;margin-top:3px}.primary{background:var(--green);color:#fffcdf;border:1px solid var(--green);border-radius:9px;padding:13px 19px;font-size:13px;letter-spacing:1px}.start-button{display:flex;width:100%;align-items:center;justify-content:space-between;margin-top:25px;padding:14px 18px}.start-note{font-size:9px;letter-spacing:1px;text-align:center;color:#a0a88f;margin:12px 0 0}footer{display:flex;align-items:center;justify-content:space-between;border-top:1px solid var(--line);padding:18px 0;font-size:9px;color:#a0a88f}footer button{font-size:9px!important}
|
||||
body.is-playing{overflow:hidden}.is-playing .app{max-width:760px;padding:0 28px}.game-screen{height:100vh;height:var(--game-height,100vh);min-height:320px;display:flex;flex-direction:column;padding:12px 0 16px}.game-topbar{display:flex;align-items:center;justify-content:space-between;flex:0 0 43px}.game-topbar>div{text-align:center;min-width:0}.game-topbar strong{display:block;font-size:13px;letter-spacing:1px;font-weight:500}.game-topbar>div>span{display:block;font-size:9px;color:#95a086;margin-top:1px}.nav-button{width:35px;height:35px;min-height:35px;flex:0 0 35px;border:1px solid #dbe0d0;border-radius:50%;background:rgba(255,254,249,.65);font-size:20px;line-height:1;padding:0;color:#728566}.game-hud{display:flex;align-items:center;flex:0 0 73px;padding:0 26px}.game-hud>div{margin-right:32px}.stat-label{display:block;font-size:9px;letter-spacing:1px;color:#929d85}.game-hud strong{font-size:23px;line-height:1.4;font-weight:500;font-variant-numeric:tabular-nums}.game-hud .score strong{font-size:30px;font-weight:600;color:var(--green)}.game-hud strong small{font-size:11px;color:#a0ab94}.game-hud .next-inline{display:flex;margin-right:0;margin-left:auto;align-items:center;max-width:46%;min-width:0}.next-inline canvas{display:block;width:64px;height:46px;flex:0 0 64px;margin-right:10px}.next-inline>div{min-width:0}.next-inline strong{font-size:11px;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}
|
||||
.tank-stage{display:flex;align-items:center;justify-content:center;padding:3px 24px 9px;flex:1;min-height:0}.board-wrap{position:relative;width:100%;max-width:440px;height:100%;max-height:760px;border-left:8px solid #7895a0;border-right:8px solid #7895a0;border-bottom:10px solid #7895a0;border-radius:5px;overflow:hidden;box-shadow:0 5px 0 #e0e3da;will-change:transform;background:#f1f2e9}.board-wrap>canvas{display:block;width:100%;height:100%;touch-action:manipulation}.board-tag{position:absolute;left:12px;top:12px;display:flex;align-items:center;font-size:9px;letter-spacing:1px;color:#7e8c72;pointer-events:none}.live-dot{height:5px;width:5px;border-radius:50%;background:#8ca474;margin-right:6px}.danger-label{position:absolute;right:6px;top:68px;font-size:8px;color:#bd686c;background:#f1f2e9;padding-left:6px;pointer-events:none}.board-status{position:absolute;top:105px;left:8px;right:8px;text-align:center;font-size:9px;color:var(--orange);pointer-events:none;letter-spacing:1px}.game-progress{display:flex;justify-content:space-between;padding:2px 25px 8px;font-size:9px;color:#9ba68c;flex:0 0 27px}.controls{display:flex;flex:0 0 67px;padding:0 24px}.controls button{position:relative;display:flex;align-items:center;justify-content:center;flex:1;min-height:60px;background:#e8eedf;border:1px solid #cad9ba;border-radius:11px;color:#466b3d;user-select:none;-webkit-user-select:none}.controls button:first-child{margin-right:13px}.controls button.pressed{background:#365c47;border-color:#365c47;color:#fffce2}.controls button>span{font-size:30px;font-weight:300;line-height:1}.controls button:first-child>span{margin-right:16px}.controls button:last-child>span{margin-left:16px}.controls strong{font-size:16px;letter-spacing:2px;font-weight:500;margin-top:-9px}.controls small{position:absolute;bottom:10px;left:0;right:0;text-align:center;font-size:8px;letter-spacing:1px;opacity:.65}
|
||||
dialog{border:1px solid #dce0cf;background:var(--card);border-radius:18px;color:var(--ink);padding:26px;width:420px;max-width:calc(100% - 32px);max-height:85vh;overflow:auto;box-shadow:0 16px 80px rgba(29,56,47,.19)}dialog::backdrop{background:rgba(41,61,52,.44)}dialog.modal-fallback{display:block;position:fixed;z-index:100;top:50%;left:50%;margin:0;transform:translate(-50%,-50%);box-shadow:0 0 0 100vmax rgba(41,61,52,.44)}.modal-top{display:flex;align-items:center;justify-content:space-between}.modal-top .eyebrow{font-size:8px}dialog h2{font:26px/1.5 serif;letter-spacing:1px;margin:18px 0}dialog p,dialog li{font-size:12px;line-height:1.9;color:#7c8971}dialog ol{padding-left:20px}dialog li{margin-bottom:8px}dialog b{color:#42643d;font-weight:500}.rules-score{border-radius:9px;background:#eff2e5;padding:13px 15px;font-size:11px;line-height:1.9;color:#718267}#modal-actions{display:flex;flex-wrap:wrap;margin-top:20px}#modal-actions button{flex:1;margin-right:8px;min-width:90px;padding:10px 8px;font-size:11px}#modal-actions button:last-child{margin-right:0}.secondary{border:1px solid #d2dac4;border-radius:8px;background:#f0f3e7;color:#5e7b4e;font-size:12px}.result-number{font:48px/1.2 sans-serif;color:#3e6146;margin:12px 0}.result-label{font-size:10px;letter-spacing:1px;color:#9aa48e}.result-details{display:flex;justify-content:space-between;border-top:1px solid var(--line);padding-top:15px;font-size:10px;color:#8d9980}.toast{position:fixed;z-index:200;bottom:30px;left:50%;transform:translateX(-50%);background:rgba(43,69,56,.94);color:#f6f5e7;border-radius:10px;padding:11px 18px;font-size:12px;max-width:90%;text-align:center;pointer-events:none}
|
||||
@media(max-width:1000px){.app{padding:0 28px}.entry-main{grid-template-columns:minmax(0,1fr) 340px;grid-column-gap:35px}.setup{padding:24px}h1{font-size:43px}.entry-map{height:260px}}
|
||||
@media(max-width:720px){.app{padding:0 22px}.header{height:76px}.brand{font-size:19px;letter-spacing:2px}.brand-mark{width:36px;height:36px;margin-right:10px;border-radius:10px}.brand small{font-size:6px;letter-spacing:1.3px}.header .text-button{font-size:10px}.entry-main{display:flex;flex-direction:column;padding:27px 0 20px;min-height:0}.entry-story{width:100%;text-align:center}.eyebrow{font-size:8px}h1{font-size:31px;line-height:1.4;margin:11px 0 9px;letter-spacing:1px}h1 br{display:none}.lead{font-size:10px;line-height:1.8}.lead br{display:none}.entry-map{height:180px;margin-top:5px;max-width:340px;margin-left:auto;margin-right:auto}.entry-map>span{font-size:8px;bottom:0}.entry-instruction{display:none}.setup{width:100%;padding:23px 21px;border-radius:14px;margin-top:19px}.setup h2{font-size:22px}.setup-intro{margin-bottom:18px;font-size:10px}.section-title{margin-bottom:8px}.mode-tabs{margin-bottom:18px}.mode-tabs button{min-height:53px;padding:9px 2px;font-size:12px}.mode-tabs small{display:inline;margin-left:7px;font-size:9px}.speed-heading{font-size:10px;margin-bottom:10px}.speed-options button{font-size:10px;padding:8px 0}.speed-options i{height:16px;margin-bottom:2px}.field-note{font-size:8px;margin-top:9px}.journey-summary{padding-top:14px;margin-top:17px}.journey-summary strong{font-size:13px}.start-button{margin-top:18px;padding:12px 15px;font-size:12px}.start-note{font-size:8px}.field-label{font-size:10px}footer{font-size:8px;padding:12px 0}footer button{font-size:8px!important}.is-playing .app{padding:0 12px}.game-screen{padding:8px 0 12px}.game-topbar{flex-basis:42px;padding:0 4px}.game-topbar strong{font-size:12px}.game-topbar>div>span{font-size:8px}.nav-button{width:32px;height:32px;min-height:32px;flex-basis:32px;font-size:18px}.game-hud{flex-basis:65px;padding:0 22px}.game-hud>div{margin-right:22px}.stat-label{font-size:8px}.game-hud strong{font-size:21px}.game-hud .score strong{font-size:27px}.next-inline canvas{width:46px;height:38px;flex-basis:46px;margin-right:6px}.next-inline strong{font-size:10px;max-width:84px}.tank-stage{padding:3px 22px 8px}.board-wrap{border-left-width:7px;border-right-width:7px;border-bottom-width:9px}.board-tag{font-size:8px;left:9px}.danger-label{font-size:7px;right:4px;top:69px}.board-status{font-size:8px}.game-progress{font-size:8px;padding:2px 22px 7px;flex-basis:24px}.controls{flex-basis:65px;padding:0 22px}.controls button:first-child{margin-right:12px}.controls button>span{font-size:27px}.controls strong{font-size:15px}.controls small{font-size:7px}dialog{padding:22px}dialog h2{font-size:23px}}
|
||||
@media(max-width:360px){.app{padding:0 16px}.brand{font-size:18px}.game-hud{padding:0 19px}.game-hud>div{margin-right:14px}.game-hud .next-inline{max-width:43%}.next-inline canvas{width:38px;flex-basis:38px;margin-right:4px}.next-inline strong{max-width:65px;font-size:9px}.game-progress>span:last-child{font-size:7px}}
|
||||
@media(max-height:680px){.game-screen{padding-top:4px;padding-bottom:8px}.game-topbar{flex-basis:36px}.game-hud{flex-basis:55px}.controls{flex-basis:55px}.controls button{min-height:52px}.controls small{bottom:6px}.game-progress{flex-basis:22px}.game-hud .score strong{font-size:25px}}
|
||||
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
|
||||
/* Wall contact feedback follows the physics contact lifetime. */
|
||||
.board-wrap{transition:border-color .12s,box-shadow .12s}.board-wrap.impact{border-color:#93a9ad;box-shadow:0 5px 0 #d9ded3,0 0 0 2px rgba(205,171,119,.16)}
|
||||
/* All primary screens share the visible viewport, including the journey entrance. */
|
||||
body{overflow:hidden}.entry-screen{height:100vh;height:var(--game-height,100vh);display:flex;flex-direction:column;min-height:0}.header{flex:0 0 86px;height:auto}.entry-main{flex:1;min-height:0;padding:24px 0 18px}.entry-story{max-height:100%}.entry-map{height:240px}footer{flex:0 0 44px;padding:4px 0}.setup{padding:24px}.setup h2{font-size:23px}.setup-intro{margin-bottom:18px}.mode-tabs{margin-bottom:18px}.speed-options button{padding:7px 0 9px;min-height:67px}.speed-options button>span{font:9px monospace;opacity:.5;margin-bottom:4px}.speed-options strong{font-size:11px;font-weight:500;white-space:nowrap}.speed-options small{font-size:8px;opacity:.75;margin-top:3px}.journey-summary{margin-top:18px;padding-top:14px}.start-button{margin-top:20px}.start-note{margin-top:9px}
|
||||
.province-picker{width:100%;display:flex;align-items:center;background:#eef2e6;border:1px solid #d3dfc5;border-radius:9px;padding:10px 12px;min-height:62px;text-align:left}.destination-mark{height:32px;width:32px;display:flex;align-items:center;justify-content:center;border:1px solid #d1dcc1;border-radius:9px;margin-right:10px;font-size:21px;color:#6f8d56}.destination-copy{display:flex;flex-direction:column;min-width:0}.destination-copy small{font-size:8px;color:#94a184}.destination-copy strong{font-size:13px;font-weight:500;line-height:1.6;color:#4e703d}.destination-count{font-size:9px;color:#8c9d79;margin-left:auto;padding-left:8px}.destination-arrow{font-size:15px;color:#849a6d;margin-left:10px}#city-select-panel{margin-bottom:17px}#city-note{font-size:8px;margin-top:7px;letter-spacing:0}
|
||||
.province-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));grid-gap:7px;margin:12px 0}.province-grid button{border:1px solid #e0e6d6;background:#f2f5eb;border-radius:7px;min-height:34px;padding:6px 0;font-size:11px;color:#7d8e6b}.province-grid button.selected{background:#365c47;border-color:#365c47;color:#fffce2}.picker-note{font-size:9px;line-height:1.8;color:#9ba58e;margin:12px 0 0}.province-picker-modal h2{font-size:23px;margin:12px 0}.province-picker-modal{padding:22px}.province-picker-modal .modal-top{height:31px}
|
||||
/* Arrow, title and hint occupy one centered flex row; nothing is absolutely positioned. */
|
||||
.controls button>.control-arrow{font-size:28px;line-height:1;flex:0 0 auto;margin:0!important}.controls button>.control-copy{display:flex;flex-direction:column;align-items:center;margin:0 16px;font-size:14px;line-height:1.5}.controls strong{font-size:17px;letter-spacing:2px;margin:0;line-height:1.5}.controls small{position:static;display:block;bottom:auto;left:auto;right:auto;font-size:9px;letter-spacing:.5px;line-height:1.4;opacity:.7;margin-top:2px}.game-progress{color:#8e9d7d}.game-progress>span:last-child{font-size:9px}
|
||||
@media(max-width:720px){.header{flex-basis:59px}.entry-main{padding:13px 0 9px;justify-content:center}.entry-story{flex:1;min-height:116px;max-height:255px;display:flex;flex-direction:column;align-items:center;justify-content:center}.entry-map{flex:1;width:100%;height:130px;min-height:65px;max-height:160px;margin-top:0}.entry-map>span{font-size:7px}.entry-story h1{font-size:28px;margin:5px 0}.lead{font-size:9px;line-height:1.5}.entry-story>.eyebrow{font-size:7px}.setup{flex:0 0 auto;margin-top:12px;padding:18px;width:100%}.setup .section-title,.setup-intro{display:none}.setup h2{font-size:21px;margin-bottom:12px;line-height:1.3}.mode-tabs{margin-bottom:12px}.mode-tabs button{min-height:46px;padding:7px 0}.speed-heading{margin-bottom:8px}.speed-options button{min-height:58px;padding:6px 0}.speed-options strong{font-size:10px}.speed-options small{font-size:7px}.field-note{font-size:8px;line-height:1.6;margin-top:7px;min-height:13px}.journey-summary{padding-top:10px;margin-top:13px}.journey-summary span{font-size:8px}.journey-summary strong{font-size:12px;margin-top:2px}.start-button{min-height:43px;padding:10px 13px;margin-top:14px}.start-note{font-size:7px;margin-top:7px;line-height:1.4}footer{flex-basis:29px;font-size:7px}footer .text-button{min-height:24px}.province-picker{min-height:54px;padding:8px 10px}.destination-mark{height:28px;width:28px;margin-right:8px;font-size:19px}.destination-copy strong{font-size:12px}.destination-count{font-size:8px}.destination-arrow{margin-left:7px}#city-select-panel{margin-bottom:12px}#city-note{font-size:7px;margin-top:6px;line-height:1.5}.controls strong{font-size:16px}.controls small{font-size:8px}.controls button>.control-arrow{font-size:27px}.controls button>.control-copy{margin:0 13px}.game-progress>span:last-child{font-size:8px}}
|
||||
body.compact-entry .entry-main{padding:8px 0}body.compact-entry .header{flex-basis:50px}body.compact-entry .entry-story{flex:0 1 80px;min-height:34px;max-height:110px}body.compact-entry .entry-story>.eyebrow,body.compact-entry .lead{display:none}body.compact-entry h1{font-size:25px;line-height:1.25;margin:1px 0}body.compact-entry .entry-map{display:none}body.compact-entry .setup{padding:15px;margin-top:8px}body.compact-entry .setup h2{font-size:19px;margin-bottom:9px}body.compact-entry .setup .section-title,body.compact-entry .setup-intro{display:none}body.compact-entry .mode-tabs{margin-bottom:9px}body.compact-entry .mode-tabs button{min-height:43px;padding:6px 0}body.compact-entry .speed-heading{font-size:10px;margin-bottom:6px}body.compact-entry .speed-options button{min-height:47px;padding:5px 0}body.compact-entry .speed-options button>span{display:none}body.compact-entry #speed-note,body.compact-entry .start-note{display:none}body.compact-entry .journey-summary{margin-top:10px;padding-top:8px}body.compact-entry .journey-summary>div{display:flex;align-items:center}body.compact-entry .journey-summary strong{font-size:11px;margin:0 0 0 8px}body.compact-entry .start-button{margin-top:11px;min-height:42px;padding:9px 12px}body.compact-entry .province-picker{min-height:51px}body.compact-entry #city-select-panel{margin-bottom:10px}body.compact-entry #city-note{font-size:7px;margin-top:4px}body.compact-entry footer{flex-basis:25px}
|
||||
body.tiny-entry .entry-story,body.tiny-entry .journey-summary{display:none}body.tiny-entry .entry-main{justify-content:center}body.tiny-entry .setup{margin-top:0}body.tiny-entry .setup h2{font-size:18px;margin-bottom:8px}
|
||||
@media(max-height:520px) and (min-width:600px){.entry-main{display:grid!important;grid-template-columns:minmax(0,1fr) 310px;grid-column-gap:24px}.entry-story{display:block!important;min-height:0!important;max-height:100%!important}.entry-map{display:block!important;height:110px;min-height:0}.entry-map>span{display:none}.entry-story h1{font-size:30px;line-height:1.25}.setup{padding:12px 16px!important;margin:0!important}.setup h2,.journey-summary,.setup-intro,.section-title,#city-note{display:none!important}.mode-tabs button{min-height:38px!important}.province-picker{min-height:44px!important;padding:6px 8px}.destination-mark{height:25px;width:25px}.speed-options button{min-height:40px!important}.start-button{min-height:37px!important;margin-top:8px!important}.header{flex-basis:43px!important}.brand{font-size:18px}.brand-mark{width:31px;height:31px}.entry-screen footer{flex-basis:22px!important}.entry-instruction{display:none}}
|
||||
|
||||
.using-pointer button:focus{outline:none}
|
||||
/* Independent rebound choice; the lowest setting preserves the original feel. */
|
||||
.bounce-heading{display:flex;justify-content:space-between;margin:15px 0 7px;font-size:11px}.bounce-heading>span{font-size:8px;color:#95a086}.bounce-options{display:flex}.bounce-options button{flex:1;min-width:0;border:1px solid #e0e6d5;background:#f5f5ee;border-radius:7px;min-height:49px;padding:6px 2px;margin-right:6px;color:#8b9780}.bounce-options button:last-child{margin-right:0}.bounce-options strong{display:block;font-size:11px;font-weight:500}.bounce-options small{display:block;font-size:8px;opacity:.75}.bounce-options button.selected{background:#e7eddc;border-color:#cbd7bb;color:#537343}
|
||||
.controls button{min-width:0}.controls button+button{margin-left:9px}.controls button:first-child{margin-right:0}.controls button>.control-copy{margin:0 9px}.controls strong{font-size:16px;letter-spacing:1px}.controls small{font-size:8px;letter-spacing:0}.controls button>.control-arrow{font-size:23px}.controls #up{background:#f1ebdb;border-color:#dcd0b3;color:#957349;flex:.85}.controls #up:active{background:#e4d6b7}.controls #up .control-copy{margin:0 4px}
|
||||
.result-screen{height:100vh;height:var(--game-height,100vh);display:flex;flex-direction:column;padding:12px 0;max-width:650px;margin:auto;min-height:0}.result-topbar{display:flex;align-items:center;justify-content:space-between;flex:0 0 35px}.result-screen h2{font:25px/1.4 serif;margin:9px 0 3px;text-align:center;color:#365c47}.result-intro{font-size:10px;text-align:center;color:#95a086;margin:0 0 12px}.card-preview-wrap{flex:1;min-height:0;display:flex;justify-content:center;align-items:center;background:#e8ebdf;border:1px solid #dce2d1;border-radius:12px;padding:10px}.card-preview-wrap canvas{display:block;max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 3px 12px rgba(40,61,52,.08)}.result-actions{display:flex;flex:0 0 46px;margin-top:12px}.result-actions button{flex:1;min-width:0;font-size:11px;padding:9px 4px;letter-spacing:0}.result-actions button+button{margin-left:8px}.result-actions button:first-child{flex:1.3}.result-footnote{flex:0 0 18px;font-size:8px;color:#9aa48e;text-align:center;margin:7px 0 0}
|
||||
@media(max-width:720px){.bounce-heading{margin-top:10px;font-size:10px}.bounce-options button{min-height:42px;padding:4px 2px}.bounce-options strong{font-size:10px}.bounce-options small{font-size:7px}.controls button>.control-copy{margin:0 6px}.controls strong{font-size:14px}.controls small{font-size:7px}.controls button>.control-arrow{font-size:20px}.controls button+button{margin-left:7px}.result-screen h2{font-size:21px}.result-intro{font-size:9px}.result-screen{padding-top:5px;padding-bottom:8px}.result-actions{margin-top:9px;flex-basis:42px}.result-actions button{font-size:10px}}
|
||||
body.compact-entry .bounce-heading{margin-top:8px;margin-bottom:5px}body.compact-entry .bounce-options button{min-height:38px;padding:3px 2px}body.compact-entry .entry-story{flex-basis:45px;min-height:28px}body.compact-entry .setup{padding:12px 15px}body.compact-entry .setup h2{margin-bottom:7px}
|
||||
@media(max-height:520px){.bounce-heading{margin-top:6px!important;margin-bottom:4px!important}.bounce-options button{min-height:35px!important}.bounce-options small{display:none}.result-topbar{flex-basis:25px}.result-screen h2{font-size:17px;margin:0 0 5px}.result-intro,.result-footnote{display:none}.result-actions{flex-basis:38px;margin-top:7px}.card-preview-wrap{padding:5px}}
|
||||
/* A sliding selection track also responds to horizontal swipes. */
|
||||
.mode-tabs{position:relative;touch-action:pan-y}.mode-tabs::before{content:"";position:absolute;top:4px;bottom:4px;left:4px;width:calc((100% - 8px) / 2);border-radius:7px;background:#fffef9;box-shadow:0 2px 5px rgba(50,69,45,.07);transform:translateX(0);transition:transform .34s cubic-bezier(.22,1,.36,1);pointer-events:none}.city-mode .mode-tabs::before{transform:translateX(100%)}.mode-tabs button{position:relative;z-index:1;transition:color .2s}.mode-tabs button.selected{background:transparent;box-shadow:none}
|
||||
button{transition:background-color .16s,border-color .16s,color .16s,box-shadow .16s,transform .16s}.controls button.pressed{transform:translateY(2px) scale(.98)}.speed-options button.selected{box-shadow:0 2px 6px rgba(74,108,54,.09)}.destination-arrow{display:inline-block;transition:transform .25s}.province-picker.expanded .destination-arrow{transform:rotate(180deg)}
|
||||
.tap-pop{animation:tap-pop .26s ease-out}.bounce-pop{animation:bounce-pop .50s cubic-bezier(.28,.8,.3,1);transform-origin:50% 70%}.city-mode #city-select-panel{animation:destination-in .22s ease-out}.game-screen,.result-screen{animation:screen-in .26s ease-out}dialog[open] #modal-content,dialog[open] #modal-actions{animation:screen-in .22s ease-out}
|
||||
@keyframes tap-pop{0%{transform:scale(1)}35%{transform:scale(.955)}70%{transform:scale(1.012)}100%{transform:scale(1)}}
|
||||
@keyframes bounce-pop{0%{transform:scale(1)}18%{transform:translateY(2px) scale(1.045,.88)}44%{transform:translateY(-4px) scale(.96,1.09)}68%{transform:translateY(1px) scale(1.025,.96)}85%{transform:translateY(-1px) scale(.99,1.02)}100%{transform:translateY(0) scale(1)}}
|
||||
@keyframes destination-in{from{opacity:0;transform:translateY(-5px)}to{opacity:1;transform:translateY(0)}}
|
||||
@keyframes screen-in{from{opacity:.4;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}
|
||||
.board-wrap.impact{border-color:#8ca3a8;box-shadow:0 5px 0 #dce1d5,0 0 0 1px rgba(185,166,124,.10)}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}.controls button.pressed{transform:none}}
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+6
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
|
||||
import {chromium} from 'playwright';import assert from 'node:assert/strict';import fs from 'node:fs';
|
||||
const browser=await chromium.launch({executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});const results=[],errors=[],network=[];
|
||||
const watch=p=>{p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(!r.url().startsWith('http://localhost:4173'))network.push(r.url());});};
|
||||
const state=p=>p.evaluate(()=>window.shanheDebug.state());
|
||||
const context=await browser.newContext({viewport:{width:1440,height:1000},deviceScaleFactor:1});const page=await context.newPage();watch(page);
|
||||
await page.goto('http://localhost:4173');await page.waitForFunction(()=>window.shanheDebug);assert.equal((await state(page)).status,'entry');assert.equal(await page.locator('#entry-screen').isVisible(),true);assert.equal(await page.locator('#game-screen').isVisible(),false);await page.waitForTimeout(300);assert.equal((await state(page)).dropped,0);await page.screenshot({path:'artifacts/desktop.png',fullPage:true});results.push('入口先选版本/地区/速度,未开局不生成碎片');
|
||||
await page.locator('[data-mode="city"]').click();await page.locator('#province-picker').click();await page.locator('[data-province="440000"]').click();await page.locator('[data-speed="3"]').click();assert.equal((await state(page)).level,'440000');assert.equal((await state(page)).speed,3);await page.locator('#start').click();assert.equal((await state(page)).status,'playing');assert.equal(await page.locator('#entry-screen').isVisible(),false);assert.equal(await page.locator('.controls button').count(),3);assert.equal(await page.locator('#rotate,#drop,#shake,#hint,#shuffle').count(),0);assert.equal(await page.locator('#total').textContent(),'21');results.push('选广东21市和山河起飞后直接开局,游戏包含左晃、上晃、右晃三项操作');
|
||||
const bounds=await page.locator('#tank').boundingBox();assert.ok(bounds.width<=440);const frameStyle=await page.locator('#tank').evaluate(e=>({left:parseFloat(getComputedStyle(e).borderLeftWidth),bottom:parseFloat(getComputedStyle(e).borderBottomWidth)}));assert.ok(frameStyle.left>=7&&frameStyle.bottom>=9);
|
||||
await page.keyboard.down('ArrowLeft');await page.waitForFunction(()=>{const s=window.shanheDebug.state();return s.shakeOffset<0&&s.shakeCount>=2;});const a=await state(page);assert.ok(a.shakeOffset<0&&a.shakeCount>=2);const x=await page.locator('#tank').evaluate(e=>getComputedStyle(e).transform);assert.notEqual(x,'none');await page.keyboard.up('ArrowLeft');await page.waitForTimeout(350);const released=(await state(page)).shakeCount;await page.waitForTimeout(350);assert.equal((await state(page)).shakeCount,released);await page.keyboard.press('ArrowUp');assert.equal((await state(page)).shakeCount,released+1);await page.keyboard.press('ArrowDown');await page.keyboard.press('s');assert.equal((await state(page)).shakeCount,released+1);assert.ok((await state(page)).regions.every(r=>Math.abs(r.angle)<=.161));results.push('按住左右键驱动整个框,松开停止输入,上键轻颠,旧旋转/加速/S快捷键无效');
|
||||
await page.waitForTimeout(2200);assert.ok((await state(page)).dropped>=2);await page.screenshot({path:'artifacts/city-desktop.png',fullPage:true});
|
||||
await page.locator('#pause').click();assert.equal((await state(page)).status,'paused');const paused=await state(page);await page.mouse.move(bounds.x+bounds.width/2,bounds.y+160);await page.mouse.down();await page.mouse.move(bounds.x+bounds.width/2+60,bounds.y+220);await page.mouse.up();await page.waitForTimeout(200);assert.deepEqual((await state(page)).regions,paused.regions);await page.getByRole('button',{name:'继续游戏',exact:true}).click();assert.equal((await state(page)).status,'playing');results.push('暂停冻结物理,棋盘不支持碎片拖动');
|
||||
await page.locator('#back').click();await page.getByRole('button',{name:'继续游戏',exact:true}).click();assert.equal((await state(page)).status,'playing');await page.locator('#back').click();await page.getByRole('button',{name:'结束旅程',exact:true}).click();assert.equal((await state(page)).screen,'result');await page.locator('#result-back').click();assert.equal((await state(page)).status,'entry');assert.equal((await state(page)).dropped,0);await page.locator('[data-mode="province"]').click();await page.locator('#start').click();assert.equal((await state(page)).level,'100000');assert.equal(await page.locator('#total').textContent(),'34');await page.locator('#pause').click();await page.getByRole('button',{name:'重新开局',exact:true}).click();assert.equal((await state(page)).dropped,1);assert.equal((await state(page)).shakeCount,0);results.push('返回确认、重新选择、重新开局均清理旧局与按键状态');await context.close();
|
||||
const mobile=await browser.newContext({viewport:{width:390,height:844},deviceScaleFactor:2,isMobile:true,hasTouch:true});const mp=await mobile.newPage();watch(mp);await mp.goto('http://localhost:4173');await mp.waitForFunction(()=>window.shanheDebug);assert.ok(await mp.evaluate(()=>document.documentElement.scrollHeight<=innerHeight+1));await mp.screenshot({path:'artifacts/mobile.png',fullPage:true});await mp.locator('#start').tap();assert.equal((await state(mp)).status,'playing');await mp.locator('#left').tap();await mp.waitForTimeout(90);assert.ok((await state(mp)).shakeCount>0);await mp.screenshot({path:'artifacts/mobile-playing.png',fullPage:true});
|
||||
for(const viewport of [{width:390,height:844},{width:320,height:568},{width:740,height:390}]){await mp.setViewportSize(viewport);await mp.waitForFunction(()=>{const r=document.querySelector('.controls').getBoundingClientRect();return r.bottom<=innerHeight+1;});const b=await mp.locator('.controls').boundingBox();assert.ok(b.y+b.height<=viewport.height+1,JSON.stringify(viewport)+' controls on screen');assert.ok(await mp.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));const saved=await state(mp);assert.equal(saved.status,'playing');assert.ok(saved.scale>0);}
|
||||
results.push('390/320窄屏及横屏:框体与三个触摸按钮同屏,无横向溢出,缩放保留局面');await mobile.close();
|
||||
const responsive=await browser.newContext({viewport:{width:320,height:568},isMobile:true,hasTouch:true});const rp=await responsive.newPage();watch(rp);await rp.goto('http://localhost:4173');await rp.waitForFunction(()=>window.shanheDebug);
|
||||
for(const viewport of [{width:320,height:568},{width:375,height:667},{width:390,height:844},{width:740,height:390}]){await rp.setViewportSize(viewport);for(const chosen of ['province','city']){await rp.locator('[data-mode="'+chosen+'"]').click();await rp.waitForFunction(()=>document.getElementById('start').getBoundingClientRect().bottom<=innerHeight);const fit=await rp.evaluate(()=>({scroll:document.documentElement.scrollHeight,viewport:innerHeight,start:document.getElementById('start').getBoundingClientRect().bottom}));assert.ok(fit.scroll<=fit.viewport+1,JSON.stringify({viewport,chosen,fit}));}await rp.screenshot({path:'artifacts/entry-'+viewport.width+'x'+viewport.height+'.png'});}
|
||||
await rp.setViewportSize({width:320,height:568});await rp.addStyleTag({content:':root{--safe-area-inset-top:44px;--safe-area-inset-bottom:34px}'});await rp.evaluate(()=>dispatchEvent(new Event('resize')));await rp.waitForFunction(()=>document.documentElement.scrollHeight<=innerHeight+1);await rp.locator('#province-picker').click();assert.equal(await rp.locator('.province-grid button').count(),27);assert.equal(await rp.locator('[data-province="710000"]').count(),0);const picker=await rp.locator('#modal').evaluate(e=>({scroll:e.scrollHeight,client:e.clientHeight}));assert.ok(picker.scroll<=picker.client+1);await rp.screenshot({path:'artifacts/province-picker-mobile.png'});await rp.locator('[data-province="330000"]').click();assert.equal((await state(rp)).level,'330000');results.push('入口省级/地级在320/375/390及横屏一屏显示;含44/34安全区;省区网格27项无需滚动');await responsive.close();
|
||||
const sdk=await browser.newContext();const sp=await sdk.newPage();watch(sp);await sp.addInitScript(()=>{Storage.prototype.getItem=()=>{throw Error('Storage denied');};window.xhs={miniTool:{getLaunchOptions:async()=>({miniToolEnv:{buildVersion:9462004}}),getStorage:async()=>({data:JSON.stringify({'100000:0':999})}),setStorage:async()=>({})}};});await sp.goto('http://localhost:4173');await sp.locator('[data-bounce="0"]').click();await sp.waitForFunction(()=>document.getElementById('entry-best').textContent==='999');results.push('原生Storage在入口展示所选关卡最佳纪录');await sdk.close();
|
||||
const migration=await browser.newContext();const mg=await migration.newPage();watch(mg);await mg.addInitScript(()=>{localStorage.setItem('shanhe-records-v1',JSON.stringify({'100000:0':1234}));window.savedNative=null;window.xhs={launchOptions:{miniToolEnv:{buildVersion:9460001}},miniTool:{getStorage:async()=>({data:JSON.stringify({'100000:0':999})}),setStorage:async(o)=>{window.savedNative=JSON.parse(o.data);}}};});await mg.goto('http://localhost:4173');await mg.waitForFunction(()=>window.savedNative&&window.savedNative['100000:0']===1234);results.push('旧纪录升级迁移到原生Storage并保留较高分');await migration.close();
|
||||
const noStorage=await browser.newContext();const np=await noStorage.newPage();watch(np);await np.addInitScript(()=>{Storage.prototype.getItem=()=>{throw Error('denied');};Storage.prototype.setItem=()=>{throw Error('denied');};});await np.goto('http://localhost:4173');await np.waitForFunction(()=>window.shanheDebug);await np.locator('#start').click();assert.equal((await state(np)).status,'playing');results.push('无SDK且存储被禁时,仍可从入口开局');await noStorage.close();
|
||||
assert.deepEqual(errors,[]);assert.deepEqual(network,[]);results.push('运行无页面异常、无外部网络请求');fs.writeFileSync('artifacts/browser-report.json',JSON.stringify({passed:true,results,errors,externalRequests:network},null,2));console.log(results.join('\n'));await browser.close();
|
||||
@@ -0,0 +1,33 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');
|
||||
fs.mkdirSync('artifacts',{recursive:true});
|
||||
const C=require('../src/core.js'),{Game,SPEEDS}=require('../src/game.js'),M=require('matter-js');
|
||||
const box={window:{}};vm.runInNewContext(fs.readFileSync('src/maps.js','utf8'),box);const data=box.window.MAP_DATA;
|
||||
const square=(id,x,y)=>({id:String(id),name:'地区'+id,center:[x+50,y+50],rings:[[[x,y],[x+100,y],[x+100,y+100],[x,y+100]]]});
|
||||
const level={id:'100',name:'两块',width:200,height:100,regions:[square(0,0,0),square(1,100,0)],edges:[[0,1,0]]};
|
||||
function game(l=level,s=0){return new Game(l,420,560,s,()=>{},()=>.5);}
|
||||
test('相邻但贴错边、方向不一致、非邻接地区均不可合并',()=>{const a={ids:[0],tx:50,ty:100,angle:0};assert.equal(C.canSnap(a,{ids:[1],tx:150,ty:100,angle:0},level.edges,22),null);assert.equal(C.canSnap(a,{ids:[1],tx:50,ty:100,angle:Math.PI/2},level.edges,22),null);assert.equal(C.canSnap(a,{ids:[2],tx:50,ty:100,angle:0},level.edges,22),null);assert.ok(C.canSnap(a,{ids:[1],tx:62,ty:100,angle:0},level.edges,22));});
|
||||
test('刚体旋转后按正确方位吸合,并且一局可达通关',()=>{const g=game();g.status='playing';g.queue=[];const pose={tx:300,ty:200,angle:Math.PI/2};g.createGroup([0],pose);g.createGroup([1],{...pose,tx:308});assert.ok(g.tryMerges());assert.equal(g.groups.length,1);assert.equal(g.groups[0].ids.length,2);assert.equal(g.status,'won');assert.equal(g.score,1100);g.destroy();});
|
||||
test('跨海独立片可连接,且按跨海倍率计分',()=>{const l={...level,edges:[[0,1,1]]},g=game(l,1);g.status='playing';g.createGroup([0],{tx:10,ty:120,angle:0});g.createGroup([1],{tx:12,ty:120,angle:0});g.tryMerges();assert.equal(g.score,1620);g.destroy();});
|
||||
test('出片无重复,暂停冻结计时,四档实际间隔与重力递增',()=>{const g=game();g.start();const clock=g.clock;g.status='paused';g.tick(34);assert.equal(g.clock,clock);g.status='playing';g.nextAt=0;g.tick(16);assert.equal(g.dropped,2);assert.equal(new Set(g.groups.flatMap(x=>x.ids)).size,2);for(let i=1;i<4;i++){assert.ok(SPEEDS[i].interval<SPEEDS[i-1].interval);assert.ok(SPEEDS[i].gravity>SPEEDS[i-1].gravity);}g.destroy();});
|
||||
test('左右晃动可反复使用且不扣分',()=>{const g=game();g.start();g.queue=[];g.score=200;for(let i=0;i<20;i++){assert.ok(g.nudge(i%2?-1:1));for(let j=0;j<9;j++)g.tick(16.67);}assert.equal(g.score,200);assert.equal(g.shakeCount,20);g.destroy();});
|
||||
test('堆顶有出生保护,稳定堵塞警戒线才判负',()=>{const g=game();g.start();g.queue=[];const a=g.groups[0];M.Body.setStatic(a.body,true);M.Body.setPosition(a.body,{x:150,y:42});for(let i=0;i<100;i++)g.tick(34);assert.equal(g.status,'playing');for(let i=0;i<130;i++)g.tick(34);assert.equal(g.status,'lost');g.destroy();});
|
||||
test('全国每个真实关卡均连通、每片轮廓可生成有限的刚体',()=>{assert.equal(data.levels[0].regions.length,34);assert.equal(data.levels.length,28);let count=0;for(const l of data.levels){const seen=new Set([0]);let changed=true;while(changed){changed=false;for(const e of l.edges){if(seen.has(e[0])!==seen.has(e[1])){seen.add(e[0]);seen.add(e[1]);changed=true;}}}assert.equal(seen.size,l.regions.length,l.name+' must be completable');const g=game(l);for(let i=0;i<l.regions.length;i++){const p=g.createGroup([i],{tx:0,ty:0,angle:0});assert.ok(Number.isFinite(p.body.mass)&&p.body.mass>0,l.name+' '+i);assert.ok(Number.isFinite(p.body.position.x));M.Composite.remove(g.engine.world,p.body);g.groups=[];count++;}g.destroy();}assert.equal(count,367);});
|
||||
test('完整的全国地图可全部吸合,海岛无死局',()=>{const g=game(data.levels[0]);g.status='playing';g.queue=[];for(let i=0;i<34;i++)g.createGroup([i],{tx:20,ty:100,angle:0});for(let i=0;i<40;i++)g.tryMerges();assert.equal(g.status,'won');assert.equal(g.groups.length,1);assert.equal(g.groups[0].ids.length,34);g.destroy();});
|
||||
test('窗口缩放保留进度与组合',()=>{const g=game();g.start();g.score=120;g.resize(360,440);assert.equal(g.score,120);assert.equal(g.dropped,1);assert.equal(g.groups.length,1);assert.ok(Number.isFinite(g.groups[0].body.position.x));g.destroy();});
|
||||
test('损坏或恶意纪录输入安全降级',()=>{assert.deepEqual(C.safeRecord(null),{});assert.deepEqual(C.safeRecord({'100000:0':123,'x':7,'330100:2':-1}),{'100000:0':123});});
|
||||
test('正式包只包含省级与地级单元,全部27个地级关卡可拼完',()=>{for(const l of data.levels.slice(1)){assert.ok(l.regions.every(r=>Number(r.id)%100===0),l.name+'不得包含县区或县级市');const g=game(l);g.status='playing';g.queue=[];for(let i=0;i<l.regions.length;i++)g.createGroup([i],{tx:25,ty:110,angle:0});for(let i=0;i<l.regions.length+3;i++)g.tryMerges();assert.equal(g.status,'won',l.name+'可通关');g.destroy();}});
|
||||
test('碎片轻微翻动受角度上限约束,松手后自动回正',()=>{const g=game();g.start();g.queue=[];const a=g.groups[0];g.nudge(1);for(let i=0;i<200;i++)g.tick(16.67);assert.ok(Math.abs(a.body.angle)<.025);g.destroy();});
|
||||
test('左右按键驱动容器弹簧,并对所有碎片施加惯性,而非只移动选中块',()=>{const g=game();g.start();g.queue=[];const b=g.createGroup([g.groups[0].ids[0]===0?1:0],{tx:180,ty:160,angle:0});const a=g.groups[0];const ax=a.body.position.x,bx=b.body.position.x;assert.ok(g.nudge(-1));g.tick(16.67);assert.ok(g.shake.offset<0);assert.ok(a.body.position.x!==ax);assert.ok(b.body.position.x!==bx);assert.equal(g.score,0);g.status='paused';const offset=g.shake.offset;assert.equal(g.nudge(1),false);g.tick(16.67);assert.equal(g.shake.offset,offset);g.destroy();});
|
||||
test('开局全国碎片放大超过旧版两倍,拼合大区域时全局缩放且仍能通关',()=>{const l=data.levels[0],g=new Game(l,320,435,0);const old=Math.min((320-52)/l.width,435*.48/l.height);assert.ok(g.scale/old>2.2);const scale=g.scale;g.status='playing';g.queue=[];for(let i=0;i<34;i++)g.createGroup([i],{tx:10,ty:150,angle:0});for(let i=0;i<40;i++)g.tryMerges();assert.equal(g.status,'won');assert.ok(g.scale<scale);const b=g.groups[0].body.bounds;assert.ok(b.max.x-b.min.x<=g.w-19);assert.ok(b.max.y-b.min.y<=g.h-78-23);g.destroy();});
|
||||
|
||||
test('真实落地会回弹并产生碰撞反馈,落地碎片可被晃动轻轻颠起',()=>{const g=game();g.start();g.queue=[];let sawBounce=false;for(let i=0;i<480;i++){g.tick(16.67);if(g.groups[0].body.velocity.y<-.15)sawBounce=true;}assert.ok(sawBounce);assert.ok(g.collisionCount>0);const body=g.groups[0].body,start=body.position.y;g.nudge(1);assert.ok(body.velocity.y<0,'睡眠中的已落地碎片也会轻弹');let highest=start;for(let i=0;i<45;i++){g.tick(16.67);highest=Math.min(highest,body.position.y);}assert.ok(start-highest>4);assert.ok(start-highest<75);g.destroy();});
|
||||
test('反复交替晃动限制速度和倾斜,不会把碎片无限加速或甩出框外',()=>{const g=game();g.start();g.queue=[];for(let i=0;i<600;i++){if(i%9===0)g.nudge(Math.floor(i/9)%2?-1:1);g.tick(16.67);const b=g.groups[0].body;assert.ok(Math.abs(b.velocity.x)<=7.201);assert.ok(b.velocity.y<=9.001);assert.ok(Math.abs(b.angle)<=.1601);const real=M.Bounds.create(b.vertices);assert.ok(real.min.x>=-3&&real.max.x<=g.w+3);assert.ok(real.max.y<=g.h+4);}assert.ok(g.collisionCount>0);assert.ok(g.impacts.length<=20);g.destroy();});
|
||||
|
||||
|
||||
test('上晃作用于整个框和每个组合,冷却防连点,暂停时不可操作',()=>{const g=game();g.start();g.queue=[];g.createGroup([g.groups[0].ids[0]===0?1:0],{tx:180,ty:160,angle:0});assert.equal(g.nudgeUp(),true);assert.ok(g.groups.every(p=>p.body.velocity.y<0));assert.equal(g.nudgeUp(),false);g.tick(16.67);assert.ok(g.shake.y<0);g.status='paused';assert.equal(g.nudgeUp(),false);g.destroy();});
|
||||
test('三档弹性实际递增且反复三向晃动始终受速度/框体限制',()=>{const {BOUNCES}=require('../src/game.js');assert.equal(BOUNCES.length,3);let heights=[];for(let b=0;b<3;b++){const g=new Game(level,420,560,0,()=>{},()=>.5,b);g.start();g.queue=[];for(let i=0;i<480;i++)g.tick(16.67);const start=g.groups[0].body.position.y;g.nudgeUp();let highest=start;for(let i=0;i<60;i++){g.tick(16.67);highest=Math.min(highest,g.groups[0].body.position.y);}heights.push(start-highest);assert.equal(g.groups[0].body.restitution,BOUNCES[b].restitution);for(let i=0;i<600;i++){if(i%30===0)g.nudgeUp();if(i%9===0)g.nudge(i%2?1:-1);g.tick(16.67);const body=g.groups[0].body,real=M.Bounds.create(body.vertices);assert.ok(Math.abs(body.velocity.x)<=BOUNCES[b].maxX+.001);assert.ok(Math.abs(body.angle)<=.1601);assert.ok(real.min.x>=-3&&real.max.x<=g.w+3&&real.max.y<=g.h+4);}g.destroy();}assert.ok(heights[1]>heights[0]*1.5,heights);assert.ok(heights[2]>heights[1]*1.5,heights);});
|
||||
test('地级版相对原来缩小三成,省级版保留原尺寸',()=>{const {baseScale}=require('../src/game.js');for(const l of data.levels.slice(1)){const same={...l,id:'100000'};assert.ok(Math.abs(baseScale(l,320,435)/baseScale(same,320,435)-.7)<.00001);}});
|
||||
test('暂停也可主动结束,成绩曲线从零开始、通关含奖励、结束后冻结且只发一次事件',()=>{let ends=0;const g=new Game(level,420,560,0,t=>{if(t==='end')ends++;},()=>.5);g.start();g.queue=[];g.tick(100);g.status='paused';const before=g.clock;g.tick(100);assert.equal(g.clock,before);assert.ok(g.finish());assert.equal(g.status,'ended');assert.equal(g.endReason,'stopped');assert.equal(ends,1);assert.deepEqual(g.history,[{ms:0,score:0},{ms:100,score:0}]);assert.equal(g.finish(),false);g.tick(100);assert.equal(g.clock,100);g.destroy();const won=game();won.status='playing';won.clock=60000;won.queue=[];won.createGroup([0],{tx:20,ty:100,angle:0});won.createGroup([1],{tx:20,ty:100,angle:0});won.tryMerges();assert.equal(won.endReason,'won');assert.deepEqual(won.history,[{ms:0,score:0},{ms:60000,score:1100}]);won.destroy();});
|
||||
test('不同弹性的纪录分开存储,仍兼容旧版最低弹性纪录',()=>{assert.deepEqual(C.safeRecord({'100000:0':100,'100000:0:1':200,'100000:0:2':300,'100000:0:3':900}),{'100000:0':100,'100000:0:1':200,'100000:0:2':300});});
|
||||
|
||||
test('四档下落速度下,实测上晃分别为轻弹、正常和强弹,强弹可颠起至少200px',()=>{const fs=require('node:fs'),results=[];const l={id:'100000',name:'弹跳测试',width:1000,height:1000,regions:[square(0,0,0)],edges:[]};for(let speed=0;speed<4;speed++){let heights=[];for(let bounce=0;bounce<3;bounce++){const g=new Game(l,320,590,speed,()=>{},()=>.5,bounce);g.start();g.queue=[];const body=g.groups[0].body;M.Body.translate(body,{x:0,y:g.h-1-body.bounds.max.y});M.Body.setVelocity(body,{x:0,y:0});M.Sleeping.set(body,true);const start=body.position.y;assert.ok(g.nudgeUp());let highest=start;for(let i=0;i<180;i++){g.tick(16.67);highest=Math.min(highest,body.position.y);}const height=start-highest;heights.push(height);results.push({speed,bounce,height:Number(height.toFixed(1))});g.destroy();}assert.ok(heights[0]>=25&&heights[0]<=55,heights);assert.ok(heights[1]>=85&&heights[1]<=150,heights);assert.ok(heights[2]>=200&&heights[2]<=340,heights);}fs.writeFileSync('artifacts/bounce-probe.json',JSON.stringify({method:'320×590 logical pixels, one supported square, one upward shake, actual physics peak; not real-device performance',results},null,2));});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {chromium} from 'playwright';import assert from 'node:assert/strict';import fs from 'node:fs';
|
||||
const browser=await chromium.launch({executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});const context=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://localhost:4173');const state=()=>page.evaluate(()=>shanheDebug.state());assert.equal((await state()).bounce,1);assert.equal(await page.locator('[data-bounce="1"]').getAttribute('aria-pressed'),'true');
|
||||
let tabs=await page.locator('.mode-tabs').boundingBox();await page.mouse.move(tabs.x+tabs.width-25,tabs.y+tabs.height/2);await page.mouse.down();await page.mouse.move(tabs.x+25,tabs.y+tabs.height/2,{steps:10});await page.mouse.up();assert.equal((await state()).level,'330000');assert.equal(await page.locator('[data-mode="city"]').getAttribute('aria-pressed'),'true');await page.waitForTimeout(400);const cityTrack=await page.locator('.mode-tabs').evaluate(e=>getComputedStyle(e,'::before').transform);assert.ok(!cityTrack.endsWith(', 0, 0)'),'滑块到达地级位置');
|
||||
tabs=await page.locator('.mode-tabs').boundingBox();await page.mouse.move(tabs.x+25,tabs.y+tabs.height/2);await page.mouse.down();await page.mouse.move(tabs.x+tabs.width-25,tabs.y+tabs.height/2,{steps:10});await page.mouse.up();assert.equal((await state()).level,'100000');await page.waitForTimeout(400);await page.locator('[data-mode="city"]').tap();assert.equal((await state()).level,'330000');await page.locator('#province-picker').tap();assert.ok((await page.locator('#province-picker').getAttribute('class')).includes('expanded'));await page.locator('[data-province="440000"]').tap();assert.equal((await state()).level,'440000');
|
||||
await page.locator('[data-bounce="2"]').tap();assert.equal((await state()).bounce,2);assert.ok((await page.locator('[data-bounce="2"]').getAttribute('class')).includes('bounce-pop'));await page.waitForTimeout(600);assert.ok(!(await page.locator('[data-bounce="2"]').getAttribute('class')).includes('bounce-pop'));assert.ok(await page.evaluate(()=>document.documentElement.scrollHeight<=innerHeight+1));await page.screenshot({path:'artifacts/animated-entry.png'});
|
||||
await page.locator('[data-mode="province"]').tap();await page.locator('[data-speed="3"]').tap();await page.clock.install();await page.locator('#start').tap();await page.clock.runFor(7800);await page.locator('#up').tap();await page.clock.runFor(320);const strong=await state();assert.equal(strong.bounce,2);assert.ok(strong.shakeCount>0);await page.screenshot({path:'artifacts/strong-bounce.png'});
|
||||
let seenContact=false;for(let i=0;i<70;i++){await page.clock.runFor(32);const s=await state();if(s.contactPulse>0){seenContact=true;await page.screenshot({path:'artifacts/contact-feedback.png'});break;}}assert.ok(seenContact,'真实碰撞触发短促反馈');
|
||||
const reduced=await browser.newContext({viewport:{width:320,height:568},reducedMotion:'reduce'});const rp=await reduced.newPage();rp.on('pageerror',e=>errors.push(e.message));await rp.goto('http://localhost:4173');await rp.locator('[data-bounce="2"]').click();assert.ok(!(await rp.locator('[data-bounce="2"]').getAttribute('class')).includes('bounce-pop'));assert.equal(await rp.locator('.mode-tabs').evaluate(e=>getComputedStyle(e,'::before').transitionDuration),'0s');assert.equal(await rp.locator('[data-bounce="2"]').evaluate(e=>getComputedStyle(e).animationName),'none');await rp.locator('#start').click();await rp.locator('#up').click();assert.equal((await rp.evaluate(()=>shanheDebug.state())).shakeCount,1);assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('artifacts/interactions-report.json',JSON.stringify({passed:true,results:['默认推荐蹦蹦跳','模式左右滑动和点击均更新真实关卡,滑块到位','省区选择与弹性按钮回弹不破坏点击','三向晃动和真实碰撞短反馈','减少动态效果设置禁用装饰动画,游戏仍可操作'],errors},null,2));console.log('滑动选择、回弹点击、强弹试玩、真实碰撞反馈与减少动态效果通过');await browser.close();
|
||||
@@ -0,0 +1,3 @@
|
||||
import {chromium} from 'playwright';import assert from 'node:assert/strict';import fs from 'node:fs';
|
||||
const browser=await chromium.launch({executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});const context=await browser.newContext({viewport:{width:390,height:844},deviceScaleFactor:2});const page=await context.newPage();
|
||||
await page.clock.install();await page.addInitScript(()=>{let seed=785;Math.random=()=>{seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;};});await page.goto('http://localhost:4173');await page.locator('[data-speed="3"]').click();await page.locator('#start').click();await page.clock.runFor(19500);const s=await page.evaluate(()=>window.shanheDebug.state());for(const name of ['上海','台湾','香港','澳门'])assert.ok(s.labels.some(b=>b.name===name),name+'应有可见标签');for(const box of s.labels){assert.ok(box.x>=3&&box.y>=3&&box.x+box.w<=s.width-3&&box.y+box.h<=s.height-4,box.name+'标签不得贴底或越界');}let collisions=[];for(let i=0;i<s.labels.length;i++)for(let j=0;j<i;j++){let a=s.labels[i],b=s.labels[j];const overlap=Math.max(0,Math.min(a.x+a.w,b.x+b.w)-Math.max(a.x,b.x))*Math.max(0,Math.min(a.y+a.h,b.y+b.h)-Math.max(a.y,b.y));if(overlap>1)collisions.push([a.name,b.name,overlap]);}assert.deepEqual(collisions,[]);await page.screenshot({path:'artifacts/labels-small-regions.png'});fs.writeFileSync('artifacts/label-report.json',JSON.stringify({passed:true,viewport:{width:390,height:844},pieces:s.dropped,labels:s.labels,collisions},null,2));console.log('小地区标签通过:台湾、香港、澳门、上海均可见,无贴底、越界或标签相互遮挡。');await context.close();await browser.close();
|
||||
@@ -0,0 +1,16 @@
|
||||
import {chromium} from 'playwright';import assert from 'node:assert/strict';import fs from 'node:fs';
|
||||
const browser=await chromium.launch({executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});
|
||||
const context=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});const p=await context.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));
|
||||
await p.addInitScript(()=>{let seed=785;Math.random=()=>{seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;};window.calls=[];window.xhs={miniTool:{writeTempFile:async args=>{window.exportData=args.data;window.calls.push('write');return {filePath:'test://fresh-card.png'};},postNote:async args=>{window.posted=args;window.calls.push('post');},saveImageToPhotosAlbum:async args=>{window.saved=args;window.calls.push('save');}}};});
|
||||
await p.clock.install();await p.goto('http://localhost:4173');await p.waitForFunction(()=>window.shanheDebug);await p.locator('[data-speed="3"]').click();await p.locator('[data-bounce="2"]').click();await p.locator('#start').click();await p.clock.runFor(19500);const before=await p.evaluate(()=>shanheDebug.state());assert.equal(before.status,'playing');await p.locator('#up').tap();await p.clock.runFor(100);assert.ok((await p.evaluate(()=>shanheDebug.state())).shakeY<0);await p.locator('#pause').tap();const paused=await p.evaluate(()=>shanheDebug.state());await p.clock.runFor(60000);assert.equal((await p.evaluate(()=>shanheDebug.state())).elapsed,paused.elapsed);await p.getByRole('button',{name:'结束旅程',exact:true}).tap();const ended=await p.evaluate(()=>shanheDebug.state());assert.equal(ended.screen,'result');assert.equal(ended.status,'ended');assert.equal(ended.result.bounceName,'弹力全开');assert.equal(ended.result.speedName,'山河起飞');assert.equal(ended.result.score,paused.score);assert.equal(ended.result.elapsed,paused.elapsed);assert.equal(ended.result.history.at(-1).ms,paused.elapsed);assert.equal(ended.result.history.at(-1).score,paused.score);assert.ok(ended.result.history.every((v,i,a)=>!i||v.ms>=a[i-1].ms));assert.equal(ended.result.dropped,ended.dropped);assert.ok(ended.dropped<34,'结局截图保留未完成状态');await p.screenshot({path:'artifacts/result-mobile.png'});
|
||||
await p.locator('#share-note').tap();await p.waitForFunction(()=>window.posted);const posted=await p.evaluate(()=>window.posted);assert.equal(posted.pageType,'photo_publish');assert.equal(posted.mediaInfo.image_resources[0].url,'test://fresh-card.png');assert.ok(posted.content.includes('弹力全开')&&posted.content.includes('山河起飞'));assert.ok(posted.title.length<=20&&posted.content.length<=1000);const image=await p.evaluate(()=>window.exportData);fs.writeFileSync('artifacts/result-card.png',Buffer.from(image.split(',')[1],'base64'));await p.locator('#save-card').tap();await p.waitForFunction(()=>window.saved);assert.deepEqual(await p.evaluate(()=>window.calls),['write','post','write','save']);
|
||||
// Failure/cancellation must leave the card usable; no-SDK must not throw.
|
||||
await p.evaluate(()=>{window.xhs.miniTool.postNote=async()=>{throw Error('cancelled');};});await p.locator('#share-note').tap();await p.waitForFunction(()=>!document.querySelector('#share-note').disabled);assert.equal(await p.locator('#result-screen').isVisible(),true);await p.evaluate(()=>{window.xhs=null;});await p.locator('#share-note').tap();assert.ok((await p.locator('#toast').textContent()).includes('小红书小工具'));
|
||||
for(const viewport of [{width:320,height:568},{width:375,height:667},{width:740,height:390}]){await p.setViewportSize(viewport);await p.waitForFunction(()=>{const r=document.querySelector('.result-actions').getBoundingClientRect();return r.bottom<=innerHeight;});assert.ok(await p.evaluate(()=>document.documentElement.scrollHeight<=innerHeight+1));const rect=await p.locator('#result-card').boundingBox();assert.ok(rect.width>20&&rect.height>20);}
|
||||
await p.setViewportSize({width:320,height:568});await p.addStyleTag({content:':root{--safe-area-inset-top:44px;--safe-area-inset-bottom:34px}'});await p.evaluate(()=>dispatchEvent(new Event('resize')));assert.ok(await p.evaluate(()=>document.documentElement.scrollHeight<=innerHeight+1));assert.ok(await p.locator('.result-actions').evaluate(e=>e.getBoundingClientRect().bottom<=innerHeight-34));
|
||||
await p.locator('#replay').tap();assert.equal((await p.evaluate(()=>shanheDebug.state())).dropped,1);assert.equal((await p.evaluate(()=>shanheDebug.state())).result,null);await p.locator('#pause').tap();await p.getByRole('button',{name:'结束旅程',exact:true}).tap();assert.equal((await p.evaluate(()=>shanheDebug.state())).result.score,0);await p.locator('#result-back').tap();assert.equal((await p.evaluate(()=>shanheDebug.state())).screen,'entry');assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('artifacts/results-report.json',JSON.stringify({passed:true,scope:'Browser regression with mocked native SDK; not real publish/save acceptance',result:ended.result,exportBytes:Buffer.from(image.split(',')[1],'base64').length,errors},null,2));console.log('成绩图真实结局、三档弹性记录、暂停计时、折线终点、图片原生API参数/失败降级及手机布局通过');
|
||||
// Automatic loss uses the full released map; victory uses a deliberately small
|
||||
// two-piece level fixture, exercising the real engine -> app -> image flow.
|
||||
await p.goto('http://localhost:4173');await p.locator('[data-speed="3"]').tap();await p.locator('#start').tap();await p.clock.runFor(90000);const lost=await p.evaluate(()=>shanheDebug.state());assert.equal(lost.screen,'result');assert.equal(lost.result.reason,'lost');assert.equal(lost.result.history.at(-1).score,lost.score);await p.screenshot({path:'artifacts/result-lost.png'});
|
||||
const winPage=await context.newPage();winPage.on('pageerror',e=>errors.push(e.message));await winPage.clock.install();const region=(id,y)=>({id,name:'测试'+id,center:[50,y+50],label:[50,y+50],rings:[[[0,y],[100,y],[100,y+100],[0,y+100]]]});const fixture={levels:[{id:'100000',name:'两块通关测试',width:1000,height:1000,regions:[region('0',100),region('1',0)],edges:[[0,1,0]]}]};await winPage.route('**/maps.js',route=>route.fulfill({contentType:'text/javascript',body:'Math.random=function(){return .5;};window.MAP_DATA='+JSON.stringify(fixture)+';'}));await winPage.goto('http://localhost:4173');await winPage.locator('[data-speed="3"]').tap();await winPage.locator('#start').tap();await winPage.clock.runFor(10000);const won=await winPage.evaluate(()=>shanheDebug.state());assert.equal(won.screen,'result');assert.equal(won.result.reason,'won');assert.equal(won.result.score,3300);assert.equal(won.result.history.at(-1).score,3300);await winPage.screenshot({path:'artifacts/result-won-fixture.png'});assert.deepEqual(errors,[]);console.log('真实地图自然判负、两块测试关卡自然通关均自动生成结局图,通关曲线包含奖励');const report=JSON.parse(fs.readFileSync('artifacts/results-report.json'));report.automaticEndings={lost:{reason:lost.result.reason,score:lost.score},wonFixture:{reason:won.result.reason,score:won.score}};fs.writeFileSync('artifacts/results-report.json',JSON.stringify(report,null,2));await browser.close();
|
||||
@@ -0,0 +1,15 @@
|
||||
// Exercise only public game controls. The virtual clock accelerates a real round.
|
||||
import {chromium} from 'playwright';import fs from 'node:fs';import assert from 'node:assert/strict';
|
||||
const browser=await chromium.launch({executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});
|
||||
const context=await browser.newContext({viewport:{width:390,height:844},deviceScaleFactor:2});
|
||||
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install();await page.goto('http://localhost:4173');await page.waitForFunction(()=>window.shanheDebug);await page.locator('[data-speed="3"]').click();await page.locator('#start').click();await page.clock.runFor(7800);
|
||||
let maxTilt=0,maxSpeed=0,maxEffects=0,collisions=0,observations=[];
|
||||
for(let k=0;k<16;k++){
|
||||
const key=k%2?'ArrowRight':'ArrowLeft';await page.keyboard.down(key);
|
||||
for(let j=0;j<4;j++){await page.clock.runFor(90);const s=await page.evaluate(()=>window.shanheDebug.state());maxTilt=Math.max(maxTilt,...s.regions.map(r=>Math.abs(r.angle)));maxSpeed=Math.max(maxSpeed,...s.regions.map(r=>Math.hypot(r.vx,r.vy)));maxEffects=Math.max(maxEffects,s.impactCount);collisions=Math.max(collisions,s.collisionCount);observations.push({pieceCount:s.dropped,frame:s.shakeOffset,impactCount:s.impactCount,status:s.status});if(s.status!=='playing')break;}
|
||||
await page.keyboard.up(key);await page.clock.runFor(120);
|
||||
if([3,7,11,15].includes(k))await page.screenshot({path:'artifacts/shake-motion-'+k+'.png'});
|
||||
}
|
||||
await page.clock.runFor(1200);const final=await page.evaluate(()=>window.shanheDebug.state());assert.ok(collisions>0);assert.ok(maxEffects>0);assert.ok(maxTilt<=.161);assert.ok(maxSpeed<18);assert.deepEqual(errors,[]);
|
||||
fs.writeFileSync('artifacts/shake-preview-report.json',JSON.stringify({passed:true,method:'390×844 modern Chrome; real controls; virtual clock; 16 alternating holds',pieces:final.dropped,collisions,maxEffects,maxTiltDegrees:maxTilt*180/Math.PI,maxSpeed,errors,observations},null,2));
|
||||
await context.close();console.log(JSON.stringify({pieces:final.dropped,collisions,maxEffects,maxTiltDegrees:maxTilt*180/Math.PI,maxSpeed}));await browser.close();
|
||||
Reference in New Issue
Block a user