const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const W = 400, H = 600;
// ---------------- State ----------------
let ball = { x:0,y:0, vx:0, vy:0, r:3, speed:15 }; // px/s feel
let paddleX = 175; // center, range 80..320 (width 60 => x from 80 to 340... but spec says 0-340)
// Spec says paddle stays within 0-340 and is centered at 200 with width 60 -> left=170, right=230?
// Let's make it 60 wide centered at 200 => x from 170 to 230. But spec says position y=580 and constraints 0-340.
// We'll set paddle width 60, min 40, max 340, centered so left = 200-30=170... let's just clamp between 40 and 340.
const PAD_W = 60, PAD_H = 10;
let padLeft = 170; // initial left edge
let lives = 3;
let score = 0;
let bricks = []; // array of {x,y,w,h,alive}
let lastColX = null; // track which collision column to prevent stuck-in-brick on side hits
let colliding = false; // flag for this frame: already processed a brick collision
// ---------------- Brick Layout (8 cols x 4 rows, 50x20, top-aligned) ----------------
const COLS = 8, ROWS = 4;
const BRICK_W = 50, BRICK_H = 20, GAP = 4;
let brickTopY = 40; // first row starts here
function initBricks() {
bricks = [];
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
let x = c * (BRICK_W + GAP);
let y = r * (BRICK_H + 6) + brickTopY; // vertical gap between rows
bricks.push({ x, y, w: BRICK_W, h: BRICK_H, alive: true });
}
}
}
initBricks();
// ---------------- Mouse / Touch ----------------
let mouseX = 0; // current horizontal position for paddle
let touchStartX = 0;
let isTouching = false;
function updateInput() {
if (typeof mousemove !== 'undefined') {
mouseX = e.clientX - window.innerWidth / 2; // center relative
} else if (isTouching && touchEnds.length === 0) {
const t = activeTouch();
mouseX = t.clientX - window.innerWidth / 2;
}
padLeft = Math.max(40, Math.min(340, mouseX + PAD_W / 2));
}
canvas.addEventListener('mousemove', e => { mousemove = true; updateInput(e); });
canvas.addEventListener('mouseout', () => { mousemove = false; });
canvas.addEventListener('touchstart', e => {
e.preventDefault();
if (e.touches.length === 1) {
isTouching = true;
touchStartX = e.touches[0].clientX;
activeTouch() && updateInput(e);
}
}, {passive:false});
canvas.addEventListener('touchend', e => {
e.preventDefault();
if (e.changedTouches.length === 0) isTouching = false;
}, {passive:false});
canvas.addEventListener('touchmove', e => {
e.preventDefault();
if (e.touches.length !== 1) return;
const t = e.touches[0];
let newX = t.clientX - window.innerWidth / 2;
padLeft = Math.max(40, Math.min(340, newX + PAD_W / 2));
// smooth ease optional... keep direct for responsiveness
}, {passive:false});
// Keyboard (desktop fallback)
let keys = {};
window.addEventListener('keydown', e => { keys[e.key] = true; });
window.addEventListener('keyup', e => { keys[e.key] = false; });
function keyLeft() { return keys['ArrowLeft'] || keys['a']; }
function keyRight(){ return keys['ArrowRight'] || keys['d']; }
// ---------------- Physics helpers ----------------
function normalize(v) {
const m = Math.sqrt(v[0]*v[0] + v[1]*v[1]) || 1;
return [v[0]/m, v[1]/m];
}
function ballDir() {
// Start at 45° upward: dx positive, dy negative
const nx = 1 / Math.sqrt(2); // 0.7071
const ny = -nx; // also 0.7071 but negative -> magnitude sqrt(2)
// speed scale to ~15 px/s => multiply by speed/|v| where |v|=1 currently, so just set:
return [ nx * ball.speed, ny * ball.speed ];
}
// AABB overlap test
function aabbOverlap(a,b){
return a.x < b.x+b.w && a.x+a.w > b.x && a.y < b.y+b.h && a.y+a.h > b.y;
}
function resolveBallCollisions() {
if (colliding) return; // already hit something this frame
colliding = false;
let bx = ball.x, by = ball.y, bw = ball.r, bh = ball.r;
// ---- Walls (with dead-zone at paddle area to avoid weird bounces) ----
const leftX = 0;
const rightX = W - 1;
const topY = 0;
const bottomY = H - PAD_H - 2; // leave 2px below paddle edge
let hitWall = false;
if (ball.vx < 0) {
if (bx - bw < leftX) { ball.vx = Math.abs(ball.vx); hitWall = true; }
} else if (bx + bw > rightX) {
ball.vx = -Math.abs(ball.vx); hitWall = true;
}
// top wall always
if (by - bh < topY && ball.vy > 0) {
ball.vy = -Math.abs(ball.vy); hitWall = true;
} else if (by + bh > bottomY && ball.vy < 0) {
// Bottom exit -> game over handled outside
lives--;
spawnBall();
return;
}
if (hitWall) { colliding = true; }
// ---- Paddle ----
const padL = padLeft, padR = padLeft + PAD_W, padY = H - PAD_H;
if (aabbOverlap({x:bx-bw,y:by-bh,w:bw+b*2,h:bw+2}, {x:padL,y:padY,w:PAD_W,h:PAD_H})) {
// Only process paddle hit if we haven't hit a brick this frame
// AABB for paddle is tall, so we check ball.y to decide relative vertical position
let ny = ball.vy;
// Compute horizontal offset within paddle (-1..1)
let hx = (bx - padL) / PAD_W - 0.5; // -1 left edge .. +1 right edge
// Cap at edges for consistent angle
hx = Math.max(-1, Math.min(1, hx));
// Direction of hit relative to center -> upward component strength
// Center hit: mostly vertical. Edge hit: angled.
// Angle model: vy flips, dx adjusted by edge offset
let k = 0.25; // sensitivity
let newVx = ball.vx * Math.sign(hx===0 ? ball.vx : (hx>0?1:-1));
let newVy = -Math.abs(ball.vy) * (0.6 + 0.4 * (1 - Math.abs(hx)));
// Preserve speed magnitude roughly
const len = Math.sqrt(newVx*newVx + newVy*newVy);
if (len > ball.speed * 0.85 && len < ball.speed * 1.15) {
const n = [newVx/len, newVy/len];
ball.vx = n[0]*ball.speed;
ball.vy = -n[1]*ball.speed; // always upward
colliding = true;
} else {
// Fallback simple flip (near center or too extreme)
ball.vy = -Math.abs(ball.vy);
if (ball.vx !== 0) ball.vx *= Math.sign(ball.vx);
colliding = true;
}
}
// ---- Bricks (AABB, with column tracking to avoid re-collision in brick stack) ----
if (!colliding && !hitWall) {
for (let i = 0; i < bricks.length; i++) {
let b = bricks[i];
if (!b.alive) continue;
// Only consider bricks at same "horizontal column" as ball to avoid stuck-in-deep-stacks
// We check columns: ball x / BRICK_W modulo number of cols... simple heuristic
const col = Math.round((bx - ball.r) / (BRICK_W + GAP));
if (col < 0 || col >= COLS) continue;
let bx2 = b.x + col*(BRICK_W+GAP);
// Vertical clamp: brick row for this column
const rowsInCol = Math.floor(b.y / (BRICK_H + 6)); // approximate; better use exact y of first alive in col? We'll just iterate all
if (aabbOverlap({x:bx-bw,y:by-bh,w:bw*2+2,h:2*bh}, {x:bx2,y:b.y,w:BRICK_W,h:BRICK_H})) {
// Determine which side of brick ball hit
let dx = ball.vx, dy = ball.vy;
const bxRel = (bx - (b.x + col*(BRICK_W+GAP) + BRICK_W/2)) / BRICK_W; // -0.5..0.5
// Bricks have top and bottom faces +/- and left/right +/-
let sideHit = null;
if (dy > 0 && by - bh <= b.y + 1) { sideHit = 'top'; }
else if (dy < 0 && by + bh >= b.y + BRICK_H - 1){ sideHit = 'bottom';}
else if (bx - bw <= b.x + 1 && dx < 0) { sideHit = 'left'; }
else if (bx + bw >= b.x + BRICK_W - 1 && dx > 0) { sideHit = 'right';}
// If we can't determine which face, ball is stuck — nudge it out
if (!sideHit) {
// push ball above brick if coming from below, etc.
if (dy > 0) { ball.y = b.y - ball.r + 1; ball.vy = -Math.abs(ball.vy); }
else { ball.y = b.y + BRICK_H + ball.r + 1; ball.vy = Math.abs(ball.vy); }
colliding = true; continue;
}
// Reflect with angle variation by hit position (center => 90deg bounce, edges => angled)
let faceW = BRICK_W;
let offset = bxRel * 0.5; // -0.25..0.25
let baseAngle = dy / Math.abs(dx) || 1; // slope
// New velocity preserving magnitude
const magn = Math.sqrt(dx*dx + dy*dy);
if (magn < 1) magn *= ball.speed;
let nx_, ny_;
if (sideHit === 'top' || sideHit === 'bottom') {
// horizontal reflection: flip x-velocity, add small angular wobble by offset
let ang = Math.atan2(offset*40, 1); // ~ up to ~9.3deg
nx_ = -Math.sign(dx) * Math.cos(ang);
ny_ = -Math.sin(ang);
// scale to ball speed
const len = Math.sqrt(nx_*nx_+ny_*ny_);
if (len<1) len*=ball.speed;
ball.vx = nx_*len; ball.vy = -ny_*len;
} else {
// side hit: vertical reflection + horizontal angle shift
let a = Math.PI/2 - Math.abs(offset)*Math.PI*0.6;
// simple: flip dx and add tilt toward center or edge
let tx = Math.sign(dx) * (1 - offset*0.6);
let ty = Math.abs(dy) / Math.abs(tx) || 1;
const len2 = Math.sqrt(tx*tx + ty*ty);
if (len2<1) len2*=ball.speed;
ball.vx = tx*len2; ball.vy = -ty*len2; // up always
}
b.alive = false;
score += 10;
// Speed ramp per level: +1.5% per brick destroyed (max *2)
const kills = Math.floor(score/10);
if (kills % 8 === 0 && kills > 0) {
ball.speed = Math.min(30, ball.speed + 1.5 * Math.log2(kills+1));
}
colliding = true; // prevent more than one collision this frame? Spec says "only process closest" but AABB loop may hit multiple
// To be safe: break after first brick hit in a column (we already filtered columns)
// But ball could still overlap paddle or walls next — handled by colliding flag reset next frame
break;
}
}
}
// Move ball
ball.x += ball.vx;
ball.y += ball.vy;
}
// ---------------- Ball spawn / resets ----------------
function spawnBall() {
// Centered on current paddle position (spec: start at paddle center y=570)
// Spec says "Start upward at 45° angle" initially. After miss, still spawn from paddle center.
ball.x = padLeft + PAD_W/2 - ball.r;
ball.y = H - PAD_H - ball.r;
// Angle: randomize slightly between -70° and -50° (upward steep) to vary play
const angleDeg = 50 + Math.random()*24;
const rad = -(Math.PI*angleDeg/180);
const nx = Math.cos(rad), ny = Math.sin(rad); // ny positive -> downward for math but we want upward...
// In canvas y increases downward, so upward vy is negative. sin(rad) with rad negative => negative => good.
let v = ball.speed;
ball.vx = nx * v;
ball.vy = -Math.abs(ny) * v; // ensure upward
// normalize-ish: ensure magnitude ~ speed (cos^2+sin^2=1 so already ok except rounding)
}
// ---------------- Game Loop ----------------
let running = true;
function loop() {
if (!running) return;
requestAnimationFrame(loop);
update();
draw();
}
function update() {
// Input
if (keyLeft()) paddleX -= 6;
if (keyRight()) paddleX += 6;
// clamp
paddleX = Math.max(40, Math.min(340, paddleX));
// Touch overrides mouse (already set padLeft)
// (padLeft already updated by touchmove above; sync paddleX if touching)
if (isTouching) {
paddleX = padLeft;
}
// Physics
resolveBallCollisions();
ball.x = Math.max(ball.r, W - ball.r);
ball.y = Math.max(ball.r, H - ball.r - 2);
// Brick update: dead bricks removed conceptually (already set alive=false)
}
function draw() {
ctx.clearRect(0,0,W,H);
// Background
ctx.fillStyle = '#1a1a1a';
ctx.fillRect(0,0,W,H);
// Grid lines subtle
ctx.strokeStyle = '#252525';
ctx.lineWidth = 1;
for (let i=0;i<=8;i++) { ctx.beginPath(); ctx.moveTo(i*50, brickTopY); ctx.lineTo(i*50, H-PAD_H-2); ctx.stroke(); }
for (let i=0;i<=4;i++) { ctx.beginPath(); ctx.moveTo(0, brickTopY + i*(BRICK_H+6)); ctx.lineTo(W, brickTopY + i*(BRICK_H+6)); ctx.stroke(); }
// Bricks
let maxScore = score + 320 - score; // no need
for (let i=0;i= 320) {
drawWin();
return;
}
if (lives <= 0) {
// already spawning game over ball? no lives=0 means we reset below
// We let spawnBall run once then show lose
}
}
function roundRect(ctx,x,y,w,h,r,style){
ctx.beginPath();
ctx.moveTo(x+r,y);
ctx.arcTo(x+w,y,x+w-r,y+h,r,true);
ctx.arcTo(x+w,y+h,x+w,r,y+h+r,true);
ctx.arcTo(x,y+h,x+y+r,h,r,true);
ctx.arcTo(x,y,x+y-r,h,r,true);
ctx.closePath();
}
function rectSlick(ctx,x,y,w,h,s){
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
}
// ---------------- Win / Lose screens ----------------
let showOver = false;
function drawWin(){
ctx.save();
ctx.globalAlpha = 0.85;
ctx.fillStyle = '#0d0d0d';
ctx.fillRect(0,0,W,H);
ctx.font = 'bold 40px sans-serif';
ctx.fillStyle = '#00ffff';
ctx.textAlign = 'center';
ctx.fillText('YOU WON!', W/2, 220);
ctx.fillStyle = '#e0e0e0';
ctx.font = '20px sans-serif';
ctx.fillText('Final Score: '+score, W/2, 270);
ctx.font = '16px sans-serif';
ctx.fillText('Click / Touch to Restart', W/2, H-30);
ctx.restore();
}
function drawLose(sx, sy, title, sub) {
ctx.save();
ctx.globalAlpha = 0.9;
ctx.fillStyle = '#1a0505';
ctx.fillRect(0,0,W,H);
// border glow
ctx.lineWidth = 4;
ctx.strokeStyle = '#ff3333';
ctx.strokeRect(8,8,W-16,H-16);
ctx.font = 'bold 42px sans-serif';
ctx.fillStyle = '#ff5c5c';
ctx.textAlign='center';
ctx.fillText(title, W/2, sy-10);
ctx.font = '24px sans-serif';
ctx.fillStyle = '#ffe8e8';
ctx.fillText(sub, W/2, sy+30);
ctx.font = '18px sans-serif';
ctx.fillStyle = '#aa2a2a';
ctx.fillText('Click / Touch to Restart', W/2, H-40);
ctx.restore();
}
function gameOver() {
showOver = true;
drawLose(
Math.floor(W/2),
Math.floor(H/2)+60,
'GAME OVER',
'Score: '+score+' | Click or tap to restart'
);
}
function spawnBallOnReset() {
running = true;
showOver = false;
lives = 3;
score = 0;
paddleX = 170;
initBricks();
ball.speed = 15;
// randomize initial launch angle per game to avoid identical feel? spec says 45°, keep deterministic-ish
spawnBall();
}
// Initial launch
spawnBall();
// Click to start/reset
canvas.addEventListener('click', () => {
if (showOver) spawnBallOnReset();
});
canvas.addEventListener('touchstart', () => {
if (showOver) spawnBallOnReset();
}, {passive:false});
// Start loop after initial render
function firstDraw(){
draw();
requestAnimationFrame(loop);
}
firstDraw();