Files
shanhe-puzzle/tests/county-levels.test.cjs
T
codex-bot 4845826deb
Shanhe source and offline package checks / verify (pull_request) Failing after 5s
feat: sync Shanhe 2.2 source and add remote package verification
2026-11-01 17:13:46 +08:00

55 lines
9.7 KiB
JavaScript

const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),M=require('matter-js');
const createAtlas=require('../src/atlas.js'),C=require('../src/core.js'),{Game}=require('../src/game.js');
const source=()=>{const box={window:{}};for(const f of ['maps.js','county-index.js'])vm.runInNewContext(fs.readFileSync('src/'+f,'utf8'),box);return {data:box.window.MAP_DATA,index:box.window.COUNTY_INDEX};};
const {data,index}=source();
function readStage(id){let result;vm.runInNewContext(fs.readFileSync('src/county/'+id+'.js','utf8'),{window:{PuzzleAtlas:{register:value=>{result=value;}}}});return result;}
function diskAtlas(){let reads=0,atlas;atlas=createAtlas(data,index,(meta,done)=>{reads++;atlas.register(readStage(meta.id));done(null);});return {atlas,reads:()=>reads};}
test('364关目录完整,县区329关2728块;旧35关ID不变,四个无县区子级城市不伪造关卡',()=>{
const {atlas}=diskAtlas();assert.equal(atlas.catalog.length,364);assert.equal(new Set(atlas.catalog.map(l=>l.id)).size,364);assert.equal(index.levels.reduce((n,l)=>n+l.count,0),2728);for(const l of data.levels)assert.equal(atlas.get(l.id),l);for(const id of ['441900','442000','460400','620200']){assert.equal(atlas.meta(id),null);assert.ok(atlas.unavailable(id));assert.ok(!atlas.catalog.some(l=>l.id===id));}
for(const meta of index.levels){assert.ok(data.levels.some(l=>l.id===meta.province));assert.ok(/^\.\/county\/\d{6}\.js$/.test(meta.path));}
});
test('地级县区按需加载,重复点选合并请求,仅缓存最近3关,淘汰后可重新打开',async()=>{
const {atlas,reads}=diskAtlas(),ids=index.levels.slice(0,5).map(l=>l.id);assert.equal(reads(),0);const a=atlas.load(ids[0]),b=atlas.load(ids[0]);assert.equal(a,b);const [x,y]=await Promise.all([a,b]);assert.equal(x,y);assert.equal(reads(),1);await atlas.load(ids[0]);assert.equal(reads(),1);
for(const id of ids.slice(1))await atlas.load(id);assert.equal(atlas.cacheSize(),3);assert.equal(atlas.get(ids[0]),null);assert.equal((await atlas.load(ids[0])).id,ids[0]);assert.equal(reads(),6);assert.ok(atlas.cacheSize()<=3);
});
test('并发打开超过缓存容量的关卡,各请求都返回自己的图形且缓存仍有上限',async()=>{
let atlas;atlas=createAtlas(data,index,(meta,done)=>{atlas.register(readStage(meta.id));Promise.resolve().then(()=>done(null));});const metas=index.levels.slice(0,7),levels=await Promise.all(metas.map(l=>atlas.load(l.id)));assert.deepEqual(levels.map(l=>l.id),Array.from(metas,l=>l.id));assert.equal(atlas.cacheSize(),3);
});
test('加载失败、缺少注册和同步异常均可重试,未知路径不发起读取',async()=>{
for(const failure of ['callback','missing','throw']){let attempts=0,atlas;atlas=createAtlas(data,index,(meta,done)=>{attempts++;if(attempts===1){if(failure==='throw')throw Error('broken');done(failure==='callback'?Error('missing'):null);return;}atlas.register(readStage(meta.id));done(null);});await assert.rejects(atlas.load('330100'));assert.equal((await atlas.load('330100')).id,'330100');assert.equal(attempts,2);await assert.rejects(atlas.load('../330100'));assert.equal(attempts,2);}
});
test('错误关卡/父级/数量拒绝注册,不把坏数据放进缓存',()=>{
const {atlas}=diskAtlas(),level=readStage('330100');for(const bad of [{...level,id:'999999'},{...level,province:'110000'},{...level,regions:[]},{...level,width:NaN}])assert.throws(()=>atlas.register(bad));assert.equal(atlas.cacheSize(),0);
});
test('全部329个县区关卡每个图块均能生成有限刚体,保持唯一队列和正常松手释放',()=>{
let pieces=0;for(const meta of index.levels){const level=readStage(meta.id),g=new Game(level,340,560,4,()=>{},()=>.5,1,0);g.start();assert.equal(g.queue.length,meta.count);assert.equal(new Set(g.queue).size,meta.count);const serial=g.pending.serial;g.holdPending(serial);assert.ok(g.releasePending(serial));assert.equal(g.dropped,1);
M.Composite.remove(g.engine.world,g.groups[0].body);g.groups=[];for(let i=0;i<level.regions.length;i++){const group=g.createGroup([i],{tx:0,ty:0,angle:0});assert.ok(Number.isFinite(group.body.mass)&&group.body.mass>0,meta.name);assert.ok(Number.isFinite(group.body.position.x)&&Number.isFinite(group.body.inertia));M.Composite.remove(g.engine.world,group.body);g.groups=[];pieces++;}g.destroy();}assert.equal(pieces,2728);
});
test('329个县区关卡按源地图正确位置均可拼到通关,包括海岛和环形地区',()=>{
for(const meta of index.levels){const level=readStage(meta.id),g=new Game(level,420,560,4,()=>{},()=>.5,1,2);g.status='playing';g.queue=[];g.rescale(Math.min(g.scale,380/(level.width*1.06),400/(level.height*1.06)));for(let i=0;i<level.regions.length;i++)g.createGroup([i],{tx:20,ty:130,angle:0});for(let i=0;i<level.regions.length+3;i++)g.tryMerges();assert.equal(g.status,'won',meta.id+' '+meta.name+' should be completable');assert.equal(g.groups[0].ids.length,level.regions.length);g.destroy();}
});
test('新增县区成绩和奖杯与省域成绩隔离,全部364关支持1092杯',()=>{
const {atlas}=diskAtlas();let progress={};for(const stage of atlas.catalog)for(let snap=0;snap<3;snap++)progress=C.finishProgress(progress,stage.id,snap,1,Number(stage.id)+snap,true);assert.equal(Object.keys(progress.triumphs).length,1092);const stats=C.journeyStats('330100',progress.records,progress.triumphs);assert.deepEqual(stats.wins,[true,true,true]);assert.equal(stats.best,330102);assert.equal(C.journeyStats('330000',progress.records,progress.triumphs).best,330002);
});
const {parse}=require('acorn'),appSource=fs.readFileSync('src/app.js','utf8'),navigationFunctions=parse(appSource,{ecmaVersion:2017}).body[0].expression.callee.body.body.filter(n=>n.type==='FunctionDeclaration'&&['selectProvince','selectCity','detailPlayable','displayLevelName','shortName'].includes(n.id.name)).map(n=>appSource.slice(n.start,n.end)).join('\n');
function navigation(){const {atlas}=diskAtlas(),messages=[],box={data,Atlas:atlas,screen:'entry',selectedProvince:null,selectedCity:null,pendingCity:null,mapRequest:0,mode:'province',level:data.levels[0],entryMap:data.levels[0],updateUI(){},drawReference(){},toast:value=>messages.push(value)};vm.createContext(box);vm.runInContext(navigationFunctions,box);return {box,messages};}
test('真实导航函数支持全国→浙江→杭州→浙江→全国,并保持县区难度可开局',async()=>{
const {box}=navigation();box.selectProvince('330000');assert.equal(box.mode,'city');await box.selectCity('330100');assert.equal(box.selectedProvince,'330000');assert.equal(box.selectedCity,'330100');assert.equal(box.level.regions.length,13);assert.equal(box.mode,'county');assert.equal(box.detailPlayable(),true);assert.equal(box.displayLevelName(),'浙江 · 杭州');box.selectProvince(box.selectedProvince);assert.equal(box.level.id,'330000');assert.equal(box.selectedCity,null);box.selectProvince(null);assert.equal(box.level.id,'100000');assert.equal(box.selectedProvince,null);
});
test('退出地图或改选其他城市后,迟到加载不会抢回已选地图',async()=>{
const {box}=navigation();box.selectProvince('330000');let done;box.Atlas={...box.Atlas,load:()=>new Promise(resolve=>{done=resolve;})};const task=box.selectCity('330100');assert.equal(box.pendingCity,'330100');assert.equal(box.detailPlayable(),false);box.selectProvince(null);done(readStage('330100'));await task;assert.equal(box.level.id,'100000');assert.equal(box.pendingCity,null);assert.equal(box.selectedCity,null);
const a=navigation();a.box.selectProvince('330000');const pending={};a.box.Atlas={...a.box.Atlas,load:id=>new Promise(resolve=>{pending[id]=resolve;})};const first=a.box.selectCity('330100'),second=a.box.selectCity('330200');pending['330200'](readStage('330200'));await second;pending['330100'](readStage('330100'));await first;assert.equal(a.box.level.id,'330200');
});
test('加载失败返回原省域可重试,不允许跨省误选或伪造无县区子级城市',async()=>{
const {box,messages}=navigation();box.selectProvince('440000');await box.selectCity('441900');assert.equal(box.level.id,'440000');assert.ok(messages[0].includes('下辖镇街'));await box.selectCity('330100');assert.equal(box.selectedCity,null);
box.selectProvince('330000');box.Atlas={...box.Atlas,load:async()=>{throw Error('failed');}};await box.selectCity('330100');assert.equal(box.pendingCity,null);assert.equal(box.level.id,'330000');assert.equal(box.detailPlayable(),true);assert.ok(messages.some(m=>m.includes('重试')));
});
test('真实杭州、楚雄和带内环的地级关卡连续出块晃动,普通物理解算保持无深穿透',()=>{
const proofs=JSON.parse(fs.readFileSync('research/county-map-index.json','utf8')),hole=proofs.levels.find(l=>l.regions.some(r=>r.sourceHoles>0)).id;
for(const code of new Set(['330100','532300',hole])){const level=readStage(code);let seed=19;const rng=()=>{seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;},g=new Game(level,340,560,4,()=>{},rng,1,0);g.start();
for(let i=0;i<1500&&g.status==='playing';i++){if(g.pending&&i%75===0){const serial=g.pending.serial;g.movePending(30+rng()*280,serial);g.holdPending(serial);g.releasePending(serial);}if(i%29===0&&g.groups.length)g.swipe({x:40+rng()*260,y:300+rng()*230},{x:(rng()-.5)*160,y:(rng()-.7)*140},60);g.tick(1000/60);
if(i%30===0)for(let a=0;a<g.groups.length;a++)for(let b=0;b<a;b++)for(const pa of g.groups[a].body.parts.length>1?g.groups[a].body.parts.slice(1):g.groups[a].body.parts)for(const pb of g.groups[b].body.parts.length>1?g.groups[b].body.parts.slice(1):g.groups[b].body.parts){if(!M.Bounds.overlaps(pa.bounds,pb.bounds))continue;const collision=M.Collision.collides(pa,pb);assert.ok(!collision||collision.depth<=3,code+' depth '+(collision&&collision.depth));}
}assert.ok(g.dropped>0);assert.ok(g.groups.every(p=>Number.isFinite(p.body.position.x)&&Number.isFinite(p.body.angle)));g.destroy();
}
});