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
+22
View File
@@ -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();
+33
View File
@@ -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));});
+9
View File
@@ -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();
+3
View File
@@ -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();
+16
View File
@@ -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();
+15
View File
@@ -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();