feat: add offline Shanhe Puzzle mini tool

This commit is contained in:
2026-10-16 22:06:27 +08:00
commit 9bd76c83cf
29 changed files with 1464 additions and 0 deletions
+9
View File
@@ -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+'段。');
+18
View File
@@ -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);
+1
View File
@@ -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);
+9
View File
@@ -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 与入口结构检查通过。');
+26
View File
@@ -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))
+26
View File
@@ -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))
+10
View File
@@ -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))
+121
View File
@@ -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'})
+6
View File
@@ -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'));