/* Style A review build. The original gameplay keeps its 430 × 600 field coordinates. UI geometry is scaled to a 750-wide reference and safe areas stay outside it. */ 'use strict'; const art={}; const atlasInfo={terrain:[2,2],towers:[5,2],enemies:[3,2],avatars:[4,2],props:[4,4]}; const artFiles={menu:'menu-desert',campaign:'mode-campaign',endless:'mode-endless',terrain:'terrain-atlas',towers:'tower-item-atlas',enemies:'enemy-atlas',avatars:'avatar-atlas',props:'props-atlas'}; for(const key of ['serpentine','longhorn','switchback','chokepoint'])artFiles['map-'+key]='../maps/'+key; for(const key of ['impact','frost','repair','muzzle','portal']){artFiles['fx-'+key]='../fx/'+key;atlasInfo['fx-'+key]=[8,1];} const review={frozen:true,stack:[],ready:false,failures:[],map:1}; const $=id=>document.getElementById(id); // Fixed navigation with a separately scrollable lobby keeps bottom actions reachable. const lobbyMain=document.createElement('div');lobbyMain.className='lobby-main'; const lobby=document.querySelector('.lobby');const lobbyNav=lobby.querySelector('.nav-row'); let lobbyChild=lobby.querySelector('.lb-player'); while(lobbyChild&&lobbyChild!==lobbyNav){const next=lobbyChild.nextElementSibling;lobbyMain.append(lobbyChild);lobbyChild=next;} lobby.insertBefore(lobbyMain,lobbyNav); if(new URLSearchParams(location.search).get('embed')==='1')document.body.classList.add('embed'); const safeTop=document.createElement('div'),safeBottom=document.createElement('div'); const safeProbe=document.createElement('div');safeProbe.style.cssText='position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)';document.body.append(safeProbe); safeTop.className='safe-zone top';safeBottom.className='safe-zone bottom';screenEl.append(safeTop,safeBottom); removeEventListener('resize',fit); fit=function(){ const embed=document.body.classList.contains('embed'); const [pw,ph,st,sb]=$('reviewSize').value.split(',').map(Number); const toolbar=embed?0:Math.ceil(document.querySelector('.review-toolbar').getBoundingClientRect().height); document.documentElement.style.setProperty('--toolbar-h',toolbar+'px'); const margin=embed?0:(innerWidth<=620?12:32); const availH=Math.max(160,innerHeight-toolbar-margin),availW=Math.max(160,innerWidth-margin); const w=embed?availW:Math.min(510,availW,availH*pw/ph); const h=embed?availH:w*ph/pw; device.style.setProperty('--preview-w',w+'px');device.style.setProperty('--preview-h',h+'px'); const ratio=w/430,pointWidth=pw===750?375:pw/3; const top=embed?(parseFloat(getComputedStyle(safeProbe).paddingTop)||0):st/pointWidth*w,bottom=embed?(parseFloat(getComputedStyle(safeProbe).paddingBottom)||0):sb/pointWidth*w; const logicalH=(h-top-bottom)/ratio; canvasRoot.style.transform=`scale(${ratio})`; canvasRoot.style.top=top+'px'; canvasRoot.style.setProperty('--logical-h',logicalH+'px'); safeTop.style.height=top+'px';safeBottom.style.height=bottom+'px'; const fieldScale=Math.max(.15,Math.min(1,(logicalH-88-172)/600)); field.style.width=FW*fieldScale+'px';field.style.height=FH*fieldScale+'px'; field.style.left=(430-FW*fieldScale)/2+'px'; field.style.top=88+Math.max(0,(logicalH-88-172-FH*fieldScale)/2)+'px'; screenEl.dataset.designSize=pw+'x'+ph; }; addEventListener('resize',fit); new ResizeObserver(fit).observe(document.querySelector('.review-toolbar')); $('reviewSize').addEventListener('change',fit); drawModeArt=function(){}; paintStartLandscape=function(){}; function sprite(c,key,index,x,y,w,h=w){ const im=art[key];if(!im||!im.complete||!im.naturalWidth)return; const [cols,rows]=atlasInfo[key],sw=im.naturalWidth/cols,sh=im.naturalHeight/rows; // Source rectangles exclude a tiny cell-edge guard to prevent sampling neighbours. c.drawImage(im,(index%cols)*sw+.5,Math.floor(index/cols)*sh+.5,sw-1,sh-1,x,y,w,h); } buildGround=function(){ if(!art.terrain)return; const c=bgc,mapIndex=MAP_DEFS.indexOf(CUR_MAP),random=seedRnd(1024+mapIndex*87); $('battleRoot').style.setProperty('--battle-terrain',`url('assets/sprites/terrain.${CUR_MAP.key}.png')`); if(art['map-'+CUR_MAP.key]?.naturalWidth){c.clearRect(0,0,FW,FH);c.drawImage(art['map-'+CUR_MAP.key],0,0,FW,FH);return;} c.clearRect(0,0,FW,FH);sprite(c,'terrain',Math.max(0,mapIndex),0,0,FW,FH); c.fillStyle='#edc48322';c.fillRect(0,0,FW,FH); const trace=(width,color)=>{c.beginPath();CUR_MAP.path.forEach((p,i)=>i?c.lineTo(...p):c.moveTo(...p));c.lineJoin='round';c.lineCap='round';c.lineWidth=width;c.strokeStyle=color;c.stroke();}; trace(53,'#714b2a55');trace(48,'#a47440');trace(41,'#c99859');trace(33,'#dcb275'); c.save();c.setLineDash([3,11]);trace(1.2,'#aa794b77');c.restore(); for(let i=0;i<38;i++){ const x=12+random()*406,y=15+random()*565; if(distToPath(x,y)<41||SLOTS.some(s=>Math.hypot(s.x-x,s.y-y)<38)||Math.hypot(BASE.x-x,BASE.y-y)<68)continue; const idx=4+Math.floor(random()*12),size=idx===15?50:25+random()*24; sprite(c,'props',idx,x-size/2,y-size*.78,size,size); } // A light perimeter vignette keeps play elements readable on the textured sand. const shade=c.createLinearGradient(0,0,FW,0);shade.addColorStop(0,'#56351c35');shade.addColorStop(.12,'#56351c00');shade.addColorStop(.88,'#56351c00');shade.addColorStop(1,'#56351c35');c.fillStyle=shade;c.fillRect(0,0,FW,FH); }; drawSlots=function(c){ SLOTS.forEach(s=>{if(s.tower)return;c.save();c.globalAlpha=G.selType?.85:.48;sprite(c,'props',2,s.x-22,s.y-17,44,34);c.globalAlpha=1; c.strokeStyle=G.selType?'#fff2ba':'#fff1c9aa';c.lineWidth=1.7;c.beginPath();c.moveTo(s.x-4,s.y);c.lineTo(s.x+4,s.y);c.moveTo(s.x,s.y-4);c.lineTo(s.x,s.y+4);c.stroke();c.restore();}); }; drawTower=function(c,t){ c.save();c.translate(t.x,t.y);const scale=1+(t.lv-1)*.06;c.scale(scale,scale); c.fillStyle='#3b241a44';c.beginPath();c.ellipse(2,8,23,9,0,0,TAU);c.fill(); sprite(c,'towers',TOWER_ORDER.indexOf(t.type),-29,Math.max(-t.y/scale,-43-(t.recoil||0)*.2),58,58); c.font='bold 9px Barlow';c.textAlign='center';c.lineWidth=2.5;c.strokeStyle='#41291c';c.fillStyle='#ffdb82';c.strokeText('★'.repeat(t.lv),0,20);c.fillText('★'.repeat(t.lv),0,20);c.restore(); }; drawEnemy=function(c,e){ const index=['rabbit','bison','wolf','vulture','scorpion','king'].indexOf(e.type);if(index<0)return; const size=e.boss?80:(e.type==='rabbit'?37:e.air?53:49); const bob=G.paused?0:Math.sin(G.time*(e.air?8:14)+e.seed)*(e.air?3:1.3); c.save();c.translate(e.x,e.y);c.fillStyle='#3a241f40';c.beginPath();c.ellipse(0,8,size*.3,size*.11,0,0,TAU);c.fill(); c.save();if(Math.cos(e.ang)<-.1)c.scale(-1,1);if(e.frozen>0)c.filter='sepia(.2) hue-rotate(145deg) saturate(.65) brightness(1.2)';else if(e.hitFlash>0)c.filter='brightness(1.6)'; sprite(c,'enemies',index,-size/2,-size*.52+bob,size,size);c.restore(); if(e.hpsprite(c,'fx-frost',frame,e.x-40,e.y-40,80));} else{const size=f.kind==='boom'?f.r*2.5:f.kind==='heal'?100:38;c.translate(f.x,f.y);if(f.kind==='muzzle')c.rotate(f.ang||0);sprite(c,'fx-'+key,frame,-size/2,-size/2,size);} c.restore(); }; function syncModal(){ review.stack=review.stack.filter(id=>$(id)?.classList.contains('is-open')); const top=review.stack.at(-1); document.querySelectorAll('.sheet').forEach(el=>{el.inert=!!top&&el.id!==top;el.setAttribute('aria-hidden',String(el.id!==top));}); document.querySelectorAll('.view').forEach(el=>el.inert=!!top||!el.classList.contains('is-active')); if(currentView==='battle')G.paused=review.frozen||!!top; } openSheet=function(id){ const el=$(id);if(!el)return;review.stack=review.stack.filter(x=>x!==id);review.stack.push(id); el.classList.add('is-open');el.style.zIndex=60+review.stack.length;el.setAttribute('role','dialog');el.setAttribute('aria-modal','true'); const title=el.querySelector('h2');if(title){if(!title.id)title.id=id+'Title';el.setAttribute('aria-labelledby',title.id);} syncModal();el.querySelector('button:not([disabled]),input,[data-close]')?.focus({preventScroll:true}); }; closeSheet=function(id){$(id)?.classList.remove('is-open');review.stack=review.stack.filter(x=>x!==id);syncModal();}; closeAllSheets=function(){document.querySelectorAll('.sheet').forEach(s=>s.classList.remove('is-open'));review.stack=[];syncModal();}; const originalShowView=showView; showView=function(name){originalShowView(name);syncModal();}; const originalStartBattle=startBattle; startBattle=function(mode,level){review.frozen=false;setPlayButton();originalStartBattle(mode,level);fit();syncModal();}; $('btnResume').onclick=()=>closeSheet('sheetPause'); document.querySelectorAll('[data-close]').forEach(el=>el.onclick=()=>closeSheet(el.dataset.close)); addEventListener('keydown',e=>{ if(e.key==='Tab'&&review.stack.length){const panel=$(review.stack.at(-1));const nodes=[...panel.querySelectorAll('button:not([disabled]),input,[tabindex="0"]')].filter(el=>el.getClientRects().length);if(nodes.length){const at=nodes.indexOf(document.activeElement),next=e.shiftKey?(at<=0?nodes.length-1:at-1):(at+1)%nodes.length;nodes[next].focus();e.preventDefault();}return;} if(e.key!=='Escape')return;e.preventDefault();e.stopImmediatePropagation();const top=review.stack.at(-1); if(top){if(top!=='sheetResult')closeSheet(top);return;} if(G.armed){G.armed=null;renderItemDock();toast('Airstrike cancelled');return;} if(G.selTower){closeTowerPanel();return;} if(currentView==='battle')openSheet('sheetPause'); },true); // Validate use before spending. Full-health repair never costs coins or inventory. confirmBuy=function(){ const it=ITEMS[buyKey];if(!it||G.phase==='done')return; if(buyKey==='repair'&&G.baseHP>=G.maxHP){toast('Base is already at full HP');return;} if(state.coins=G.maxHP){toast('Base is already at full HP');return;}originalUseItem(k);}; $('btnNextWave').onclick=()=>{if(G.phase==='prep'){G.gold+=25;G.prepLeft=0;startNextWave(false);floatText(BASE.x,BASE.y-70,'+25 EARLY','255,235,180');updateHUD(true);}else toast('Wave in progress');}; function setPlayButton(){const b=$('reviewLive');b.textContent=review.frozen?'播放战斗':'冻结画面';b.setAttribute('aria-pressed',String(!review.frozen));} function sampleSave(){ state=defaults();state.coins=1500;state.cleared=5;state.stars={1:3,2:3,3:3,4:2,5:2};state.best={score:8640,wave:12};state.player={name:'Desert Ranger',id:'10086001',avatar:'bison'}; state.armory.archer=2;state.tutorial=1;state.stats={kills:628,waves:42,towers:57}; state.board.push({name:state.player.name,score:8640,wave:12,me:true});save();ensurePlayer(); } function battleFixture(kind){ originalStartBattle(kind==='endless'?'endless':'campaign',kind==='endless'?0:review.map); G.level=kind==='endless'?0:6;G.totalWaves=8;G.wave=kind==='boss'?5:3;G.score=1240;G.kills=28;G.baseHP=18;G.gold=320;G.time=4;G.queue=[];G.enemies=[];G.fx=[];G.projs=[];G.towers=[]; $('hudMode').textContent=kind==='endless'?'ENDLESS':'STAGE 6'; const choices=[2,6,10,14,18].map(i=>SLOTS[Math.min(i,SLOTS.length-1)]); choices.forEach((slot,i)=>{if(slot.tower)return;const type=TOWER_ORDER[i],t={slot,type,lv:i===0?2:1,cd:.6,invested:TOWERS[type].cost,x:slot.x,y:slot.y,angle:0,combos:[],recoil:0,flash:0};slot.tower=t;G.towers.push(t);}); recomputeCombos(); const enemies=kind==='boss'?['bison','king','wolf','scorpion','vulture']:['rabbit','rabbit','bison','wolf','bison','scorpion','vulture']; enemies.forEach((type,i)=>{spawnEnemy(type,140+i*130);const e=G.enemies.at(-1);e.ang=posAt(e.d).ang;if(i===3)e.hp=Math.round(e.maxHp*.65);}); G.waveTotalCount=18;G.phase='running';review.frozen=true;G.running=true;G.paused=true; renderDock();renderItemDock();updateHUD(true);closeTowerPanel();fit(); if(kind==='tower')openTowerPanel(G.towers[0]); if(kind==='build'){G.selType='rifle';document.querySelector('[data-type="rifle"]')?.classList.add('is-sel');$('dockHint').innerHTML='Tap a gold slot to build Rifle';} if(kind==='skill'){G.enemies.forEach(e=>e.frozen=4);addFx('frost',0,0,{life:.8});G.fx.at(-1).t=.2;} if(kind==='buy')openBuy('frost'); if(kind==='pause')openSheet('sheetPause'); if(['victory','defeat','endless'].includes(kind)){G.phase='done';G.running=false;G.firstClear=true;G.score=kind==='endless'?8640:3240;G.kills=56;showResult(kind==='victory',kind==='endless'?12:8,kind==='defeat'?0:kind==='endless'?390:1060,kind==='endless');} setPlayButton();syncModal();draw(); } function previewScreen(name){ closeAllSheets();closeTowerPanel();G.running=false;G.phase='done';lobbyMain.scrollTop=0; const battleStates=['battle','build','boss','tower','skill','buy','pause','victory','defeat','endless']; if(battleStates.includes(name)){battleFixture(name);} else if(['lobby','start','loading','levels'].includes(name)){showView(name);if(name==='loading'){$('bootFill').style.width='68%';$('bootPct').textContent='LOADING… 68%';}} else{showView('lobby');const actions={armory:()=>openArmory(),shop:()=>{renderShop();openSheet('sheetShop');},checkin:()=>{renderCheckin();openSheet('sheetCheckin');},profile:()=>openProfile(),avatar:()=>{openProfile();profShow('avatar');},rename:()=>{openProfile();profShow('rename');},board:()=>{renderBoard();openSheet('sheetBoard');},settings:()=>{renderSettings();openSheet('sheetSettings');},help:()=>{renderHelp();openSheet('sheetHelp');},terms:()=>openDoc('terms'),privacy:()=>openDoc('privacy')};actions[name]?.();} $('reviewStatus').textContent='素材已加载 · 交互数据仅保存在本地';fit(); } const screenSelect=$('reviewScreen'); for(const [value,label]of [['build','战斗 · 建造选中'],['skill','战斗 · 冰冻技能']]){const option=new Option(label,value);screenSelect.add(option,screenSelect.options[6]);} const mapLabel=document.createElement('label');mapLabel.innerHTML='地图 '; document.querySelector('.review-controls').insertBefore(mapLabel,$('reviewLive')); const focusLink=document.createElement('a');focusLink.href='?embed=1';focusLink.target='_blank';focusLink.rel='noopener';focusLink.textContent='手机全屏 ↗';document.querySelector('.review-controls').append(focusLink); $('reviewMap').onchange=e=>{review.map=Number(e.target.value);if(currentView==='battle')previewScreen(screenSelect.value);}; screenSelect.onchange=()=>{if(review.ready)previewScreen(screenSelect.value);}; $('reviewLive').onclick=()=>{if(currentView!=='battle'){screenSelect.value='battle';previewScreen('battle');}if(G.phase==='done'){screenSelect.value='battle';previewScreen('battle');}review.frozen=!review.frozen;setPlayButton();syncModal();}; $('reviewReset').onclick=()=>{sampleSave();screenSelect.value='lobby';previewScreen('lobby');toast('Preview sample restored');}; // Give custom controls keyboard support without changing original pointer handlers. const a11yObserver=new MutationObserver(()=>{ document.querySelectorAll('.icon-btn,.mode,.ars,.nav,.lv,.tcard,.item,.panel__x,.av-cell,.set-row,.lb-player,.coinpill,.link,[data-close]').forEach(el=>{ if(el.tagName==='BUTTON'||el.dataset.keyboard)return;el.dataset.keyboard='1';el.tabIndex=0;el.setAttribute('role','button');el.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();el.click();}}); if(!el.textContent.trim()&&!el.getAttribute('aria-label'))el.setAttribute('aria-label',el.title||el.dataset.close&&'Close'||'Open'); }); });a11yObserver.observe(canvasRoot,{childList:true,subtree:true}); async function loadArt(){ let loaded=0; await Promise.all(Object.entries(artFiles).map(([key,file])=>new Promise(resolve=>{ const im=new Image();art[key]=im;im.onload=()=>{loaded++;const pct=Math.round(loaded/Object.keys(artFiles).length*100);$('bootFill').style.width=pct+'%';$('bootPct').textContent='LOADING… '+pct+'%';resolve();};im.onerror=()=>{review.failures.push(file);resolve();};im.src='assets/art/'+file+'.png'; }))); await document.fonts.ready; if(review.failures.length){$('reviewStatus').textContent='素材未加载:'+review.failures.join(', ');return;} let saved=false;try{saved=!!localStorage.getItem(SAVE_KEY);}catch{} if(saved){load();ensurePlayer();}else sampleSave(); buildGround();review.ready=true;previewScreen(new URLSearchParams(location.search).get('screen')||screenSelect.value||'lobby'); const requested=new URLSearchParams(location.search).get('screen');if(requested)screenSelect.value=requested; } fit();loadArt();