Breakout Game JavaScript: Resolve Each Brick and Life Once

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>Breakout Game JavaScript: Resolve Each Brick and Life Once</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:#182333;--paper:#233247;--ink:#f4f5f8;--accent:#4c629a;--soft:#223c60;--muted:#d2deef}canvas{width:min(100%,640px);background:#0b1525;border:2px solid #7184ad;margin:auto;border-radius:8px;image-rendering:auto}</style></head><body><main><header><p class="eyebrow">Ball-and-paddle lab · Twelve original bricks</p><h1>Clear the bricks. Keep the state honest.</h1><p class="lede">A brick scores when it changes from alive to removed. A miss ends active play.</p><p class="hint">Original local ball-and-paddle game, 320 × 240 logical units. Canvas is supplemental to DOM status; no full assistive-game conformance claim.</p></header><section class="panel"><h2>Original brick field</h2><div id="arena" tabindex="0" role="group" aria-label="Ball game, left and right arrows move paddle"><canvas id="game" width="320" height="240" aria-hidden="true">Read the game status below.</canvas></div><div class="row"><button id="launch" type="button">Launch</button><button id="pause" type="button">Pause</button><button id="resume" type="button">Resume</button><button id="step" type="button">Step 0.05 s (paused)</button><button id="reset" type="button" class="secondary">Reset</button></div><div class="row"><button id="left" type="button">Paddle left</button><button id="right" type="button">Paddle right</button></div><p id="status" class="result" role="status"></p><p id="geometry"></p><p id="event" role="status"></p><p id="alive"></p></section><footer>Pause and step through a brick hit, then compare the score with the remaining brick IDs.</footer></main><script>
(()=>{'use strict';const $=id=>document.getElementById(id);
let x,y,vx,vy,paddle,bricks,lives,phase,raf=null,last=null,generation=0;const radius=6,eps=1e-7;const ctx=$('game').getContext('2d');function render(){if(ctx){ctx.clearRect(0,0,320,240);for(const b of bricks)if(b.alive){ctx.fillStyle=['#a6b6e6','#dbc28a','#85beb2'][Math.floor(b.id/4)];ctx.fillRect(b.x,b.y,60,12);}ctx.fillStyle='#f0e2a9';ctx.fillRect(paddle-30,210,60,10);ctx.beginPath();ctx.arc(x,y,6,0,Math.PI*2);ctx.fill();}$('status').textContent=phase+' · Score '+(12-bricks.filter(b=>b.alive).length)+' · Lives '+lives+' · Remaining '+bricks.filter(b=>b.alive).length+'.';$('geometry').textContent='Ball ('+x.toFixed(1)+','+y.toFixed(1)+'); velocity ('+vx.toFixed(1)+','+vy.toFixed(1)+'); paddle center '+paddle.toFixed(1)+'.';$('alive').textContent='Live brick IDs: '+bricks.filter(b=>b.alive).map(b=>'B'+String(b.id+1).padStart(2,'0')).join(', ');}function stop(){generation++;if(raf!==null)cancelAnimationFrame(raf);raf=null;last=null;}function resetBall(){x=160;y=190;vx=90;vy=-90;paddle=160;}function reset(){stop();resetBall();bricks=Array.from({length:12},(_,i)=>({id:i,x:[20,92,164,236][i%4],y:[30,48,66][Math.floor(i/4)],alive:true}));lives=3;phase='Awaiting Launch';$('event').textContent='Ready. Start a launch or inspect one paused step.';render();}function contacts(rect,max){const hits=[],left=rect.x,right=rect.x+60,upper=rect.y,lower=rect.y+12;function add(t,nx,ny){if(t>=-eps&&t<=max+eps&&vx*nx+vy*ny< -eps)hits.push({t:Math.max(0,t),nx,ny,brick:rect});}if(vx>0){const t=(left-radius-x)/vx,yy=y+vy*t;if(yy>=upper&&yy<=lower)add(t,-1,0);}if(vx<0){const t=(right+radius-x)/vx,yy=y+vy*t;if(yy>=upper&&yy<=lower)add(t,1,0);}if(vy>0){const t=(upper-radius-y)/vy,xx=x+vx*t;if(xx>=left&&xx<=right)add(t,0,-1);}if(vy<0){const t=(lower+radius-y)/vy,xx=x+vx*t;if(xx>=left&&xx<=right)add(t,0,1);}for(const[cx,cy,sx,sy]of [[left,upper,-1,-1],[right,upper,1,-1],[left,lower,-1,1],[right,lower,1,1]]){const dx=x-cx,dy=y-cy,a=vx*vx+vy*vy,b=2*(dx*vx+dy*vy),c=dx*dx+dy*dy-radius*radius,disc=b*b-4*a*c;if(disc<0)continue;const t=(-b-Math.sqrt(disc))/(2*a),xx=x+vx*t,yy=y+vy*t;if((xx-cx)*sx>=-eps&&(yy-cy)*sy>=-eps)add(t,(xx-cx)/radius,(yy-cy)/radius);}return hits;}function simulate(dt){let remaining=dt;for(let event=0;remaining>eps&&event<24;event++){const hits=[];function wall(t,nx,ny){if(t>=-eps&&t<=remaining+eps)hits.push({t:Math.max(0,t),nx,ny});}if(vx<0)wall((6-x)/vx,1,0);if(vx>0)wall((314-x)/vx,-1,0);if(vy<0)wall((6-y)/vy,0,1);if(vy>0){const t=(204-y)/vy,xx=x+vx*t;if(xx+6>=paddle-30&&xx-6<=paddle+30)wall(t,0,-1);}for(const b of bricks)if(b.alive)hits.push(...contacts(b,remaining));if(!hits.length){x+=vx*remaining;y+=vy*remaining;remaining=0;}else{hits.sort((a,b)=>a.t-b.t||(a.brick?.id??-1)-(b.brick?.id??-1));const t=hits[0].t,ties=hits.filter(h=>Math.abs(h.t-t)<=eps);x+=vx*t;y+=vy*t;remaining-=t;for(const h of ties)if(h.brick&&h.brick.alive){h.brick.alive=false;$('event').textContent='Removed B'+String(h.brick.id+1).padStart(2,'0')+' once; score +1.';}if(bricks.every(b=>!b.alive)){phase='Won';stop();return;}const normals=[];for(const h of ties)if(!normals.some(n=>Math.abs(n.nx-h.nx)<eps&&Math.abs(n.ny-h.ny)<eps))normals.push(h);for(const n of normals){const dot=vx*n.nx+vy*n.ny;if(dot<0){vx-=2*dot*n.nx;vy-=2*dot*n.ny;}}x=Math.max(6,Math.min(314,x));if(y<6)y=6;const nudge=Math.min(remaining,eps);x+=vx*nudge;y+=vy*nudge;remaining-=nudge;}}if(y-6>240){lives--;phase=lives?'Awaiting Launch':'Lost';stop();resetBall();$('event').textContent='One miss; one life removed. '+(lives?'Waiting for explicit Launch.':'No lives remain.');}}function loop(){const token=generation;function frame(timestamp){if(token!==generation||phase!=='Playing')return;const dt=last===null?0:Math.min(.05,Math.max(0,(timestamp-last)/1000));last=timestamp;simulate(dt);render();if(phase==='Playing')raf=requestAnimationFrame(frame);}raf=requestAnimationFrame(frame);}function launch(){if(phase!=='Awaiting Launch')return;stop();phase='Playing';loop();render();}function pause(){if(phase!=='Playing')return;stop();phase='Paused';render();}$('launch').addEventListener('click',launch);$('pause').addEventListener('click',pause);$('resume').addEventListener('click',()=>{if(phase!=='Paused')return;stop();phase='Playing';loop();render();});$('step').addEventListener('click',()=>{if(phase==='Won'||phase==='Lost'||phase==='Playing')return;if(phase==='Awaiting Launch')phase='Paused';simulate(.05);render();});function shift(n){if(phase==='Won'||phase==='Lost')return;paddle=Math.max(30,Math.min(290,paddle+n));render();}$('left').addEventListener('click',()=>shift(-20));$('right').addEventListener('click',()=>shift(20));$('arena').addEventListener('keydown',event=>{if(event.key!=='ArrowLeft'&&event.key!=='ArrowRight')return;event.preventDefault();if(event.repeat)return;shift(event.key==='ArrowLeft'?-20:20);});$('game').addEventListener('pointermove',event=>{if(phase==='Won'||phase==='Lost')return;const r=$('game').getBoundingClientRect();paddle=Math.max(30,Math.min(290,(event.clientX-r.left)*320/r.width));render();});window.addEventListener('blur',pause);document.addEventListener('visibilitychange',()=>{if(document.hidden)pause();});$('reset').addEventListener('click',reset);reset();
})();
</script></body></html>