[reasoning, returned separately by llama-server]
Let me build a polished falling-block puzzle game in a single HTML file.
Key features:
- 10x20 grid, 7 standard tetrominoes
- Gravity with speed increase
- Arrow keys, space drop, P pause
- Prevent page scroll
- Wall/floor/collision checks
- Line clears with animation
- Score, lines, next piece
- Start screen with controls
- Game over screen with restart
- All inline, no external resources
- 800x640 viewport
Let me design visually impressive: neon glow, particle effects, screen shake, line clear flash, combo scoring, ghost piece, hold piece maybe (not required but nice). Keep it self-contained.
Let me write the code.
Canvas-based rendering for the board, plus HTML overlay for messages. Actually let's do everything on canvas for full control, with HTML overlay divs for text. Hmm, mixing is fine. Let me use a canvas for the whole game area and draw text on canvas. But requirement says "Show every message on the page itself" — canvas text is on the page. That's fine.
Actually, let me use a canvas for the board and HTML for the start/gameover overlay. Simpler: one canvas covering the whole 800x640, draw everything.
Let me plan the layout:
- Canvas 800x640
- Board area: 10 cols x 20 rows. Cell size 30px → 300x600. That's too tall for 640 with HUD. Let's use cell size 28 → 280x560. Board at x=250, y=40. Then HUD on right side (x=560..800) showing score, lines, level, next piece.
- Actually 800 wide: board 280 wide starting at x=250 leaves 250 on right for HUD. Good.
- Height 640: board 560 tall starting at y=40 leaves 40 at bottom. Fine.
Hmm, but maybe make board bigger: cell 30 → 300x600, y=20. Then HUD right side. Let's do cell = 30, board x = 250, y = 20, size 300x600. Bottom margin 20. Good.
Actually let's center: total height 640, board 600, so y=20. Good.
Next piece preview: draw in a small canvas area on the right, 4x4 cells of 24px = 96x96.
Let me write the tetromino definitions with rotation states. I'll use matrices.
Standard pieces:
I: [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
J: [[1,0,0],[1,1,1],[0,0,0]]
L: [[0,0,1],[1,1,1],[0,0,0]]
O: [[1,1],[1,1]]
S: [[0,1,1],[1,1,0],[0,0,0]]
T: [[0,1,0],[1,1,1],[0,0,0]]
Z: [[1,1,0],[0,1,1],[0,0,0]]
Colors: I cyan, J blue, L orange, O yellow, S green, T purple, Z red.
Rotation: rotate matrix clockwise.
Wall kicks: simple — try offsets [0,0], [-1,0], [1,0], [-2,0], [2,0], [0,-1].
Gravity: drop interval based on level. Level = floor(lines/10)+1. Interval = max(80, 1000 - (level-1)*80) or use a table. Let's do: interval = Math.max(70, 800 * Math.pow(0.85, level-1)).
Scoring: single 100, double 300, triple 500, tetris 800, times level. Soft drop +1 per cell, hard drop +2 per cell.
Lock delay: small, maybe 500ms. Keep simple but add a bit.
Ghost piece: draw faded outline at drop position.
Animations:
- Line clear: flash white then shrink/slide out.
- Piece lock: brief flash.
- Particle effects on line clear.
- Screen shake on hard drop / line clear.
- Combo counter.
Let me implement a simple particle system.
Rendering: draw board background with grid, blocks with 3D bevel effect (lighter top-left, darker bottom-right), glow.
Let me write it.
Structure:
```html
Block Cascade
```
Wait — the page must fit in 800x640 frame. Canvas 800x640 plus body margins could overflow. Use body margin 0, overflow hidden, background black.
Let me write the JS.
```js
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const W = 800, H = 640;
const COLS = 10, ROWS = 20;
const CELL = 30;
const BOARD_X = 250, BOARD_Y = 20;
const BOARD_W = COLS*CELL, BOARD_H = ROWS*CELL;
```
Hmm, BOARD_Y=20, BOARD_H=600 → bottom at 620, 20px margin. Good.
HUD on right: x from 560 to 800.
Let me define pieces:
```js
const SHAPES = {
I: [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]],
J: [[1,0,0],[1,1,1],[0,0,0]],
L: [[0,0,1],[1,1,1],[0,0,0]],
O: [[1,1],[1,1]],
S: [[0,1,1],[1,1,0],[0,0,0]],
T: [[0,1,0],[1,1,1],[0,0,0]],
Z: [[1,1,0],[0,1,1],[0,0,0]]
};
const COLORS = { I:'#00e5ff', J:'#3b6bff', L:'#ff9f1c', O:'#ffd93b', S:'#3bff7a', T:'#b45cff', Z:'#ff3b5c' };
```
For I piece, spawn position: matrix 4x4 with row 1 filled. Spawn at row 0 → the piece appears at row 1. Fine.
Actually for standard, spawn I at columns 3-6. With 4x4 matrix at x=3, cells at columns 3,4,5,6. Good.
J/L/S/T/Z are 3x3, spawn at x=3 (columns 3,4,5). O is 2x2 at x=4.
Let me define spawn x per piece: I:3, J:3, L:3, O:4, S:3, T:3, Z:3.
Spawn y: -1 for 3x3 pieces (so the top empty row is above the board), 0 for I (row 0 empty, row 1 filled → appears at row 1)... hmm. Let's just use y=0 for all and let the matrices handle it. For 3x3 pieces with top row filled (J: row0 = [1,0,0]), at y=0 the piece occupies row 0. That's fine, visible.
Actually for J the top row has a block, so it appears at row 0. Fine.
For I, matrix row 1 filled, at y=0 → appears at row 1. Fine.
Let me just use y=0 for all.
Hmm, but for a nicer look, spawn at y=-1 so pieces slide in. Let's keep y=0 for simplicity and correctness.
Actually, let's do y = -1 for 3x3 and O, and y = -1 for I too (so I appears at row 0). Hmm, with y=-1, I's row 1 → board row 0. Good. And 3x3 pieces' row 0 → board row -1, which is off-screen. That would hide part of the piece. Not good.
Let's just use y=0. Simple.
Now the game state:
```js
let board, current, nextPiece, score, lines, level, dropInterval, dropCounter, state, ...
```
state: 'start' | 'playing' | 'paused' | 'gameover'
Bag randomizer for fairness.
Let me write functions:
- createBoard()
- randomPiece()
- rotate(matrix, dir)
- collide(board, piece)
- merge()
- clearLines()
- drop()
- lockPiece()
- update()
- draw()
Input handling with keydown, preventDefault for arrows and space.
Let me write the drawing with nice effects.
drawBlock(x, y, color, alpha, size, glow):
- fillRect with gradient
- inner highlight
- shadow glow
Let me write a helper:
```js
function drawCell(px, py, color, alpha, size, glowColor) {
ctx.globalAlpha = alpha;
// glow
if (glowColor) {
ctx.shadowColor = glowColor;
ctx.shadowBlur = 12;
}
// body gradient
const g = ctx.createLinearGradient(px, py, px+size, py+size);
g.addColorStop(0, lighten(color, 0.35));
g.addColorStop(0.5, color);
g.addColorStop(1, darken(color, 0.35));
ctx.fillStyle = g;
roundRect(px+1, py+1, size-2, size-2, 4);
ctx.fill();
// top highlight
...
ctx.shadowBlur = 0;
ctx.globalAlpha = 1;
}
```
Need lighten/darken helpers using hex parsing.
Let me write:
```js
function hexToRgb(hex){ const n = parseInt(hex.slice(1),16); return [n>>16&255, n>>8&255, n&255]; }
function shade(hex, amt){ // amt -1..1
let r,g,b; [r,g,b]=hexToRgb(hex);
if(amt>0){ r=Math.min(255,r+ (255-r)*amt); ... }
...
}
```
Simpler: mix with white or black.
```js
function mix(hex, target, t) {
const [r,g,b] = hexToRgb(hex);
const tr = target===0?0:255;
...
}
```
Let me just do:
```js
function lighten(hex, t){ return mix(hex, [255,255,255], t); }
function darken(hex, t){ return mix(hex, [0,0,0], t); }
function mix(hex, c, t){
const [r,g,b] = hexToRgb(hex);
const nr = Math.round(r + (c[0]-r)*t);
...
return `rgb(${nr},${ng},${nb})`;
}
```
Good.
Now the main render loop with requestAnimationFrame and delta time.
Let me handle the drop timer with accumulated time.
Game loop:
```js
let lastTime = 0;
function loop(t){
const dt = t - lastTime; lastTime = t;
if (state === 'playing') {
dropCounter += dt;
if (dropCounter > dropInterval) { softDropStep(); }
}
render();
requestAnimationFrame(loop);
}
```
Actually for animations (line clear), I'll use a separate animation queue. Let me keep it simpler: when lines clear, set a `clearing` state with a timer, and during that time the piece is locked and no new piece spawns until animation done.
Let me implement:
```js
let clearAnim = null; // {t: 0, duration: 400, rows: [...]}
```
During clearing, update t and render the rows shrinking.
Simpler approach: on line clear, capture the rows to clear, then animate them by scaling down over 300ms, then remove and shift. Let's do that.
Actually let me do a two-phase: flash (white overlay on those rows) for 100ms, then shrink out for 200ms, then apply.
I'll implement with a `clearProgress` value 0..1.
Let me structure:
```js
function lockPiece(){
merge into board (with lock flash)
const full = findFullRows();
if (full.length) {
state = 'clearing';
clearRows = full;
clearT = 0;
// particles
} else {
spawn();
}
}
```
In update, if state==='clearing', advance clearT; when done, remove rows, shift, spawn new piece, state='playing'.
During 'clearing', the current piece is null.
Let me write render to handle each state.
For the start screen: draw title, controls, "Click or press any key to start".
For game over: draw "GAME OVER", score, "Press Enter or click to restart".
Pause: overlay "PAUSED".
Let me now write the code carefully.
```js
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const W = 800, H = 640;
const COLS = 10, ROWS = 20;
const CELL = 30;
const BOARD_X = 250, BOARD_Y = 20;
const BOARD_W = COLS * CELL; // 300
const BOARD_H = ROWS * CELL; // 600
```
Board occupies x 250-550, y 20-620.
HUD right panel: x 570-790.
Next piece preview: at x 600, y 120, cell 22, 4x4 → 88x88.
Let me lay out HUD:
- "SCORE" label at (600, 60), value at (600, 90) big.
- "LINES" at (600, 150), value at (600, 180).
- "LEVEL" at (600, 220), value at (600, 250).
- Next piece box at (620, 300) size 90x90.
- Controls hint at bottom right.
Hmm, let me reconsider. Right panel from x=570 to 800, width 230.
Let me place:
- Score panel: rounded rect at (575, 40, 215, 110)
- Lines panel: (575, 165, 215, 90)
- Level panel: (575, 270, 215, 90)
- Next panel: (575, 375, 215, 200) with "NEXT" label and preview
- Bottom hint text at y=600
That works.
Actually the board is 300 wide starting at 250, ending at 550. Right panel starts at 575. Good.
Let me write the drawing code.
Background: dark gradient with subtle grid.
Let me write it all out now.
```js
// ---------- Utilities ----------
function hexToRgb(hex){
const n = parseInt(hex.slice(1), 16);
return [(n>>16)&255, (n>>8)&255, n&255];
}
function mixHex(hex, c, t){
const [r,g,b] = hexToRgb(hex);
const nr = Math.round(r + (c[0]-r)*t);
const ng = Math.round(g + (c[1]-g)*t);
const nb = Math.round(b + (c[2]-b)*t);
return `rgb(${nr},${ng},${nb})`;
}
const lighten = (h,t) => mixHex(h,[255,255,255],t);
const darken = (h,t) => mixHex(h,[0,0,0],t);
```
roundRect helper:
```js
function roundRect(x,y,w,h,r){
ctx.beginPath();
ctx.moveTo(x+r,y);
ctx.arcTo(x+w,y,x+w,y+h,r);
ctx.arcTo(x+w,y+h,x,y+h,r);
ctx.arcTo(x,y+h,x,y,r);
ctx.arcTo(x,y,x+w,y,r);
ctx.closePath();
}
```
Board drawing:
```js
function drawBoardBackground(){
// playfield background
const g = ctx.createLinearGradient(0, BOARD_Y, 0, BOARD_Y+BOARD_H);
g.addColorStop(0, '#0a0e1a');
g.addColorStop(1, '#05070f');
ctx.fillStyle = g;
roundRect(BOARD_X-6, BOARD_Y-6, BOARD_W+12, BOARD_H+12, 10);
ctx.fill();
// inner
ctx.fillStyle = '#0d1424';
ctx.fillRect(BOARD_X, BOARD_Y, BOARD_W, BOARD_H);
// grid lines
ctx.strokeStyle = 'rgba(80,120,200,0.10)';
ctx.lineWidth = 1;
for (let x=1;x0;i--){
const j = Math.floor(Math.random()*(i+1));
[bag[i],bag[j]]=[bag[j],bag[i]];
}
}
return bag.pop();
}
```
State:
```js
let board, cur, nextType, score, lines, level, dropInterval, dropCounter, state, clearState, particles, shake, combo, gameOverScore;
```
Let me write reset():
```js
function reset(){
board = createBoard();
bag = [];
score = 0; lines = 0; level = 1;
dropInterval = 800;
dropCounter = 0;
particles = [];
shake = 0;
combo = 0;
nextType = nextFromBag();
spawn();
state = 'playing';
}
```
spawn():
```js
function spawn(){
const type = nextType;
nextType = nextFromBag();
const matrix = SHAPES[type].map(r=>r.slice());
cur = {
type,
matrix,
x: SPAWN_X[type],
y: 0,
rot: 0
};
if (collide(cur.matrix, cur.x, cur.y)){
// game over
state = 'gameover';
}
}
```
Hmm, but for I piece the matrix is 4x4 with the filled row at index 1, so at y=0 it appears at row 1. For 3x3 pieces at y=0 the top row is at row 0. That's fine.
Actually wait — for the I piece, spawning at y=0 means the visible blocks are at row 1. That's fine.
collide:
```js
function collide(matrix, px, py){
for (let y=0;y=COLS || by>=ROWS) return true;
if (by>=0 && board[by][bx]) return true;
}
}
return false;
}
```
Note: by<0 allowed (above board).
Rotation:
```js
function rotateMatrix(m, dir){
const n = m.length;
const res = m.map((row,i)=>row.map((_,j)=> m[n-1-j][i]));
// for clockwise
return res;
}
```
Let me verify: clockwise rotation: new[i][j] = old[n-1-j][i]. Yes.
For counter-clockwise: new[i][j] = old[j][n-1-i].
I'll only support clockwise (up arrow rotates). Maybe also allow Z for counter-clockwise as a bonus. Let's add it.
Wall kick offsets:
```js
const KICKS = [[0,0],[-1,0],[1,0],[-2,0],[2,0],[0,-1]];
```
Try each.
Move:
```js
function move(dx, dy){
if (!cur) return;
if (!collide(cur.matrix, cur.x+dx, cur.y+dy)) { cur.x += dx; cur.y += dy; }
}
```
Soft drop: move down, if collide, lock.
Hard drop: while !collide down, y++, score += 2.
Lock:
```js
function lockPiece(){
// merge
for each cell: if by>=0 board[by][bx] = cur.type;
// flash animation
...
const full = getFullRows();
if (full.length){
state = 'clearing';
clearRows = full;
clearT = 0;
clearDur = 420;
// particles at row centers
for (const r of full){
for (let i=0;i= clearDur){
// remove rows
for (let i=clearRows.length-1;i>=0;i--){
board.splice(clearRows[i],1);
board.unshift(createRow());
}
// scoring
const n = clearRows.length;
const table = [0,100,300,500,800];
score += table[n] * level;
lines += n;
level = Math.floor(lines/10)+1;
dropInterval = Math.max(70, 800*Math.pow(0.82, level-1));
dropCounter = 0;
spawn();
state = 'playing';
}
}
```
Wait, `board.splice` then `unshift` — order matters. If I splice from highest index first, then unshift, that works. Actually simpler: build a new board.
```js
const newBoard = [];
for (let y=0;y=0.35: rows above have moved down by (t-0.35)/0.65 * CELL.
Then at t=1, finalize.
Let me implement render for clearing:
```js
function renderClearing(t){
const p = t; // 0..1
// draw board cells
for (let y=0;y 0.35 ? (p-0.35)/0.65 : 0;
offY = -slide * CELL;
}
drawCellAt(x, y, board[y][x], alpha, offY);
}
}
}
```
Hmm, this is getting complex. Let me simplify: I'll just do the flash and then instantly remove rows with a particle burst. The visual impact is mostly from the flash + particles + shake. That's acceptable and looks good.
Actually, a slide-down is quite visible and satisfying. Let me do a simplified version: during clearing, draw the board with rows above the cleared rows offset downward by an animated amount.
Let me write:
```js
function drawBoardCells(offsetFn){
for (let y=0;y 0){
const s = shake;
ctx.translate((Math.random()-0.5)*s, (Math.random()-0.5)*s);
}
... draw everything ...
ctx.restore();
```
But then the background edges might show. Let me draw the background first without shake, then shake the rest. Or just fill the whole canvas with black first.
Let me do: fill background, then save/translate, draw game, restore.
OK.
Now input handling.
```js
document.addEventListener('keydown', e => {
const k = e.key;
if (['ArrowLeft','ArrowRight','ArrowUp','ArrowDown',' '].includes(k)) e.preventDefault();
if (e.key === ' ' ) e.preventDefault();
if (state === 'start'){
startGame();
return;
}
if (state === 'gameover'){
if (k === 'Enter' || k === ' ') { reset(); }
return;
}
if (state === 'paused'){
if (k === 'p' || k === 'P') state = 'playing';
return;
}
if (state === 'clearing') return;
if (state === 'playing'){
switch(k){
case 'ArrowLeft': move(-1,0); break;
case 'ArrowRight': move(1,0); break;
case 'ArrowDown': softDrop(); break;
case 'ArrowUp': rotate(1); break;
case 'z': case 'Z': rotate(-1); break;
case ' ': hardDrop(); break;
case 'p': case 'P': state='paused'; break;
}
}
});
```
Wait, for the start screen, "presses any key" starts the game. But if the key is Enter, it starts. Fine.
For game over, Enter or click restarts.
Click handler:
```js
canvas.addEventListener('click', () => {
if (state === 'start') startGame();
else if (state === 'gameover') reset();
});
```
Also need to handle the case where the game is paused and the user clicks — maybe resume. Let's not.
Also, prevent scrolling on space: `e.preventDefault()` for space. And for arrows.
Also add `window.addEventListener('keydown', ...)` to catch keys anywhere.
Now, the "start" state: the game starts when the player clicks or presses any key. So initially state='start'.
Let me also add a subtle animated background on the start screen (moving particles / grid).
Let me add a starfield animation for the start screen.
OK, let me write the whole thing now.
One more thing: the drop interval should speed up as lines clear. I have that.
Also, "Pieces fall on their own and speed up as the player clears more lines." ✓.
Let me also add a level display.
Let me write the final code.
```html
Block Cascade
```
Now the JS. Let me write it carefully.
```js
(function(){
'use strict';
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const W = 800, H = 640;
// ---------- Constants ----------
const COLS = 10, ROWS = 20;
const CELL = 30;
const BOARD_X = 250, BOARD_Y = 20;
const BOARD_W = COLS * CELL;
const BOARD_H = ROWS * CELL;
const SHAPES = {
I: [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]],
J: [[1,0,0],[1,1,1],[0,0,0]],
L: [[0,0,1],[1,1,1],[0,0,0]],
O: [[1,1],[1,1]],
S: [[0,1,1],[1,1,0],[0,0,0]],
T: [[0,1,0],[1,1,1],[0,0,0]],
Z: [[1,1,0],[0,1,1],[0,0,0]]
};
const COLORS = {
I: '#22d3ee', J: '#3b82f6', L: '#f59e0b',
O: '#facc15', S: '#22c55e', T: '#a855f7', Z: '#ef4444'
};
const SPAWN_X = { I:3, J:3, L:3, O:4, S:3, T:3, Z:3 };
const KICKS = [[0,0],[-1,0],[1,0],[-2,0],[2,0],[0,-1]];
const SCORE_TABLE = [0, 100, 300, 500, 800];
```
Utilities...
Let me write everything out.
For the particles:
```js
function makeParticle(x, y, color){
const angle = Math.random()*Math.PI*2;
const speed = 1 + Math.random()*3;
return {
x, y,
vx: Math.cos(angle)*speed,
vy: Math.sin(angle)*speed - 1,
life: 1,
decay: 0.02 + Math.random()*0.03,
size: 2 + Math.random()*3,
color
};
}
```
Update particles: x += vx, y += vy, vy += 0.15, life -= decay.
Draw with alpha = life.
Cap particles at ~400.
Now let me write the full render.
Background: I'll draw a radial gradient plus a subtle grid pattern.
```js
function drawBackground(){
const g = ctx.createRadialGradient(W/2, H/2, 100, W/2, H/2, 700);
g.addColorStop(0, '#0b1220');
g.addColorStop(1, '#03050a');
ctx.fillStyle = g;
ctx.fillRect(0,0,W,H);
// subtle grid
ctx.strokeStyle = 'rgba(60,90,140,0.06)';
ctx.lineWidth = 1;
ctx.beginPath();
for (let x=0;xr.slice());
cur = { type, matrix, x: SPAWN_X[type], y: 0 };
if (collide(cur.matrix, cur.x, cur.y)){
state = 'gameover';
cur = null;
}
}
```
But wait — for the I piece, the matrix at y=0 has the filled row at index 1, so it occupies board row 1. If the board rows 0 and 1 are full, it collides. Good.
Hmm, but actually for the I piece, the standard spawn is at row 0 with the piece visible at row 0. Let me adjust the I matrix so the filled row is at index 0? No, then rotation would be weird.
Actually, let me shift the I piece up by 1: use y = -1 for I. Then the filled row (index 1) is at board row 0. And for 3x3 pieces, y=0 puts the top row at board row 0.
Hmm, but for J, the top row is [1,0,0] which is at board row 0. For S, top row is [0,1,1] at board row 0. For Z, [1,1,0] at row 0. For T, [0,1,0] at row 0. For L, [0,0,1] at row 0.
So all pieces appear starting at row 0. For I, with y=-1, the filled row is at board row 0.
Let me set SPAWN_Y = { I: -1, others: 0 }.
Actually, simpler: just use y=0 for all and accept that I appears at row 1. It's fine visually. But for consistency, let me use y=-1 for I.
Hmm, but then the collision check at spawn: if board row 0 is full, the I piece collides. Good.
Let me define SPAWN_Y = { I: -1, J: 0, L: 0, O: 0, S: 0, T: 0, Z: 0 }.
Wait, for O (2x2), at y=0 it occupies rows 0-1. Fine.
OK.
Now, one issue: when the piece is at y=-1 for I, the draw function needs to skip cells with by<0. Let me handle that.
Let me write drawCurrent:
```js
function drawCurrent(){
if (!cur) return;
const color = COLORS[cur.type];
for (let y=0;y ctx.measureText(ch).width);
total = widths.reduce((a,b)=>a+b,0) + spacing*(chars.length-1);
let cx = x - total/2;
chars.forEach((ch,i)=>{
ctx.fillText(ch, cx, y);
cx += widths[i] + spacing;
});
}
```
Good.
Now let me write everything.
For the game over screen, I want it to look impressive. Let me add a flashing effect and particles.
Let me write the final code.
Also, I should make sure the game doesn't break if the user presses keys rapidly.
Let me write it.
Final code:
I'll write it now in full.
One more detail: the drop counter should reset when the piece moves down (soft drop) or locks.
Also, when the player soft drops, the drop counter should reset so gravity doesn't immediately trigger.
Let me handle: in softDrop, after moving down, dropCounter = 0.
In hardDrop, dropCounter = 0.
In lock, dropCounter = 0.
OK.
Let me write.
Also for the "clearing" state, I need to make sure the drop timer doesn't run.
Let me write the update:
```js
function update(dt){
if (shake > 0) shake = Math.max(0, shake - dt*3);
// particles
for (let i = particles.length-1; i>=0; i--){
const p = particles[i];
p.x += p.vx; p.y += p.vy; p.vy += 0.18; p.life -= p.decay;
if (p.life <= 0) particles.splice(i,1);
}
if (state === 'playing'){
dropCounter += dt;
if (dropCounter >= dropInterval){
dropCounter = 0;
if (!collide(cur.matrix, cur.x, cur.y+1)){
cur.y++;
} else {
lockPiece();
}
}
} else if (state === 'clearing'){
clearT += dt;
if (clearT >= clearDur){
finalizeClear();
}
}
}
```
Wait, `lockPiece` might set state to 'clearing' or call spawn. If spawn sets state to 'gameover', that's handled.
But there's an issue: after lockPiece, `cur` might be null during clearing. The update checks state === 'playing' first, so it's fine.
Let me write finalizeClear:
```js
function finalizeClear(){
// remove rows
const remove = new Set(clearRows);
const newBoard = [];
for (let y=0;y 0.4 ? (p - 0.4) / 0.6 : 0;
const remove = new Set(clearRows);
const minY = Math.min(...clearRows);
for (let y=0;y 0.01){
ctx.save();
ctx.globalAlpha = flash * 0.9;
ctx.fillStyle = '#ffffff';
roundRect(BOARD_X + x*CELL + 2, BOARD_Y + y*CELL + 2, CELL-4, CELL-4, 4);
ctx.fill();
ctx.restore();
}
} else if (y < minY){
offY = -slide * CELL;
drawCell(x, y, t, 1, false, offY);
} else {
drawCell(x, y, t, 1, false, 0);
}
}
}
}
```
Hmm, the flash overlay with white — I need to make sure the alpha is applied correctly. Let me just draw the cell with reduced alpha and then a white overlay.
Actually simpler: draw the cell normally, then overlay white with alpha = flash*0.9.
Let me restructure:
```js
if (remove.has(y)){
drawCell(x, y, t, 1, false, 0);
if (flash > 0.01){
ctx.save();
ctx.globalAlpha = flash * 0.9;
ctx.fillStyle = '#fff';
roundRect(BOARD_X + x*CELL + 2, BOARD_Y + y*CELL + 2, CELL-4, CELL-4, 4);
ctx.fill();
ctx.restore();
}
}
```
Good.
Now, the particles should burst when the clear starts. I'll add them in lockPiece.
Let me also add a screen shake.
OK, writing the final code now. Let me be complete.
Let me also handle the `p` key for pause — but `p` might conflict with nothing. Fine.
Also, when paused, the game should still render.
Let me write the pause overlay:
```js
function drawPauseOverlay(){
ctx.save();
ctx.fillStyle = 'rgba(5,8,16,0.72)';
ctx.fillRect(0,0,W,H);
spacedText('PAUSED', W/2, H/2 - 20, 40, '#7dd3fc', 10);
text('PRESS P TO RESUME', W/2, H/2 + 30, 16, '#94a3b8', 'center', 600, 'monospace');
ctx.restore();
}
```
Good.
Game over overlay:
```js
function drawGameOver(){
ctx.save();
ctx.fillStyle = 'rgba(20,0,0,0.75)';
ctx.fillRect(0,0,W,H);
// flashing
const flash = 0.5 + 0.5*Math.sin(performance.now()/200);
spacedText('GAME OVER', W/2, H/2 - 90, 52, `rgba(255,80,80,${flash})`, 10);
text('SCORE', W/2, H/2 - 10, 16, '#94a3b8', 'center', 600, 'monospace');
text(String(score), W/2, H/2 + 25, 34, '#facc15', 'center', 700, 'monospace');
text('LINES', W/2, H/2 + 80, 16, '#94a3b8', 'center', 600, 'monospace');
text(String(lines), W/2, H/2 + 115, 34, '#facc15', 'center', 700, 'monospace');
const pulse = 0.55 + 0.45*Math.sin(performance.now()/300);
text('PRESS ENTER OR CLICK TO PLAY AGAIN', W/2, H/2 + 190, 16, `rgba(148,163,184,${pulse})`, 'center', 600, 'monospace');
ctx.restore();
}
```
Good.
Now let me write the whole file.
I need to double check the `text` function signature. Let me define:
```js
function text(str, x, y, size, color, align, weight, family){
ctx.font = `${weight} ${size}px ${family || 'monospace'}`;
ctx.textAlign = align || 'left';
ctx.textBaseline = 'middle';
ctx.fillStyle = color;
ctx.fillText(str, x, y);
}
```
OK.
Let me write the final file now.
Actually, one concern: `ctx.shadowBlur` with many cells could be slow. Let me only use glow for the active piece (10 cells max) and the next preview. For the board, no glow.
Let me finalize.
Also, I want the board to look nice. Let me add a subtle inner border and a "playfield" gradient.
Writing now.
Let me also make sure the canvas is crisp. Since it's 800x640 and displayed at 800x640, it should be 1:1.
Final code:
I'll write it out.
Let me count the pieces: I, J, L, O, S, T, Z — 7 standard pieces. ✓
Let me write.
For the start screen, I'll add a nice animated background with floating particles.
Let me write the code.
```js
// start screen stars
const stars = [];
for (let i=0;i<60;i++){
stars.push({
x: Math.random()*W,
y: Math.random()*H,
z: Math.random()*0.5+0.2,
phase: Math.random()*Math.PI*2
});
}
```
And in drawStartScreen, update positions based on time.
Actually, let me just draw them with a sine wave.
```js
const t = performance.now()/1000;
for (const s of stars){
const px = s.x + Math.sin(t*1.5 + s.phase)*30*s.z;
const py = s.y + Math.cos(t*1.2 + s.phase)*30*s.z;
ctx.globalAlpha = 0.3 + 0.7*Math.abs(Math.sin(t*2 + s.phase));
ctx.fillStyle = '#7dd3fc';
ctx.fillRect(px, py, 2, 2);
}
ctx.globalAlpha = 1;
```
Good.
Now writing the final answer.
Let me make sure I handle the `keydown` for the start screen correctly — any key starts the game. But I should also prevent default for arrows/space.
Let me write:
```js
window.addEventListener('keydown', function(e){
const k = e.key;
if (k === ' ' || k === 'ArrowLeft' || k === 'ArrowRight' || k === 'ArrowUp' || k === 'ArrowDown'){
e.preventDefault();
}
if (state === 'start'){
startGame();
return;
}
if (state === 'gameover'){
if (k === 'Enter' || k === ' '){
reset();
}
return;
}
if (state === 'paused'){
if (k === 'p' || k === 'P'){
state = 'playing';
}
return;
}
if (state === 'clearing') return;
if (state === 'playing'){
if (k === 'ArrowLeft'){ move(-1, 0); }
else if (k === 'ArrowRight'){ move(1, 0); }
else if (k === 'ArrowDown'){ softDrop(); }
else if (k === 'ArrowUp'){ rotate(1); }
else if (k === 'z' || k === 'Z'){ rotate(-1); }
else if (k === ' '){ hardDrop(); }
else if (k === 'p' || k === 'P'){ state = 'paused'; }
}
});
```
Wait, for the start screen, if the user presses 'p', it starts the game. That's fine per the requirement ("presses any key").
But there's a subtlety: if the user presses a key to start, and then the same keydown event... no, it's a single event.
Also, for the game over screen, pressing Enter restarts. But the keydown handler for 'Enter' — I check `k === 'Enter'`. Good.
Now, `startGame()` should set state to 'playing' and reset the game.
Let me define:
```js
function startGame(){
reset();
state = 'playing';
}
```
And reset() sets up the board etc. but doesn't set state.
Actually, let me have reset() do everything and set state='playing'.
```js
function reset(){
board = createBoard();
bag = [];
score = 0;
lines = 0;
level = 1;
dropInterval = 800;
dropCounter = 0;
particles = [];
shake = 0;
clearRows = [];
clearT = 0;
clearDur = 400;
nextType = nextFromBag();
spawn();
state = 'playing';
}
```
And spawn() might set state to 'gameover' if it can't fit. That's fine.
OK, writing the final code.
Let me write out the complete HTML file now.
I'll be careful about the order of function definitions (function declarations are hoisted, so it's fine).
Let me write it.
Actually, one more thought on the visual polish: let me add a "drop indicator" column highlight and a subtle scanline effect on the board. And maybe a glow around the active piece.
Let me add a scanline overlay on the board:
```js
// scanlines
ctx.save();
ctx.globalAlpha = 0.04;
ctx.fillStyle = '#000';
for (let y=0;y
Block Cascade
```
### Gameplay & Visual Design
The game runs on a 10×20 grid with all seven standard tetrominoes, and the pace gradually increases as you clear lines. The interface is built around a dark, neon-styled canvas with glowing panels and particle bursts.
- **Controls & feedback:** Arrow keys move and rotate pieces, the down arrow soft drops, space hard drops, and P pauses. Every action triggers screen shake, particles, or a flash to make the game feel responsive.
- **Scoring & progression:** Clearing lines awards points based on how many rows you clear at once, and the level rises every 10 lines, which speeds up the automatic fall.
- **Visual polish:** The board has a subtle grid, the active piece glows, a ghost piece shows where it will land, and line clears produce white flashes and sliding rows.
- **Start & game over:** Before the first move, a starfield and control panel invite you to click or press any key. When the board fills up, a flashing game over screen appears with your final score and lines.
---
**Optimization Tip:** You can adjust the starting drop speed by changing the `dropInterval` value (currently 800 ms) inside the `reset()` function, or modify the speed-up curve by editing the `Math.pow(0.82, level - 1)` expression in `finalizeClear()`.