[reasoning, returned separately by llama-server]
The user wants a complete falling-block puzzle game (Tetris-like, but without the word "Tetris"). Requirements:
- 10x20 grid, 7 standard pieces (I, O, T, S, Z, J, L)
- Pieces fall automatically, speed up with lines cleared
- Arrow keys: left/right move, up rotates, down soft drop, space hard drop, P pause
- Arrow keys and space must not scroll page
- Collision with walls, floor, other pieces
- Full row clears, rows above move down
- Show score, lines cleared, next piece
- Before start, show controls on page; game starts on click or key press
- Game over message on page; Enter or click restarts
- All messages on page itself, no alert/confirm/prompt
- Sound optional, off until player turns it on
- No localStorage etc.
- Page fits in 800x640 frame
- All inline, no external resources
- No word "Tetris" anywhere
Let me design a polished game. I'll use a canvas for the grid rendering with nice visuals: gradient background, glowing blocks, animated line clears, particles, etc.
Design plan:
- Layout: header with title, main area with canvas (grid), side panel with score/lines/next piece, footer with controls.
- Canvas: 10x20 grid, cell size ~28px → 280x560. Plus side panel. Total width 800, height 640.
Let me compute: 800x640 frame. Header ~50px, footer ~30px. Main area ~560px. Grid 10 cols x 20 rows. Cell 26px → 260x520. Side panel ~200px wide.
Actually let's do cell 27px: 270x540. Header 46, footer 26 → 540+72 = 612, fits in 640.
Visual style: dark neon aesthetic. Canvas with glow effects. Blocks drawn with gradients and inner highlights. Line clear animation: flash rows then remove. Particles on clear. Ghost piece (drop preview) — nice touch.
Game logic:
- Standard 7 pieces with rotation states. Use SRS-ish rotation but simple: rotate matrix clockwise, with basic wall kicks (try offsets 0, -1, +1, -2, +2).
- Scoring: 1 line 100, 2 lines 300, 3 lines 500, 4 lines 800 (times level multiplier maybe). Speed: base interval decreases with lines.
- Next piece preview: draw on small canvas.
- Pause with P.
- Sound: WebAudio, off by default, toggle with M key maybe. Requirement says sound optional, must stay off until player turns it on. I'll add a sound toggle button/key (M). Keep it simple: M toggles sound.
States: 'ready' (controls shown, waiting for click/key), 'playing', 'paused', 'gameover'.
Messages on page: overlay divs on the page (not alert). Show "Press any key or click to start", "Paused", "Game Over — press Enter or click to restart".
Controls shown before start: list of keys.
Let me write the code carefully.
Pieces definitions (matrices):
```
I: [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
O: [[1,1],[1,1]]
T: [[0,1,0],[1,1,1],[0,0,0]]
S: [[0,1,1],[1,1,0],[0,0,0]]
Z: [[1,1,0],[0,1,1],[0,0,0]]
J: [[1,0,0],[1,1,1],[0,0,0]]
L: [[0,0,1],[1,1,1],[0,0,0]]
```
Colors:
I: cyan #22d3ee
O: yellow #facc15
T: purple #c084fc
S: green #4ade80
Z: red #f87171
J: blue #60a5fa
L: orange #fb923c
Rotation: rotate matrix clockwise. For O piece, rotation is no-op.
Collision: check cells within bounds (x in 0..9, y in 0..19; y can be negative for spawn above? Standard: allow y negative for spawning, but collision with floor/walls. I'll allow negative y (above grid) for spawning; blocks above grid don't collide with walls horizontally? Actually walls: x must be >=0 and <10 regardless of y. Floor: y < 20. Other pieces: only check cells with y>=0.
Spawn: piece at x = 3 (for 3-wide) or 4 (for 2-wide O), y = 0 or -1. If collision at spawn → game over.
Game loop: requestAnimationFrame with accumulator for gravity. Gravity interval = max(50, 800 * pow(0.85, level)) or based on lines: interval = max(60, 800 - lines*20)? Let's do: speed level = floor(lines/10); interval = max(70, 800 * Math.pow(0.8, level)). Or simpler: interval = Math.max(60, 800 - lines * 15). Speed up as player clears more lines — either works. I'll use level-based: level = 1 + floor(lines/10), interval = max(60, 800 * Math.pow(0.82, level-1)).
Soft drop: down arrow increases fall speed (interval 30ms while held). Hard drop: space — move to bottom, lock immediately.
Line clear animation: when rows full, mark them, flash for ~250ms, then remove and add particles. During animation, pause gravity.
Particles: on clear, spawn particles at cleared rows.
Ghost piece: draw translucent outline of where piece would land.
Score: 1→100, 2→300, 3→500, 4→800, multiplied by level.
Next piece: queue of 2 (current + next). Show next in side panel.
Rendering: canvas 2D. Draw grid background, cells with subtle grid lines, locked blocks, current piece, ghost, particles, clear flash.
Also draw side panel next piece on a small canvas.
Sound: WebAudio simple beeps — move, rotate, lock, clear, game over. Toggle with M. Off by default.
Page layout:
```
title "BLOCKFALL" or something — avoid "Tetris". Maybe "NEON BLOCKS" or "FALLING BLOCKS". Let's call it "BLOCK RUSH" or "TETRIS-like"... no, avoid the word entirely. "BLOCKFALL" is fine.
message
```
Overlay: absolutely positioned over the board area (or whole wrap) with semi-transparent background, showing message and controls.
Messages:
- Ready: "BLOCKFALL" title, controls list, "Click or press any key to start"
- Paused: "PAUSED — press P to resume"
- Game over: "GAME OVER", final score, "Press Enter or click to restart"
Key handling:
- keydown: if state ready → start game (any key). If gameover → Enter or click restarts (also any key? Requirement: "player can start a new game with the Enter key or a click". So on gameover, only Enter or click restarts; other keys ignored). If playing: arrows, space, P, M.
- Prevent default on arrows and space.
Key repeat: left/right with key repeat is fine (keydown repeats). Rotation on keydown repeat could be annoying but acceptable; maybe ignore repeat for rotation? Keep it simple: allow repeat but it's fine. Actually rotation with repeat is okay.
Down arrow: soft drop — while held, fall faster. Track key state.
Let me handle keydown/keyup for down arrow soft drop.
Implementation details:
```js
const COLS=10, ROWS=20, CELL=26;
```
Canvas size: 260 x 520. Plus maybe devicePixelRatio scaling for crispness. I'll scale canvas by dpr.
Let me write the full code.
```html
Blockfall
...
```
Frame 800x640: wrap exactly 800x640.
Layout inside: header 54px, main flex row: board canvas + aside 210px, footer 34px.
Board canvas: 260x520. Aside: ~230px. Total: 260 + 230 + gaps + padding ≈ 800. Let's compute: wrap padding 12px each side → inner 776. Board 260 + gap 14 + aside 240 = 514... too much. Let's make aside 250 and board 260: 260+14+250=524, plus padding 24 = 548. Hmm, 800 wide is generous. Maybe increase cell size to 28: board 280x560. Header 48, footer 30 → 560+78=638. Tight. Cell 27: 270x540, header 46, footer 28, gaps 8 → 540+46+28+16=630. OK.
Let me just do: wrap 800x640, padding 10. Header 44. Main: board 270x540 + aside 250. 270+12+250 = 532 + 20 padding = 552... that leaves 248px unused. Hmm, 800 is wide. Maybe make board bigger: cell 30 → 300x600. Too tall with header. Cell 28 → 280x560; header 44 + footer 26 + gaps 12 = 82; 560+82=642 > 640. Cell 27 → 270x540; 540+82=622, fits with 18px slack. Good.
Aside width: 800 - 20 (padding) - 270 - 12 (gap) = 498? No: 800 - 20 = 780; 780 - 270 - 12 = 498. That's huge. Hmm, maybe center the board and aside with more spacing, or make aside wider with nice panels. 498px aside is too wide. Alternative: make the board cell 30 and reduce rows? No, must be 20 rows.
Option: cell 28 → board 280x560. Header 40, footer 24, gaps 8 → 560+72=632. Fits. Aside: 780-280-12 = 488. Still wide.
Alternatively, center content: board + aside centered with gap 20, aside 260px. Total 280+20+260=560, centered in 800 → 120px margins each side. That looks fine with a nice background. Or add decorative side panels. Let's do: main area flex, justify-content:center, gap 24. Aside 250px. Board 280x560. Total 554, centered. Good.
Actually, let me reconsider: maybe make the board cell 28 and add a decorative frame around it. Fine.
Let me now write the JS.
```js
const COLS = 10, ROWS = 20, CELL = 28;
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
canvas.width = COLS*CELL*dpr; canvas.height = ROWS*CELL*dpr;
canvas.style.width = COLS*CELL+'px'; canvas.style.height = ROWS*CELL+'px';
ctx.scale(dpr,dpr);
```
Pieces:
```js
const SHAPES = {
I: { color:'#22d3ee', matrix:[[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]] },
O: { color:'#facc15', matrix:[[1,1],[1,1]] },
T: { color:'#c084fc', matrix:[[0,1,0],[1,1,1],[0,0,0]] },
S: { color:'#4ade80', matrix:[[0,1,1],[1,1,0],[0,0,0]] },
Z: { color:'#f87171', matrix:[[1,1,0],[0,1,1],[0,0,0]] },
J: { color:'#60a5fa', matrix:[[1,0,0],[1,1,1],[0,0,0]] },
L: { color:'#fb923c', matrix:[[0,0,1],[1,1,1],[0,0,0]] },
};
const PIECE_KEYS = Object.keys(SHAPES);
```
State:
```js
let grid, current, next, score, lines, level, state, dropTimer, dropInterval, particles, clearing, clearTimer, softDrop, soundOn;
```
Functions:
- resetGame()
- spawnPiece()
- collide(matrix, px, py)
- rotate(matrix)
- move(dx), rotatePiece(), softDrop handling, hardDrop()
- lockPiece()
- clearLines()
- update(dt)
- render()
Game loop with rAF:
```js
let last = 0;
function loop(t) {
const dt = t - last; last = t;
if (state === 'playing') update(dt);
render();
requestAnimationFrame(loop);
}
```
Update: dropTimer += dt; if clearing, handle clear timer; else if dropTimer >= interval, move down or lock.
Clearing animation: when lockPiece finds full rows, set clearing = rows, clearTimer = 0, state stays 'playing' but gravity paused. After 300ms, remove rows, add particles, update score/lines, spawn next.
Particles: array of {x,y,vx,vy,life,color}. Update in render or update.
Render:
- clear canvas, draw background gradient
- draw grid lines
- draw locked blocks
- draw ghost
- draw current piece
- draw clearing rows flash (white/bright overlay with alpha oscillating)
- draw particles
Block drawing: rounded rect with gradient + highlight.
```js
function drawBlock(x,y,color,alpha=1) {
const px = x*CELL, py = y*CELL;
// gradient
const g = ctx.createLinearGradient(px,py,px,py+CELL);
g.addColorStop(0, lighten(color));
g.addColorStop(1, color);
...
}
```
Lighten: I'll precompute lighter/darker shades per piece. Simpler: use two-tone gradient with white overlay. E.g., fill with color, then overlay white gradient at top with low alpha, and dark at bottom.
```js
function drawBlock(px, py, color, alpha) {
ctx.save();
ctx.globalAlpha = alpha;
const r = 4;
roundRect(px+1, py+1, CELL-2, CELL-2, r);
const g = ctx.createLinearGradient(px, py, px, py+CELL);
g.addColorStop(0, '#ffffff'); // no...
}
```
Better: fill base color, then top highlight:
```js
ctx.fillStyle = color;
roundRect(...); ctx.fill();
const g = ctx.createLinearGradient(px,py,px,py+CELL);
g.addColorStop(0,'rgba(255,255,255,0.45)');
g.addColorStop(0.35,'rgba(255,255,255,0.08)');
g.addColorStop(1,'rgba(0,0,0,0.35)');
roundRect(...); ctx.fillStyle=g; ctx.fill();
// inner border
ctx.strokeStyle='rgba(255,255,255,0.35)'; ctx.lineWidth=1; roundRect(px+1.5,py+1.5,CELL-3,CELL-3,r); ctx.stroke();
```
Ghost: stroke rounded rect with color alpha 0.35, no fill or faint fill.
Next piece preview: small canvas 120x120 or so, draw the piece centered.
Score display: update DOM elements.
Sound: WebAudio.
```js
let audioCtx = null;
function beep(freq, dur, type='square', vol=0.15) {
if (!soundOn) return;
if (!audioCtx) audioCtx = new (window.AudioContext||window.webkitAudioContext)();
const o = audioCtx.createOscillator();
const g = audioCtx.createGain();
o.type = type; o.frequency.value = freq;
g.gain.setValueAtTime(vol, audioCtx.currentTime);
g.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + dur);
o.connect(g); g.connect(audioCtx.destination);
o.start(); o.stop(audioCtx.currentTime + dur);
}
```
Sounds: move (short 200Hz), rotate (300Hz), lock (150Hz), clear (arpeggio), gameover (descending).
Sound toggle: M key and a button in aside. Button click toggles. Note: clicking the page starts the game from ready state — the sound button click would also trigger start. That's fine; but clicking sound button during ready would start game AND toggle sound. Acceptable. Actually to avoid weirdness, the sound button can stopPropagation on click. But the requirement says game starts when player clicks the page. Clicking the sound button is clicking the page... I'll stopPropagation on the button so it doesn't start the game; it just toggles sound. That's reasonable.
Overlay messages: div#overlay covering the board area (or whole wrap). Show/hide via class. Content set via JS.
Ready state: overlay shows title, controls, "Click or press any key to start".
Paused: overlay shows "PAUSED".
Game over: overlay shows "GAME OVER", score, lines, "Press Enter or click to restart".
Overlay should not block clicks — it's fine, clicks on overlay should start/restart. I'll put click handler on wrap/body.
Key handling:
```js
document.addEventListener('keydown', e => {
const k = e.key;
if (['ArrowLeft','ArrowRight','ArrowUp','ArrowDown',' '].includes(k)) e.preventDefault();
if (state === 'ready') { startGame(); return; }
if (state === 'gameover') {
if (k === 'Enter') startGame();
return;
}
if (k === 'p' || k === 'P') { togglePause(); return; }
if (k === 'm' || k === 'M') { toggleSound(); return; }
if (state !== 'playing') return;
switch(k) {
case 'ArrowLeft': move(-1); break;
case 'ArrowRight': move(1); break;
case 'ArrowUp': rotatePiece(); break;
case 'ArrowDown': softDrop = true; break;
case ' ': hardDrop(); break;
}
});
document.addEventListener('keyup', e => {
if (e.key === 'ArrowDown') softDrop = false;
});
```
Note: ' ' is space key value. Also 'Spacebar' legacy — use e.code === 'Space' maybe. I'll check both: `k === ' ' || e.code === 'Space'`.
Click handler:
```js
document.getElementById('wrap').addEventListener('click', () => {
if (state === 'ready') startGame();
else if (state === 'gameover') startGame();
});
```
Requirement: game starts when player clicks the page or presses any key. Good.
Pause: P toggles between playing and paused. When paused, overlay shows PAUSED.
Game over: when spawnPiece collides → state = 'gameover', show overlay with score.
Hard drop: compute drop distance, move, lock immediately.
Lock: write matrix to grid, check full rows. If rows full → start clear animation. Else spawn next.
Scoring: base = [0,100,300,500,800][n] * level. lines += n. level = 1 + floor(lines/10).
Interval: `Math.max(60, 800 * Math.pow(0.82, level - 1))`. At level 1: 800ms. Level 10: 800*0.82^9 ≈ 800*0.17 ≈ 137ms. Good.
Soft drop interval: 30ms.
Ghost: compute y position by simulating down.
Rotation with wall kicks:
```js
function rotatePiece() {
const m = rotate(current.matrix);
for (const [dx,dy] of [[0,0],[-1,0],[1,0],[0,-1],[-2,0],[2,0]]) {
if (!collide(m, current.x+dx, current.y+dy)) {
current.x+=dx; current.y+=dy; current.matrix=m; beep(...); return;
}
}
}
```
O piece: rotation no-op (matrix same).
Spawn:
```js
function spawnPiece() {
current = { type: nextType, matrix: SHAPES[nextType].matrix.map(r=>r.slice()), x: ..., y: 0 };
nextType = randomType();
// x: center
const w = current.matrix[0].length;
current.x = Math.floor((COLS - w)/2);
current.y = current.type === 'I' ? -1 : 0; // hmm
if (collide(current.matrix, current.x, current.y)) { gameOver(); }
}
```
For I piece, matrix is 4x4 with row 1 filled; spawn y=0 puts filled row at row 1. Fine. For O, 2x2 at x=4, y=0. For others 3x3 at x=3 or 4? (10-3)/2 = 3.5 → floor 3. Fine.
Actually for I piece, maybe spawn y=-1 so it slides in? Keep y=0, filled row at row 1. Fine.
Game over check: if collide at spawn → game over. Also if lock causes piece to be above grid? Standard: game over when new piece can't enter. That's what requirement says.
Clearing animation:
```js
function lockPiece() {
// write to grid
for cells: if y>=0 grid[y][x] = color/type
const full = [];
for (let y=0;yc)) full.push(y);
if (full.length) {
clearing = full; clearTimer = 0;
// score/lines applied after animation
} else {
spawnPiece();
}
}
```
In update: if clearing, clearTimer += dt; if clearTimer > 350 → apply clear: remove rows, unshift empty rows, spawn particles, score, lines, level, spawnPiece, clearing=null.
Particles spawn at clear time (when animation starts) or after? Spawn at animation start for visual feedback.
Render clearing rows: flash alpha = oscillating white overlay on those rows.
Also add a subtle background animation: floating gradient or stars? Keep it simple but polished: animated gradient background on body via CSS, and canvas has subtle vignette.
Score popups: floating "+300" text on clear. Nice touch — add floating texts array.
Let me also add a "level" display.
DOM structure:
```html
BLOCKFALL
a falling-block puzzle
```
Overlay positioned absolute over board-frame.
Overlay content for ready:
```
BLOCKFALL
Falling-block puzzle
← → move
↑ rotate
↓ soft drop
SPACE hard drop
P pause
M sound
Click or press any key to start
```
Game over overlay:
```
GAME OVER
Score: X
Lines: Y
Press Enter or click to restart
```
Paused overlay:
```
PAUSED
Press P to resume
```
Now, the "any key starts" — but the sound button click shouldn't start. Also, when ready, pressing M should start the game (any key). Fine.
One nuance: after game over, pressing Enter restarts. Also click restarts. Other keys ignored. Good.
Also prevent page scroll: preventDefault on arrows/space in keydown. Also body overflow hidden.
Next piece canvas: draw piece centered. Size 120x120, cell 24 for 4-wide pieces → 96px. Center: offset = (120 - w*24)/2.
Let me write drawNext():
```js
function drawNext() {
const nc = document.getElementById('next');
const nctx = nc.getContext('2d');
nctx.clearRect(0,0,nc.width,nc.height);
const m = SHAPES[nextType].matrix;
const cell = 22;
const w = m[0].length, h = m.length;
const ox = (nc.width - w*cell)/2, oy = (nc.height - h*cell)/2;
for (let y=0;y= 0) grid[gy][gx] = current.color;
}
beep(180, 0.06, 'square', 0.12);
const full = [];
for (let y=0;yc)) full.push(y);
if (full.length) {
clearing = full; clearTimer = 0;
spawnParticles(full);
beepClear();
} else {
spawnPiece();
}
}
```
Wait — if piece locks partially above grid (gy<0), those cells are lost. Game over condition is spawn collision, so fine.
Update:
```js
function update(dt) {
// particles always update
updateParticles(dt);
updateTexts(dt);
if (clearing) {
clearTimer += dt;
if (clearTimer >= 350) {
applyClear();
}
return;
}
dropTimer += dt;
const interval = softDrop ? 30 : dropInterval;
if (dropTimer >= interval) {
dropTimer = 0;
if (!collide(current.matrix, current.x, current.y+1)) {
current.y++;
} else {
lockPiece();
}
}
}
```
applyClear:
```js
function applyClear() {
const n = clearing.length;
// score
const base = [0,100,300,500,800][n] || 0;
const gained = base * level;
score += gained;
lines += n;
level = 1 + Math.floor(lines/10);
dropInterval = Math.max(60, 800 * Math.pow(0.82, level-1));
// remove rows
for (const y of clearing) {
grid.splice(y,1);
grid.unshift(new Array(COLS).fill(null));
}
// floating text
texts.push({x: COLS*CELL/2, y: clearing[0]*CELL, text: '+'+gained, life: 1, color:'#fde047'});
clearing = null;
updateHUD();
spawnPiece();
}
```
Note: splice with multiple rows — iterate clearing in descending order to avoid index issues. clearing is ascending; sort descending before splice.
spawnPiece:
```js
function spawnPiece() {
const type = nextType;
nextType = PIECE_KEYS[Math.floor(Math.random()*PIECE_KEYS.length)];
const shape = SHAPES[type];
const m = shape.matrix.map(r=>r.slice());
const w = m[0].length;
current = { type, matrix: m, x: Math.floor((COLS-w)/2), y: 0, color: shape.color };
if (type === 'I') current.y = -1; // hmm, filled row at index 1 → row 0. Actually with y=-1, filled row at row 0. Fine.
if (collide(current.matrix, current.x, current.y)) {
gameOver();
return;
}
drawNext();
}
```
Hmm, for I piece with y=-1: matrix row 1 filled → grid row 0. OK. For others y=0: T matrix row 0 has center filled → row 0. Fine.
Actually for I piece, maybe y=0 is fine too (filled row at row 1). Either way. I'll use y=0 for all, simpler. Actually with y=0, I piece's filled row is at row 1, leaving row 0 empty — fine.
gameOver:
```js
function gameOver() {
state = 'gameover';
showOverlay('gameover');
beepGameOver();
}
```
startGame:
```js
function startGame() {
grid = Array.from({length: ROWS}, () => new Array(COLS).fill(null));
score = 0; lines = 0; level = 1;
dropInterval = 800;
dropTimer = 0;
particles = []; texts = []; clearing = null;
softDrop = false;
nextType = randomType();
state = 'playing';
hideOverlay();
spawnPiece();
updateHUD();
}
```
Wait: spawnPiece uses nextType then picks new nextType. Initial nextType = randomType() then spawnPiece uses it and picks new. Good.
updateHUD: set score/lines/level text.
Render:
```js
function render() {
// bg
ctx.clearRect(0,0,canvas.width,canvas.height); // careful with dpr scaling — use CSS pixel dims
...
}
```
Since ctx.scale(dpr,dpr), drawing coordinates are CSS pixels: width = COLS*CELL = 280, height = 560.
Draw bg: fillRect with gradient. Grid lines: stroke lines every CELL with rgba(255,255,255,0.04).
Locked blocks: for each cell with color, drawBlockAt.
Ghost + current piece.
Clearing flash: for rows in clearing, overlay white with alpha = 0.3 + 0.3*sin(clearTimer/40).
Particles: draw as small rects/circles with alpha=life.
Texts: floating score text, alpha=life, rising.
Overlay handling:
```js
function showOverlay(kind) {
const ov = document.getElementById('overlay');
ov.classList.add('visible');
if (kind === 'ready') ov.innerHTML = `...`;
else if (kind === 'paused') ov.innerHTML = `...`;
else if (kind === 'gameover') ov.innerHTML = `...`;
}
```
Ready overlay content includes controls list.
Initial state: state='ready', showOverlay('ready'), drawNext with a placeholder? nextType undefined initially — drawNext would fail. Initialize nextType = randomType() at load and drawNext. Or guard. I'll init nextType at load and drawNext.
Also render loop runs from load, drawing empty grid behind overlay. Nice.
Pause toggle:
```js
function togglePause() {
if (state === 'playing') { state = 'paused'; showOverlay('paused'); softDrop = false; }
else if (state === 'paused') { state = 'playing'; hideOverlay(); }
}
```
Sound toggle:
```js
function toggleSound() {
soundOn = !soundOn;
document.getElementById('soundBtn').textContent = 'SOUND: ' + (soundOn ? 'ON' : 'OFF');
if (soundOn) beep(600, 0.08, 'sine', 0.15);
}
```
Sound button click: e.stopPropagation(); toggleSound();
But wait — the wrap click handler starts game from ready. The button is inside wrap. stopPropagation prevents that. Good.
Also the button click during gameover shouldn't restart — stopPropagation handles it.
Now the footer controls hint. And header title.
Colors/theme: deep indigo/navy background, neon cyan/magenta accents. Title with gradient text.
Let me write CSS:
```css
body {
background: #0b1020 radial-gradient(1200px 800px at 50% -10%, #1b2440 0%, #0b1020 60%);
display:flex; align-items:center; justify-content:center;
min-height:100vh; overflow:hidden;
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
color:#e5e7eb;
}
#wrap {
width:800px; height:640px;
background: linear-gradient(160deg, #141a2e 0%, #0d1224 100%);
border:1px solid rgba(120,140,255,0.18);
border-radius:18px;
box-shadow: 0 30px 80px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.06);
display:flex; flex-direction:column;
padding: 12px 16px 10px;
position:relative;
}
header { display:flex; align-items:baseline; justify-content:center; gap:14px; height:44px; }
h1 { font-size:26px; letter-spacing:6px; background:linear-gradient(90deg,#22d3ee,#c084fc,#fb923c); -webkit-background-clip:text; background-clip:text; color:transparent; font-weight:800; }
.tag { font-size:11px; letter-spacing:2px; color:#8b93b8; text-transform:uppercase; }
main { flex:1; display:flex; justify-content:center; gap:22px; min-height:0; }
#board-frame { position:relative; border-radius:12px; padding:6px; background:#080c18; border:1px solid rgba(120,140,255,0.22); box-shadow: inset 0 0 30px rgba(0,0,0,0.7); }
canvas#board { display:block; border-radius:6px; }
aside { width:230px; display:flex; flex-direction:column; gap:10px; }
.panel { background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08); border-radius:12px; padding:10px 12px; text-align:center; }
.label { font-size:10px; letter-spacing:3px; color:#8b93b8; }
.value { font-size:26px; font-weight:700; font-variant-numeric:tabular-nums; color:#f8fafc; }
#next { display:block; margin:6px auto 0; }
#soundBtn { ... }
footer { height:30px; display:flex; align-items:center; justify-content:center; font-size:11px; letter-spacing:1px; color:#8b93b8; }
#overlay { position:absolute; inset:6px; border-radius:6px; background:rgba(6,9,20,0.82); backdrop-filter: blur(3px); display:none; flex-direction:column; align-items:center; justify-content:center; text-align:center; z-index:5; }
#overlay.visible { display:flex; }
```
Overlay inset 6px to match board-frame padding.
Controls list styling: rows with key chips.
```css
.controls { list-style:none; margin:14px 0; display:flex; flex-direction:column; gap:6px; }
.controls li { display:flex; align-items:center; gap:10px; font-size:13px; color:#c7cbe0; }
.key { min-width:64px; padding:3px 8px; border-radius:6px; background:#1c2340; border:1px solid #39406b; border-bottom-width:3px; font-family:monospace; font-size:12px; color:#7dd3fc; }
```
Blink animation:
```css
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.25} }
.blink { animation: blink 1.2s infinite; }
```
Now, canvas sizing: CELL=28 → board 280x560. Board-frame padding 6 → 292x572. Header 44 + footer 30 + paddings 22 + gaps... total: 44 + 572 + 30 + 12(top pad) + 10(bottom pad) = 668 > 640. Too tall!
Recalculate. Wrap height 640, padding 12 top + 10 bottom = 22. Header 44. Footer 30. Main = 640 - 22 - 44 - 30 = 544. Board-frame must be ≤ 544. Board canvas 560 tall + 12 padding = 572 > 544. Too tall.
Reduce CELL to 26: board 260x520. Frame = 272x532. Fits in 544. Good. Aside width: 800 - 32 (wrap padding 16*2) - 272 - 22 (gap) = 474? No: 800 - 32 = 768; 768 - 272 - 22 = 474. Still wide. Hmm.
Let me reconsider layout: maybe put aside panels in a row? Or make board bigger and aside narrower. Alternative: CELL=28, board 280x560, frame 292x572. Header 40, footer 26, padding 20 → 572+40+26+20 = 658 > 640. Slightly over. Reduce header to 36, footer 24, padding 16 → 572+36+24+16 = 648. Still over. CELL=27: board 270x540, frame 282x552. 552+36+24+16 = 628 ≤ 640.
Aside: 800 - 32 - 282 - 22 = 464. Still wide. Hmm, 800 is just wide. Options: center main content with gap 24 and aside 240px; leftover space distributed as margins. That's fine aesthetically — dark background with centered content. Or add decorative side panels. Let me just center: main { justify-content:center; gap:24px; }. Content width = 282 + 24 + 240 = 546, centered in 768 → ~111px margins each side. Looks fine with the radial background.
Alternatively make aside 260 and board CELL=28... let me just go with CELL=27, aside 250.
Actually, let me reconsider: maybe make the board cell 28 and reduce rows? No, must be 20 rows.
OK final: CELL=27, board 270x540, frame 282x552, header 40, footer 26, wrap padding 12/10. Total: 12+40+552+26+10 = 640.
Aside: 250px wide, panels: SCORE, LINES, LEVEL, NEXT (canvas 120x120), sound button. Heights: 3 small panels ~64px each = 192, next panel ~170, button ~40, gaps 4*10=40 → ~442. Fits in 552. Good.
Next canvas: 120x120 with cell 22 → 4-wide piece = 88px. Fine.
Now write everything. Also add subtle scanline/vignette on board? Keep it clean.
One more polish: piece "landing" flash — when locking, brief white flash on the piece cells. Could add lockFlash timer. Simple: on lock, spawn small particles at piece cells. Nice.
Also add combo/level-up text? Keep floating text for score.
Let me also handle the case where the player presses arrow keys during 'ready' — startGame returns before processing, so no movement. Good.
Prevent default for space/arrows also on keyup to avoid scrolling (space scrolls on keyup? Actually scrolling happens on keydown default). preventDefault on keydown suffices.
Also prevent context menu? Not needed.
Write the code now.
```js
'use strict';
const COLS = 10, ROWS = 20, CELL = 27;
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = COLS*CELL*dpr;
canvas.height = ROWS*CELL*dpr;
canvas.style.width = COLS*CELL + 'px';
canvas.style.height = ROWS*CELL + 'px';
ctx.scale(dpr, dpr);
```
Wait — ctx.scale after setting width: setting canvas.width resets transform, so scale after. Good.
Shapes and colors as above.
State variables.
```js
let grid, current, nextType, score, lines, level, dropInterval, dropTimer, state, clearing, clearTimer, particles, texts, softDrop, soundOn = false, audioCtx = null;
```
Init:
```js
nextType = randomType();
grid = emptyGrid();
state = 'ready';
showOverlay('ready');
drawNext();
updateHUD();
requestAnimationFrame(loop);
```
updateHUD reads score/lines/level — initialize score=0 etc.
Loop:
```js
let last = performance.now();
function loop(t) {
const dt = Math.min(t - last, 100);
last = t;
if (state === 'playing') update(dt);
else updateAmbient(dt); // particles/texts still animate
render();
requestAnimationFrame(loop);
}
```
Hmm, particles should update even when paused? Freeze when paused is fine; but ready state has no particles. Let me update particles/texts in update() only when playing, and also in ready/gameover for lingering particles. Simpler: always update particles/texts in loop regardless of state (except paused? fine to keep animating). I'll update particles/texts always.
update(dt):
```js
function update(dt) {
if (clearing) {
clearTimer += dt;
if (clearTimer >= 350) applyClear();
return;
}
dropTimer += dt;
const interval = softDrop ? 30 : dropInterval;
if (dropTimer >= interval) {
dropTimer = 0;
if (!collide(current.matrix, current.x, current.y + 1)) current.y++;
else lockPiece();
}
}
```
collide:
```js
function collide(m, px, py) {
for (let y=0;y= COLS || gy >= ROWS) return true;
if (gy >= 0 && grid[gy][gx]) return true;
}
return false;
}
```
rotate:
```js
function rotateMatrix(m) {
const n = m.length;
const r = Array.from({length:n}, () => new Array(n).fill(0));
for (let y=0;y current.y) drawGhost(gy);
drawCurrent();
}
// clearing flash
if (clearing) {
const a = 0.35 + 0.35*Math.sin(clearTimer/40);
ctx.fillStyle = `rgba(255,255,255,${a})`;
for (const y of clearing) ctx.fillRect(0, y*CELL, W, CELL);
}
// particles
for (const p of particles) {
ctx.globalAlpha = Math.max(0, p.life);
ctx.fillStyle = p.color;
ctx.fillRect(p.x-2, p.y-2, 4, 4);
}
ctx.globalAlpha = 1;
// texts
for (const t of texts) {
ctx.globalAlpha = Math.max(0, t.life);
ctx.fillStyle = t.color;
ctx.font = 'bold 22px "Segoe UI", sans-serif';
ctx.textAlign = 'center';
ctx.fillText(t.text, t.x, t.y);
}
ctx.globalAlpha = 1;
}
```
drawGhost:
```js
function drawGhost(gy) {
for (let y=0;y p.life > 0);
for (const t of texts) { t.y -= 0.5*s; t.life -= dt/900; }
texts = texts.filter(t => t.life > 0);
}
```
spawnParticles:
```js
function spawnParticles(rows) {
for (const y of rows) {
for (let x=0;xb-a);
const n = rows.length;
const base = [0,100,300,500,800][n] || 0;
const gained = base * level;
score += gained;
lines += n;
level = 1 + Math.floor(lines/10);
dropInterval = Math.max(60, 800 * Math.pow(0.82, level-1));
for (const y of rows) {
grid.splice(y,1);
grid.unshift(new Array(COLS).fill(null));
}
texts.push({ x: COLS*CELL/2, y: Math.max(30, rows[rows.length-1]*CELL), text: '+'+gained, life: 1, color: '#fde047' });
clearing = null;
updateHUD();
spawnPiece();
}
```
Wait, rows sorted descending; rows[rows.length-1] is the smallest row index (topmost). Text y at topmost row. Fine.
spawnPiece:
```js
function spawnPiece() {
const type = nextType;
nextType = randomType();
const shape = SHAPES[type];
const m = shape.matrix.map(r => r.slice());
const w = m[0].length;
current = { type, matrix: m, x: Math.floor((COLS - w)/2), y: 0, color: shape.color };
if (collide(current.matrix, current.x, current.y)) {
current = null;
gameOver();
return;
}
drawNext();
}
```
Hmm — for I piece, matrix 4x4, w=4, x=3. Filled row at index 1 → grid row 1. OK.
gameOver sets state and overlay. current=null so render skips.
updateHUD:
```js
function updateHUD() {
document.getElementById('score').textContent = score;
document.getElementById('lines').textContent = lines;
document.getElementById('level').textContent = level;
}
```
drawNext:
```js
function drawNext() {
const nc = document.getElementById('next');
const nctx = nc.getContext('2d');
nctx.clearRect(0,0,nc.width,nc.height);
const shape = SHAPES[nextType];
const m = shape.matrix;
const cell = 20;
const w = m[0].length, h = m.length;
const ox = (nc.width - w*cell)/2, oy = (nc.height - h*cell)/2;
for (let y=0;y beep(659, 0.09, 'square', 0.12), 70);
setTimeout(() => beep(784, 0.14, 'square', 0.12), 140);
}
function beepGameOver() {
if (!soundOn) return;
beep(392, 0.15, 'sawtooth', 0.12);
setTimeout(() => beep(311, 0.15, 'sawtooth', 0.12), 160);
setTimeout(() => beep(233, 0.3, 'sawtooth', 0.12), 320);
}
```
Overlay HTML:
ready:
```js
ov.innerHTML = `
BLOCKFALL
A falling-block puzzle
← →Move
↑Rotate
↓Soft drop
SPACEHard drop
PPause
MSound on/off
Click or press any key to start
`;
```
paused:
```js
ov.innerHTML = `
PAUSED
Press P to resume
`;
```
gameover:
```js
ov.innerHTML = `
GAME OVER
Score ${score} · Lines ${lines} · Level ${level}
Press Enter or click to restart
`;
```
hideOverlay: ov.classList.remove('visible').
Keydown handler — also handle 'Enter' in ready state: any key starts, so Enter starts too. Good.
One catch: keydown repeat for ArrowUp rotates repeatedly — acceptable.
Also prevent default for 'ArrowDown' etc. Also prevent default for space to avoid button activation when sound button focused — after clicking sound button, it has focus; pressing space would trigger button click AND our handler. preventDefault on keydown prevents button activation via space? Button activation via space happens on keyup/keydown default — preventDefault on keydown prevents scrolling and also prevents the button's space activation? Actually button space activation: keydown default scrolls? No — for buttons, space keydown default is... the button activates on keyup for space (and keydown for Enter). preventDefault on keydown prevents the "click" on keyup? Hmm. To be safe, blur the button after click: `this.blur()`. Good.
Also after game over, Enter keydown → startGame. But if sound button focused, Enter would also click it. Blur after click handles it.
Click handler on wrap:
```js
document.getElementById('wrap').addEventListener('click', () => {
if (state === 'ready' || state === 'gameover') startGame();
});
```
Sound button:
```js
document.getElementById('soundBtn').addEventListener('click', (e) => {
e.stopPropagation();
toggleSound();
e.currentTarget.blur();
});
```
Now the footer: "← → move · ↑ rotate · ↓ soft drop · SPACE hard drop · P pause · M sound".
Header: title "BLOCKFALL" + tag "falling-block puzzle".
Check requirement: "Do not use the word 'Tetris' anywhere in the file." — ensure no occurrence. Title "Blockfall" fine.
Also "Show the score, the number of cleared lines and the next piece." — done.
"Pieces fall on their own and speed up as the player clears more lines." — level from lines, interval decreases. Good.
Now, one more consideration: the overlay covers the board; clicks on overlay bubble to wrap → start. Good.
Pause during clearing animation: P toggles pause; update stops; clearTimer frozen. Fine.
Edge: hard drop during clearing — state is 'playing' and clearing non-null; hardDrop would lockPiece while clearing... Guard: in keydown, if clearing, ignore gameplay keys. Add `if (clearing) return;` after pause/sound handling. Also ignore move/rotate/harddrop while clearing.
Also softDrop keydown sets softDrop=true; if clearing, ignore.
Let me also make sure the game starts on any key including P — pressing P in ready starts game (any key). Fine.
Now the visual polish: add a subtle animated glow behind the board? CSS animation on board-frame box-shadow. Keep subtle.
Also add a "danger" indicator: when current piece is near top (y < 2), maybe flash red border? Skip — keep scope reasonable but polished.
Let me also add a small "next" label and maybe show "hold"? No hold — keep to requirements.
Write final HTML. Also ensure the page fits 800x640 exactly: wrap fixed 800x640, body overflow hidden, centered.
Font: use system stack. Numbers with tabular-nums.
Let me write it all out now, carefully checking syntax.
One more detail: `ctx.scale(dpr,dpr)` — after canvas.width set. Then all drawing in CSS pixels. Good.
For the next canvas, no dpr scaling — fine, it's small.
Also, initial render before start: grid empty, current null → render draws bg + grid. Overlay covers it. Good.
Let me also double check the clearing flash render: clearing rows drawn over locked blocks — but locked blocks in those rows are still drawn (grid unchanged until applyClear). Flash overlay on top. Good.
Particles drawn after flash — fine.
Texts: drawn with font set each time.
Now, the keydown handler:
```js
document.addEventListener('keydown', (e) => {
const k = e.key;
const isSpace = (k === ' ' || k === 'Spacebar' || e.code === 'Space');
if (k === 'ArrowLeft' || k === 'ArrowRight' || k === 'ArrowUp' || k === 'ArrowDown' || isSpace) {
e.preventDefault();
}
if (state === 'ready') { startGame(); return; }
if (state === 'gameover') {
if (k === 'Enter') startGame();
return;
}
if (k === 'p' || k === 'P') { togglePause(); return; }
if (k === 'm' || k === 'M') { toggleSound(); return; }
if (state !== 'playing' || clearing) return;
if (k === 'ArrowLeft') move(-1);
else if (k === 'ArrowRight') move(1);
else if (k === 'ArrowUp') rotatePiece();
else if (k === 'ArrowDown') softDrop = true;
else if (isSpace) hardDrop();
});
```
Note: pressing P in ready starts game — fine.
keyup:
```js
document.addEventListener('keyup', (e) => {
if (e.key === 'ArrowDown') softDrop = false;
});
```
Also on blur (window loses focus), reset softDrop and auto-pause? Nice touch: window blur → if playing, pause. Add it.
```js
window.addEventListener('blur', () => {
if (state === 'playing') togglePause();
softDrop = false;
});
```
Good.
Now write the final file. Also add meta viewport. Title "Blockfall".
CSS details for overlay controls list: two-column? Single column list of 6 items is tall (~200px) — fits in 540px board. Fine.
Let me write it.
Also, the footer hint uses arrows characters ← → ↑ ↓ — fine, not emoji.
Double-check no "Tetris" string anywhere. Title: "Blockfall". OK.
Let me also consider: "The game starts when the player clicks the page or presses any key." — clicking anywhere on the page (body), not just wrap. Add click listener on document/body instead of wrap. But then sound button stopPropagation still works. Use document.addEventListener('click', ...). Good.
Final check on heights: wrap padding 12 top, 10 bottom. Header 40. Main flex:1. Footer 26. Board frame: canvas 540 + padding 12 = 552. 12+40+552+26+10 = 640. ✓. Main height = 640-22-40-26 = 552. ✓.
Aside width 250, gap 22: total content = 282+22+250 = 554, centered in 768 → margins ~107. Fine.
Write it.
[answer]
Blockfall