JavaScript Space Invaders: Derive the Edge from Live Targets
HTML for this example
Select the code and use your copy shortcut. Changes in this preview are temporary.
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JavaScript Space Invaders: Derive the Edge from Live Targets</title><style>*{box-sizing:border-box}body{margin:0;color:var(--ink,#233342);background:var(--bg,#eef2f3);font:17px/1.6 system-ui,sans-serif}main{max-width:980px;margin:auto;padding:clamp(16px,4vw,38px)}h1{font:700 clamp(30px,5vw,49px)/1.12 Georgia,serif;margin:10px 0 20px;max-width:800px}h2{font-size:24px;line-height:1.3;margin:0 0 15px}h3{font-size:19px;margin:12px 0}p{margin:0 0 16px}.eyebrow{font-weight:750;letter-spacing:.08em;text-transform:uppercase;font-size:16px}header{padding:10px 0 25px;border-bottom:3px solid var(--accent,#24586d);margin-bottom:24px}.lede{font-size:20px;max-width:760px}.panel{background:var(--paper,#fff);padding:clamp(18px,3vw,28px);border:1px solid var(--line,#c6d1d8);border-radius:12px;margin:20px 0}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px}.grid>*{min-width:0}.row{display:flex;gap:12px;flex-wrap:wrap;align-items:center;margin:16px 0}.stack>*{margin:12px 0}button{font:700 17px/1.4 system-ui,sans-serif;cursor:pointer;color:white;background:var(--accent,#24586d);border:2px solid var(--accent,#24586d);border-radius:7px;padding:11px 17px;max-width:100%;overflow-wrap:anywhere}button.secondary{background:transparent;color:var(--ink,#233342)}button[aria-pressed=true]{box-shadow:inset 0 0 0 3px #fff;outline:2px solid var(--ink,#233342)}button:disabled{opacity:.55;cursor:default}input,textarea,select{font:17px/1.5 system-ui,sans-serif;color:inherit;background:white;border:1px solid #778591;padding:10px 12px;border-radius:6px;max-width:100%;width:100%;min-width:0}input[type=checkbox]{width:22px;height:22px}textarea{min-height:110px;resize:vertical}label{display:block;font-weight:700;margin:12px 0 7px}button:focus-visible,input:focus-visible,textarea:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid #aa3d70;outline-offset:4px}.result{padding:18px;border-left:5px solid var(--accent,#24586d);background:var(--soft,#e5eff2);white-space:pre-wrap;overflow-wrap:anywhere;margin:20px 0}.result:empty{display:none}.hint{font-size:16px;color:var(--muted,#435968)}table{border-collapse:collapse;width:100%;table-layout:fixed;margin:16px 0}th,td{text-align:left;vertical-align:top;overflow-wrap:anywhere;padding:12px 8px;border-bottom:1px solid var(--line,#c6d1d8)}caption{text-align:left;font-weight:750;margin:8px 0}details{padding:18px;border:1px dashed #7b8b96;margin:20px 0}summary{cursor:pointer;font-weight:750}pre{font:16px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#162735;color:#f5f8fa;padding:18px;border-radius:8px}canvas,svg{display:block;max-width:100%;height:auto}footer{margin:28px 0;font-size:16px}.badge{font-weight:750;color:var(--accent,#24586d)}.metric{font:700 38px/1.3 Georgia,serif}.board{display:grid;gap:5px;max-width:440px;margin:20px auto}.board button{padding:7px;min-height:45px}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}@media(max-width:560px){.grid{grid-template-columns:1fr}main{padding:16px}th,td{padding:10px 5px}.row button{flex-grow:1}.metric{font-size:32px}}
:root{--bg:#11232d;--paper:#1c3542;--ink:#f3f7f6;--accent:#277082;--soft:#124555;--muted:#cde1e5}canvas{width:min(100%,640px);background:#071b25;border:2px solid #4d8796;margin:auto;border-radius:8px}</style></head><body><main><header><p class="eyebrow">Formation lab · Six original targets</p><h1>Move. Fire. Inspect the live edge.</h1><p class="lede">One bullet removes one live target, and removed targets stop defining the boundary.</p><p class="hint">Original neutral formation shooter. Step mode pauses wall-clock play; frozen-formation inspection is explicitly labeled.</p></header><section class="panel"><h2>Six targets · One live boundary</h2><div id="arena" tabindex="0" role="group" aria-label="Formation shooter, arrows move, Space fires"><canvas id="game" width="320" height="240" aria-hidden="true">Read the status below.</canvas></div><div class="row"><button id="start" type="button">Start</button><button id="pause" type="button">Pause</button><button id="resume" type="button">Resume</button><button id="advance" type="button">Advance 0.5 s (paused)</button><button id="reset" type="button" class="secondary">Reset</button></div><div class="row"><button id="left" type="button">Left</button><button id="right" type="button">Right</button><button id="fire" type="button">Fire</button><button id="freeze" type="button" aria-pressed="false">Toggle frozen-formation inspection</button><button id="boundary" type="button">Inspect boundary descent</button></div><p id="status" class="result" role="status"></p><p id="bounds"></p><p id="live"></p><p id="mode"></p><p id="event" role="status"></p></section><footer>Reset before the centered two-shot comparison, or load the labeled boundary-descent case.</footer></main><script>
(()=>{'use strict';const $=id=>document.getElementById(id);
let targets,ox,oy,direction,player,bullets,clock,lastShot,phase,frozen,raf=null,last=null,gen=0,nextBullet=1;const ctx=$('game').getContext('2d');function stop(){gen++;if(raf!==null)cancelAnimationFrame(raf);raf=null;last=null;}function limits(){const live=targets.filter(t=>t.alive);return live.length?{min:Math.min(...live.map(t=>t.x)),max:Math.max(...live.map(t=>t.x+24))}:{min:0,max:0};}function render(){if(ctx){ctx.clearRect(0,0,320,240);ctx.font='16px system-ui';for(const t of targets)if(t.alive){ctx.fillStyle='#89bec9';ctx.fillRect(t.x+ox,t.y+oy,24,16);ctx.fillStyle='#102d37';ctx.fillText(t.id,t.x+ox+4,t.y+oy+12);}ctx.fillStyle='#e4cc85';ctx.fillRect(player,216,24,12);for(const b of bullets)ctx.fillRect(b.x,b.y,4,8);}const live=targets.filter(t=>t.alive),l=limits();$('status').textContent=phase+' · Score '+(6-live.length)+' · Remaining '+live.length+' · Player x '+player.toFixed(1)+'.';$('bounds').textContent='Rightward offset limit: '+(320-l.max)+'. Current offset ('+ox.toFixed(1)+','+oy.toFixed(1)+'), direction '+(direction>0?'right':'left')+'.';$('live').textContent='Live IDs: '+live.map(t=>t.id).join(', ')+'. Bullets: '+bullets.length+'.';$('mode').textContent=frozen?'Inspection: formation frozen; projectile simulation continues.':'Formation movement enabled.';$('freeze').setAttribute('aria-pressed',String(frozen));}function reset(){stop();targets=Array.from({length:6},(_,i)=>({id:'T'+(i+1),x:[50,100,150][i%3],y:i<3?30:60,alive:true}));ox=oy=clock=0;direction=1;player=148;bullets=[];lastShot=-Infinity;phase='Ready';frozen=false;nextBullet=1;$('event').textContent='Ready. Start or use paused inspection.';render();}function sweep(b,oldT,newT,dt){const rx=b.x-oldT.x,ry=b.y-oldT.y,dx=-(newT.x-oldT.x),dy=-180*dt-(newT.y-oldT.y);let lo=0,hi=1;for(const[p,v,min,max]of [[rx,dx,-4,24],[ry,dy,-8,16]]){if(Math.abs(v)<1e-12){if(p<=min||p>=max)return null;}else{const a=(min-p)/v,z=(max-p)/v;lo=Math.max(lo,Math.min(a,z));hi=Math.min(hi,Math.max(a,z));if(lo>=hi)return null;}}return lo>=0&&lo<=1?lo:null;}
function advanceActors(dt){
if(!frozen)ox+=direction*40*dt;
clock+=dt;
for(const bullet of bullets)bullet.y-=180*dt;
bullets=bullets.filter(bullet=>bullet.y+8>=0);
}
function awardContacts(candidates){
candidates.sort((a,b)=>a.time-b.time||a.bullet.id-b.bullet.id||a.target.id.localeCompare(b.target.id));
const consumed=new Set();
for(const contact of candidates){
if(consumed.has(contact.bullet.id)||!contact.target.alive)continue;
consumed.add(contact.bullet.id);
contact.target.alive=false;
$('event').textContent='Bullet '+contact.bullet.id+' removed '+contact.target.id+' once; score +1. Contact at '+clock.toFixed(6)+' s.';
}
bullets=bullets.filter(bullet=>!consumed.has(bullet.id));
if(targets.every(target=>!target.alive)){
phase='Won';stop();
$('event').textContent='All six live IDs removed. Won.';
}
}
function descendAtBoundary(boundary){
ox=boundary;oy+=16;direction=-direction;
if(targets.some(target=>target.alive&&target.y+oy+16>=216)){
phase='Lost';stop();
$('event').textContent='Formation reached the player line. Loss before projectile scoring.';
return;
}
// Descent is an instantaneous position change, not a diagonal sweep.
const contacts=[];
for(const bullet of bullets)for(const target of targets){
if(target.alive&&bullet.x<target.x+ox+24&&bullet.x+4>target.x+ox&&bullet.y<target.y+oy+16&&bullet.y+8>target.y+oy){
contacts.push({time:clock,bullet,target});
}
}
awardContacts(contacts);
}
function simulate(total){
let remaining=total;
const epsilon=1e-10;
while(remaining>epsilon&&(phase==='Playing'||phase==='Paused')){
const bounds=limits();
const boundary=direction>0?320-bounds.max:-bounds.min;
const untilBoundary=frozen?Infinity:Math.max(0,(boundary-ox)*direction)/40;
const dt=Math.min(.005,remaining,untilBoundary);
const boundaryDue=!frozen&&untilBoundary<=dt+epsilon;
const candidates=[];
if(dt>epsilon){
const nextOx=frozen?ox:ox+direction*40*dt;
for(const bullet of bullets)for(const target of targets)if(target.alive){
const fraction=sweep(bullet,{x:target.x+ox,y:target.y+oy},{x:target.x+nextOx,y:target.y+oy},dt);
if(fraction!==null)candidates.push({time:fraction*dt,bullet,target});
}
}
const first=candidates.length?Math.min(...candidates.map(contact=>contact.time)):Infinity;
// A descent at the same instant takes precedence, including player-line loss.
if(first<dt-epsilon||(!boundaryDue&&first<=dt)){
advanceActors(first);remaining-=first;
awardContacts(candidates.filter(contact=>Math.abs(contact.time-first)<=epsilon));
continue; // Recompute live bounds after every removal.
}
advanceActors(dt);remaining-=dt;
if(boundaryDue)descendAtBoundary(boundary);
}
}
function loop(){const token=gen;function frame(t){if(token!==gen||phase!=='Playing')return;const dt=last===null?0:Math.min(.05,Math.max(0,(t-last)/1000));last=t;simulate(dt);render();if(phase==='Playing')raf=requestAnimationFrame(frame);}raf=requestAnimationFrame(frame);}function pause(){if(phase!=='Playing')return;stop();phase='Paused';render();}function fire(){if(phase==='Won'||phase==='Lost')return;if(clock-lastShot<.3-1e-9){$('event').textContent='Fire ignored: 0.3-second simulation cooldown.';return;}lastShot=clock;bullets.push({id:nextBullet++,x:player+10,y:208});$('event').textContent='One fresh projectile created.';render();}function shift(dx){if(phase==='Won'||phase==='Lost')return;player=Math.max(0,Math.min(296,player+dx));render();}$('boundary').addEventListener('click',()=>{reset();phase='Paused';ox=145.9;bullets=[{id:1,x:298,y:82}];nextBullet=2;$('event').textContent='Boundary case: offset 145.9, moving right; bullet (298,82). Advance to inspect descent at 0.002500 s.';render();});$('start').addEventListener('click',()=>{if(phase!=='Ready')return;stop();phase='Playing';loop();render();});$('pause').addEventListener('click',pause);$('resume').addEventListener('click',()=>{if(phase!=='Paused')return;stop();phase='Playing';loop();render();});$('advance').addEventListener('click',()=>{if(phase==='Playing'||phase==='Won'||phase==='Lost')return;phase='Paused';simulate(.5);render();});$('fire').addEventListener('click',fire);$('left').addEventListener('click',()=>shift(-12));$('right').addEventListener('click',()=>shift(12));$('freeze').addEventListener('click',()=>{if(phase==='Playing')pause();frozen=!frozen;render();});$('arena').addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight',' '].includes(event.key))return;event.preventDefault();if(event.repeat)return;if(event.key===' ')fire();else shift(event.key==='ArrowLeft'?-12:12);});$('game').addEventListener('pointermove',event=>{if(phase==='Won'||phase==='Lost')return;const r=$('game').getBoundingClientRect();player=Math.max(0,Math.min(296,(event.clientX-r.left)*320/r.width-12));render();});window.addEventListener('blur',pause);document.addEventListener('visibilitychange',()=>{if(document.hidden)pause();});$('reset').addEventListener('click',reset);reset();
})();
</script></body></html>