[reasoning, returned separately by llama-server] The user wants a complete Tetris-like game in a single self-contained HTML file. Let me break down the requirements: 1. 10x20 grid, 7 standard tetrominoes. 2. Pieces fall automatically, speed up with line clears. 3. Controls: Left/Right arrows move, Up rotates, Down soft drop, Space hard drop, P pauses. 4. Arrow keys and space must not scroll page (preventDefault). 5. Collision detection with walls, floor, pieces. 6. Line clears, rows above move down. 7. Show score, lines cleared, next piece. 8. Start screen with controls. Game starts on click or keypress. 9. Game over message when new piece can't enter. Enter or click to restart. 10. Messages on page, no alert/confirm/prompt. 11. Sound optional but must be off until turned on. I'll probably skip sound or implement a simple toggle to be safe, but since it's optional and "if the game has sound", I can omit it entirely to avoid issues. Actually, the requirement says "Sound is optional. If the game has sound, it must stay off until the player turns it on." So I can just not include sound. 12. No localStorage/sessionStorage/IndexedDB/cookies. All state in memory. 13. Page fits in 800x640 frame. 14. All CSS and JS inline. No external resources. 15. Do not use the word "Tetris" anywhere. I need to be careful not to use the forbidden word. I'll call it "Blockfall" or "Falling Blocks" or just refer to it as "the game". Let me design the game: HTML structure: - Container div for the game area (800x640) - Canvas for rendering or DOM elements. Canvas is better for smooth animation and effects. - Overlay for start screen, game over, pause. - Score, lines, next piece display. Game logic: - Grid: 10 columns, 20 rows. - Pieces: 7 tetrominoes (I, O, T, S, Z, J, L). - Each piece has shape, color, rotation states. - Current piece: x, y, rotation. - Next piece: preview. - Board: 2D array or set of occupied cells. - Score, lines, level (for speed). - Game loop: requestAnimationFrame or setInterval. Since pieces fall on their own, I need a timer. Speed up as lines cleared. Let me think about the rendering. I'll use HTML5 Canvas. It's self-contained, no external images. I can draw blocks with rounded corners for polish. Colors for standard pieces: - I: cyan - O: yellow - T: purple - S: green - Z: red - J: blue - L: orange Controls: - Prevent default on keydown for arrow keys and space. - P for pause. - Enter to start/restart. - Click to start/restart. Start screen: Show controls text. Centered. Game over: Show message "Game Over" and "Press Enter or Click to Restart". Speed: Start with a fall delay. Every line clear reduces delay. Standard Tetris levels, but I can simplify: delay = max(100, 1000 - lines * 50) or something. Or use levels: level = lines / 10 + 1, delay = 1000 / level. Let's do something smooth. Let me outline the code structure: ```html
Move: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
Restart: Enter or Click
Score: ${score}
Lines: ${lines}
`; btn.textContent = 'Play Again'; btn.style.display = 'block'; } else if (!started) { title.textContent = 'Falling Blocks'; content.innerHTML = `Move: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
`; btn.textContent = 'Start Game'; btn.style.display = 'block'; } else if (paused) { title.textContent = 'Paused'; content.innerHTML = 'Press P to resume
'; btn.style.display = 'none'; } overlay.classList.remove('hidden'); } ``` Wait, I need to handle the start. When game starts, hide overlay. ```javascript function startGame() { started = true; gameOver = false; paused = false; score = 0; lines = 0; level = 1; dropInterval = 800; fallTimer = 0; board = Array.from({length: 20}, () => Array(10).fill(0)); currentPiece = createPiece(randomPiece()); nextPiece = randomPiece(); updateUI(); showOverlay(); // hide it lastTime = performance.now(); requestAnimationFrame(loop); } ``` But the overlay has a click handler. I need to make sure clicking the overlay starts the game. Also, clicking anywhere on the page starts the game. But if I click on the canvas, it should also start. So a global click listener. However, once the game is running, clicking should not restart unless game over. So: ```javascript document.addEventListener('click', (e) => { if (!started) { startGame(); } else if (gameOver) { resetGame(); } }); ``` And keydown: ```javascript document.addEventListener('keydown', (e) => { if (!started) { e.preventDefault(); startGame(); return; } if (gameOver) { if (e.key === 'Enter') { e.preventDefault(); resetGame(); } return; } if (paused) { if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } return; } // gameplay if (e.key === 'ArrowLeft') { e.preventDefault(); move(-1); } else if (e.key === 'ArrowRight') { e.preventDefault(); move(1); } else if (e.key === 'ArrowUp') { e.preventDefault(); rotate(); } else if (e.key === 'ArrowDown') { e.preventDefault(); softDrop(); } else if (e.code === 'Space') { e.preventDefault(); hardDrop(); } else if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } }); ``` Wait, the requirement says "The game starts when the player clicks the page or presses any key." So any key press starts it. My keydown handler does that. But what about the `P` key during gameplay? It pauses. That's fine. Now, the `resetGame` function is basically `startGame`. ```javascript function resetGame() { startGame(); } ``` UI update: ```javascript function updateUI() { document.getElementById('score').textContent = score; document.getElementById('lines').textContent = lines; document.getElementById('level').textContent = level; } ``` Drawing the next piece: ```javascript function drawNext() { const ctx = document.getElementById('nextCanvas').getContext('2d'); ctx.clearRect(0, 0, 100, 100); const shape = PIECES[nextPiece].shape; const bs = 20; // block size for next for (let y = 0; y < shape.length; y++) { for (let x = 0; x < shape[y].length; x++) { if (shape[y][x]) { ctx.fillStyle = PIECES[nextPiece].color; ctx.fillRect(x * bs + 10, y * bs + 10, bs, bs); // add bevel ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(x * bs + 10 + bs - 4, y * bs + 10, 4, bs); ctx.fillRect(x * bs + 10, y * bs + 10 + bs - 4, bs, 4); ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(x * bs + 10, y * bs + 10, bs, 4); ctx.fillRect(x * bs + 10, y * bs + 10, 4, bs); } } } } ``` Wait, the next piece shape is 4x4. With bs=20, that's 80x80. Offset 10 centers it in 100x100. Good. Now, the main canvas drawing. I need to handle the board coordinates. Canvas is 300x600. BLOCK_SIZE = 30. ```javascript const BLOCK_SIZE = 30; const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); canvas.width = 10 * BLOCK_SIZE; canvas.height = 20 * BLOCK_SIZE; ``` Draw function: ```javascript function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // draw board for (let y = 0; y < 20; y++) { for (let x = 0; x < 10; x++) { if (board[y][x]) { drawBlock(ctx, x * BLOCK_SIZE, y * BLOCK_SIZE, PIECES[board[y][x] - 1].color); } } } // draw ghost drawGhost(ctx, currentPiece); // draw current piece for (let y = 0; y < currentPiece.matrix.length; y++) { for (let x = 0; x < currentPiece.matrix[y].length; x++) { if (currentPiece.matrix[y][x]) { drawBlock(ctx, (currentPiece.x + x) * BLOCK_SIZE, (currentPiece.y + y) * BLOCK_SIZE, PIECES[currentPiece.type].color); } } } drawNext(); } ``` Wait, `PIECES[board[y][x] - 1]` assumes board stores type+1. Let's store the type index (0-6) directly, or store color. Let's store the piece type index + 1 to distinguish from 0 (empty). So `board[y][x] = piece.type + 1`. Then color is `PIECES[board[y][x] - 1].color`. Actually, I can just store the color string, but then I need to know it's not empty. Let's store `type + 1`. `drawBlock`: ```javascript function drawBlock(ctx, x, y, color) { ctx.fillStyle = color; ctx.fillRect(x, y, BLOCK_SIZE, BLOCK_SIZE); // bevel ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(x + BLOCK_SIZE - 4, y, 4, BLOCK_SIZE); ctx.fillRect(x, y + BLOCK_SIZE - 4, BLOCK_SIZE, 4); ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fillRect(x, y, BLOCK_SIZE, 4); ctx.fillRect(x, y, 4, BLOCK_SIZE); } ``` `drawGhost`: ```javascript function drawGhost(ctx, piece) { let ghostY = piece.y; while (!collide(board, { ...piece, y: ghostY + 1 })) { ghostY++; } ctx.globalAlpha = 0.3; for (let y = 0; y < piece.matrix.length; y++) { for (let x = 0; x < piece.matrix[y].length; x++) { if (piece.matrix[y][x]) { drawBlock(ctx, (piece.x + x) * BLOCK_SIZE, (ghostY + y) * BLOCK_SIZE, PIECES[piece.type].color); } } } ctx.globalAlpha = 1.0; } ``` Wait, `drawBlock` uses `ctx.fillStyle` and then draws. The ghost will be drawn with alpha 0.3, but `drawBlock` also draws bevels with solid colors. That might look odd. I could modify `drawBlock` to accept an alpha parameter, or just draw the ghost separately with a simpler function. Let's make `drawBlock` accept an optional alpha. ```javascript function drawBlock(ctx, x, y, color, alpha = 1) { ctx.globalAlpha = alpha; ctx.fillStyle = color; ctx.fillRect(x, y, BLOCK_SIZE, BLOCK_SIZE); ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(x + BLOCK_SIZE - 4, y, 4, BLOCK_SIZE); ctx.fillRect(x, y + BLOCK_SIZE - 4, BLOCK_SIZE, 4); ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fillRect(x, y, BLOCK_SIZE, 4); ctx.fillRect(x, y, 4, BLOCK_SIZE); ctx.globalAlpha = 1; } ``` But setting globalAlpha inside and resetting might be okay. However, the bevels will also be alpha'd. That's fine for ghost. Actually, for the ghost, I want it to look like a transparent outline or filled. Let's just draw the ghost with alpha 0.3 for the fill, and skip bevels or use alpha for bevels too. It's fine. Now, the `collide` function needs to handle the piece's matrix. The piece object has `x`, `y`, `matrix`. One issue: when rotating, the piece might go out of bounds horizontally. For example, if x=3 and the piece is 4 wide, rotating might make it 1 wide but shifted. The collision check will catch if it goes out of bounds (bx < 0 or bx >= 10). But it won't adjust position. That's okay. However, there's a known issue: rotating near the edge can cause the piece to be stuck if it can't rotate. But for this contest, it's acceptable. Let me think about the `merge` function: ```javascript function merge(board, piece) { for (let y = 0; y < piece.matrix.length; y++) { for (let x = 0; x < piece.matrix[y].length; x++) { if (piece.matrix[y][x]) { board[piece.y + y][piece.x + x] = piece.type + 1; } } } } ``` `clearLines`: ```javascript function clearLines(board) { let cleared = 0; for (let y = 19; y >= 0; y--) { let full = true; for (let x = 0; x < 10; x++) { if (!board[y][x]) { full = false; break; } } if (full) { board.splice(y, 1); board.unshift(new Array(10).fill(0)); cleared++; y++; // stay on same index because row shifted } } return cleared; } ``` Wait, `board.splice(y, 1)` removes the row. Then `unshift` adds a new row at top. The rows above move down. This is correct. But `y++` after splice: since we removed a row, the row that was above is now at index y. We need to check it again. So `y++` cancels the `y--` in the loop, effectively checking the same index again. That's correct. But there's a subtle bug: if we clear multiple lines, the loop index management with `y++` works because we only increment when we clear. Let's trace: - y=19, clear it. board becomes 19 rows (indices 0-18). y becomes 20 after y++? No, the for loop does y-- at the end. So if we do y++ inside, then the loop's y-- makes it net zero. So we check the same y again. But the board has shifted. The row that was at y-1 is now at y. So we check it. Good. Actually, standard approach: ```javascript for (let y = 19; y >= 0; y--) { if (isFull(board[y])) { board.splice(y, 1); board.unshift([0,0,0,0,0,0,0,0,0,0]); cleared++; y++; // because next iteration will y--, so we stay on same y } } ``` Yes, that's correct. Now, scoring: `score += cleared * 100 * level`. Standard is 100, 300, 500, 800 for 1,2,3,4 lines. But `cleared * 100 * level` is simpler and fine. Speed: `dropInterval = Math.max(100, 1000 - (level - 1) * 100);`. At level 1, 1000ms. Level 2, 900ms. ... Level 10, 100ms. That's reasonable. Now, the start screen. The requirement says "Before the game starts, show the controls on the page." So the overlay should show controls. I'll show them in the overlay. Also, "The game starts when the player clicks the page or presses any key." So I need to listen for click and keydown on the document. But if I have a keydown listener that starts the game, and the game also uses keydown for controls, I need to make sure the start listener doesn't interfere. My approach: one keydown listener that checks state. One issue: when the game is not started, pressing any key starts it. But if I press, say, 'A', it starts. Then the game is running. That's fine. But what about the `P` key? If not started, pressing P starts the game. That's fine per requirement. Now, the overlay should be hidden when game starts. I'll use a CSS class `hidden` with `display: none`. Let me write the HTML and CSS carefully. CSS: ```css body { margin: 0; background: #111; color: #fff; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; overflow: hidden; width: 800px; height: 640px; } #container { width: 800px; height: 640px; margin: 0 auto; position: relative; background: #222; border: 4px solid #444; box-shadow: 0 0 30px rgba(0,0,0,0.5); } canvas { display: block; } #overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 10; } .hidden { display: none !important; } h1 { font-size: 48px; margin: 0 0 20px; text-shadow: 2px 2px 4px #000; color: #4a90e2; } .controls { text-align: center; line-height: 1.8; margin-bottom: 25px; font-size: 18px; } .controls p { margin: 6px 0; } .btn { padding: 12px 28px; font-size: 20px; cursor: pointer; background: #4a90e2; color: white; border: 2px solid #fff; border-radius: 6px; box-shadow: 0 4px 0 #222; } .btn:hover { background: #5bb3f5; } .btn:active { box-shadow: 0 0 0 #222; transform: translateY(4px); } #ui { position: absolute; top: 15px; left: 15px; font-size: 22px; font-weight: bold; text-shadow: 1px 1px 2px #000; pointer-events: none; } #next { position: absolute; top: 15px; right: 15px; text-align: right; pointer-events: none; } #next-label { font-size: 16px; color: #aaa; margin-bottom: 8px; } ``` Wait, `width: 800px; height: 640px;` on body might cause scrollbars if the viewport is smaller. But the requirement says "The whole page must fit in a frame 800 pixels wide and 640 pixels high." So I should ensure the page doesn't exceed that. I can set `body { width: 800px; height: 640px; overflow: hidden; }` and `margin: 0 auto;` to center it? Actually, if the frame is exactly 800x640, the body should be that size. I'll set `body { width: 800px; height: 640px; margin: 0; overflow: hidden; }` and center the container if needed. But if the body is exactly 800x640, the container can be 100%. Actually, to be safe, I'll set: ```css body { margin: 0; background: #111; color: #fff; font-family: sans-serif; overflow: hidden; width: 800px; height: 640px; display: flex; justify-content: center; align-items: center; } #container { width: 800px; height: 640px; position: relative; background: #1a1a2e; border: 4px solid #333; box-shadow: 0 0 20px rgba(0,0,0,0.5); } ``` This ensures the page is exactly 800x640. Canvas positioning: I'll center the game canvas in the container. ```css #gameCanvas { display: block; margin: 20px auto; } ``` But the canvas is 300x600. The container is 800x640. So there's space on the sides for UI. The UI is absolutely positioned. Wait, the UI is absolutely positioned at top left and top right. The canvas is centered. That should work. Let me place the canvas at top center: ```css #gameCanvas { display: block; margin: 20px auto 0 auto; } ``` Actually, the next piece canvas is at top right. The score is at top left. The game canvas should be below them, centered. So `margin: 80px auto 0 auto;` or something. But the UI is absolutely positioned, so it doesn't affect flow. I can just center the canvas with `margin: 0 auto;` and `display: block;`. The container is 800 wide, canvas is 300 wide, so it will be centered with 250px on each side. That's fine. Now, the overlay button. When game is over, the button says "Play Again". When not started, "Start Game". When paused, no button. I need to handle the click on the overlay button. I can add a click listener to the button, or rely on the global click listener. If I use global click listener, clicking the button will trigger it. But the button is inside the overlay. The global click listener on document will catch it. However, I need to make sure that clicking the button when game is running and not over does nothing. My global click listener checks `if (!started) startGame(); else if (gameOver) resetGame();`. So if game is running and not over, clicking does nothing. That's fine. But the overlay button is visible when game over or not started. So clicking it will start/restart. Good. Now, one issue: the global keydown listener. When the game is not started, any key starts it. But the overlay has a button. If I click the button, it's a click event, not keydown. So that's fine. What about the `P` key? If not started, pressing P starts the game. That's fine. Now, I need to make sure that when the game is paused, the overlay shows "Paused" and the game loop stops updating but still renders? Actually, when paused, I should stop the fall timer and just render. The draw function still runs. That's fine. Let me code the loop: ```javascript let lastTime = performance.now(); let fallTimer = 0; let dropInterval = 800; function loop(timestamp) { const deltaTime = timestamp - lastTime; lastTime = timestamp; if (!paused && !gameOver) { fallTimer += deltaTime; while (fallTimer >= dropInterval) { fallTimer -= dropInterval; const nextPos = { ...currentPiece, y: currentPiece.y + 1 }; if (!collide(board, nextPos)) { currentPiece.y++; } else { lockPiece(); } } } draw(); requestAnimationFrame(loop); } ``` Wait, `while` loop could be problematic if deltaTime is huge, but it's fine. One issue: `lockPiece` might set `gameOver = true`. Then the loop will still run but `!gameOver` is false, so it won't try to move. It will still draw. Good. Now, `startGame`: ```javascript function startGame() { if (started && !gameOver) return; // already running started = true; gameOver = false; paused = false; score = 0; lines = 0; level = 1; dropInterval = 800; fallTimer = 0; board = Array.from({length: 20}, () => Array(10).fill(0)); currentPiece = createPiece(randomPiece()); nextPiece = randomPiece(); updateUI(); hideOverlay(); lastTime = performance.now(); requestAnimationFrame(loop); } ``` `hideOverlay`: ```javascript function hideOverlay() { document.getElementById('overlay').classList.add('hidden'); } ``` `showOverlay`: ```javascript function showOverlay() { const overlay = document.getElementById('overlay'); const title = document.getElementById('overlayTitle'); const content = document.getElementById('overlayContent'); const btn = document.getElementById('overlayBtn'); overlay.classList.remove('hidden'); if (gameOver) { title.textContent = 'Game Over'; content.innerHTML = `Final Score: ${score}
Lines Cleared: ${lines}
`; btn.textContent = 'Play Again'; btn.style.display = 'block'; btn.onclick = resetGame; } else if (!started) { title.textContent = 'Falling Blocks'; content.innerHTML = `Move: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
Restart: Enter or Click
`; btn.textContent = 'Start Game'; btn.style.display = 'block'; btn.onclick = startGame; } else if (paused) { title.textContent = 'Paused'; content.innerHTML = 'Press P to resume
'; btn.style.display = 'none'; } } ``` Wait, I need to make sure the overlay is shown initially. So in the HTML, the overlay is visible. The `startGame` hides it. But the `showOverlay` is called when game over or pause. For pause, I call `showOverlay` which sets content to paused. For game over, it sets content to game over. Now, the `togglePause`: ```javascript function togglePause() { if (gameOver) return; paused = !paused; showOverlay(); } ``` When paused, `showOverlay` is called. It shows the paused screen. When resumed (P again), `togglePause` sets `paused = false` and then `hideOverlay()`. Wait, `togglePause` should hide the overlay when resuming. Let me adjust: ```javascript function togglePause() { if (gameOver) return; paused = !paused; if (paused) { showOverlay(); } else { hideOverlay(); lastTime = performance.now(); // reset timer to avoid jump } } ``` Now, the `resetGame` function: ```javascript function resetGame() { startGame(); } ``` Now, the keydown listener. I need to attach it to the document. ```javascript document.addEventListener('keydown', (e) => { if (!started) { e.preventDefault(); startGame(); return; } if (gameOver) { if (e.key === 'Enter') { e.preventDefault(); resetGame(); } return; } if (paused) { if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } return; } // gameplay if (e.key === 'ArrowLeft') { e.preventDefault(); move(-1); } else if (e.key === 'ArrowRight') { e.preventDefault(); move(1); } else if (e.key === 'ArrowUp') { e.preventDefault(); rotate(); } else if (e.key === 'ArrowDown') { e.preventDefault(); softDrop(); } else if (e.code === 'Space') { e.preventDefault(); hardDrop(); } else if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } }); ``` Wait, the requirement says "The game starts when the player clicks the page or presses any key." So if the game is not started, any key press starts it. My code does `e.preventDefault()` and `startGame()`. That's good. But what if the user presses a key that is also a gameplay key? Since the game isn't started, it just starts. That's fine. Now, the click listener: ```javascript document.addEventListener('click', (e) => { if (!started) { startGame(); } else if (gameOver) { resetGame(); } }); ``` This handles clicking anywhere. But if the user clicks on the canvas while the game is running and not over, nothing happens. That's fine. Now, I need to make sure the `startGame` function is not called multiple times if the game is already running. The click listener checks `!started`, so it's fine. One issue: the overlay button has an `onclick` handler. If I click the button, it triggers both the button's onclick and the document's click listener? Actually, the document click listener will also fire because the button is inside the document. But since `startGame` checks `if (started && !gameOver) return;`, it won't restart if already running. However, if the game is not started, clicking the button calls `startGame` via onclick, and the document click listener also calls `startGame`. That's okay because `startGame` is idempotent (it resets everything). But to avoid double handling, I can remove the onclick from the button and rely solely on the document click listener. Or I can keep the onclick but make sure it doesn't conflict. Actually, it's fine. But wait: if the game is over, and I click the "Play Again" button, the button's onclick calls `resetGame`, and the document click listener also calls `resetGame`. Double reset. Not a big deal, but I can avoid it by not setting onclick on the button and letting the document listener handle it. Or I can set the button's onclick to `event.stopPropagation()` and then call reset. Let's just rely on the document click listener and remove onclick from the button, or set the button's onclick to a no-op. Actually, simpler: don't set onclick on the button. The document click listener will handle clicks on the button too. But the button is inside the overlay. The document click listener will fire. So I can just remove the onclick assignments. Let me adjust `showOverlay` to not set onclick. Now, the `drawNext` function. I need to draw the next piece. The next piece is stored as `nextPiece` (an index). I draw its shape. ```javascript function drawNext() { const ctx = document.getElementById('nextCanvas').getContext('2d'); ctx.clearRect(0, 0, 100, 100); const shape = PIECES[nextPiece].shape; const bs = 20; const offset = 10; for (let y = 0; y < shape.length; y++) { for (let x = 0; x < shape[y].length; x++) { if (shape[y][x]) { ctx.fillStyle = PIECES[nextPiece].color; ctx.fillRect(x * bs + offset, y * bs + offset, bs, bs); // bevel ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(x * bs + offset + bs - 4, y * bs + offset, 4, bs); ctx.fillRect(x * bs + offset, y * bs + offset + bs - 4, bs, 4); ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(x * bs + offset, y * bs + offset, bs, 4); ctx.fillRect(x * bs + offset, y * bs + offset, 4, bs); } } } } ``` Now, the `drawBlock` function for the main canvas. I'll make it use `BLOCK_SIZE`. ```javascript function drawBlock(ctx, x, y, color, alpha = 1) { ctx.globalAlpha = alpha; ctx.fillStyle = color; ctx.fillRect(x, y, BLOCK_SIZE, BLOCK_SIZE); ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(x + BLOCK_SIZE - 4, y, 4, BLOCK_SIZE); ctx.fillRect(x, y + BLOCK_SIZE - 4, BLOCK_SIZE, 4); ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fillRect(x, y, BLOCK_SIZE, 4); ctx.fillRect(x, y, 4, BLOCK_SIZE); ctx.globalAlpha = 1; } ``` Wait, if I set `ctx.globalAlpha = alpha` and then draw bevels with solid colors, they will also be alpha'd. That's fine for ghost. But for normal blocks, alpha is 1. Now, the `draw` function: ```javascript function draw() { const ctx = document.getElementById('gameCanvas').getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); // draw board for (let y = 0; y < 20; y++) { for (let x = 0; x < 10; x++) { if (board[y][x]) { drawBlock(ctx, x * BLOCK_SIZE, y * BLOCK_SIZE, PIECES[board[y][x] - 1].color); } } } // draw ghost drawGhost(ctx, currentPiece); // draw current piece for (let y = 0; y < currentPiece.matrix.length; y++) { for (let x = 0; x < currentPiece.matrix[y].length; x++) { if (currentPiece.matrix[y][x]) { drawBlock(ctx, (currentPiece.x + x) * BLOCK_SIZE, (currentPiece.y + y) * BLOCK_SIZE, PIECES[currentPiece.type].color); } } } drawNext(); } ``` `drawGhost`: ```javascript function drawGhost(ctx, piece) { let ghostY = piece.y; while (!collide(board, { ...piece, y: ghostY + 1 })) { ghostY++; } ctx.globalAlpha = 0.3; for (let y = 0; y < piece.matrix.length; y++) { for (let x = 0; x < piece.matrix[y].length; x++) { if (piece.matrix[y][x]) { drawBlock(ctx, (piece.x + x) * BLOCK_SIZE, (ghostY + y) * BLOCK_SIZE, PIECES[piece.type].color); } } } ctx.globalAlpha = 1.0; } ``` But `drawBlock` resets `globalAlpha` to 1 at the end. So after drawing a ghost block, alpha is reset to 1. Then the next ghost block will be drawn with alpha 0.3 again because I set `ctx.globalAlpha = 0.3` at the start of `drawGhost`. But `drawBlock` sets it to 1 at the end. So I need to set alpha before each block or not reset inside `drawBlock`. Let me modify `drawBlock` to not reset globalAlpha, or handle it outside. Better: `drawBlock` should not change globalAlpha permanently. I'll pass alpha and set it, draw, and leave it. Then `drawGhost` sets alpha to 0.3 before calling `drawBlock`, and after the loop, sets it back to 1. But `drawBlock` also sets it to 1 at the end. That would break the ghost. So I'll remove the `ctx.globalAlpha = 1` at the end of `drawBlock`, and manage alpha in the caller. ```javascript function drawBlock(ctx, x, y, color) { ctx.fillStyle = color; ctx.fillRect(x, y, BLOCK_SIZE, BLOCK_SIZE); ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(x + BLOCK_SIZE - 4, y, 4, BLOCK_SIZE); ctx.fillRect(x, y + BLOCK_SIZE - 4, BLOCK_SIZE, 4); ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fillRect(x, y, BLOCK_SIZE, 4); ctx.fillRect(x, y, 4, BLOCK_SIZE); } ``` Then in `drawGhost`: ```javascript function drawGhost(ctx, piece) { let ghostY = piece.y; while (!collide(board, { ...piece, y: ghostY + 1 })) { ghostY++; } const prevAlpha = ctx.globalAlpha; ctx.globalAlpha = 0.3; for (let y = 0; y < piece.matrix.length; y++) { for (let x = 0; x < piece.matrix[y].length; x++) { if (piece.matrix[y][x]) { drawBlock(ctx, (piece.x + x) * BLOCK_SIZE, (ghostY + y) * BLOCK_SIZE, PIECES[piece.type].color); } } } ctx.globalAlpha = prevAlpha; } ``` This is cleaner. Now, the `collide` function. It takes a board and a piece. The piece has `x`, `y`, `matrix`. ```javascript function collide(board, piece) { for (let y = 0; y < piece.matrix.length; y++) { for (let x = 0; x < piece.matrix[y].length; x++) { if (piece.matrix[y][x]) { const bx = piece.x + x; const by = piece.y + y; if (bx < 0 || bx >= 10 || by >= 20) return true; if (by >= 0 && board[by][bx]) return true; } } } return false; } ``` Note: `by < 0` is allowed (above board). But if `by < 0`, we don't check board. However, if the piece is partially above the board, the blocks with `by >= 0` are checked against the board. That's correct. But what about `by < 0` and `bx` out of bounds? The `bx < 0 || bx >= 10` check applies regardless of `by`. So walls are checked even above the board. That's correct. Now, `move`: ```javascript function move(dir) { if (!collide(board, { ...currentPiece, x: currentPiece.x + dir })) { currentPiece.x += dir; } } ``` `rotate`: ```javascript function rotate() { const newMatrix = rotateMatrix(currentPiece.matrix); if (!collide(board, { ...currentPiece, matrix: newMatrix })) { currentPiece.matrix = newMatrix; } } ``` `softDrop`: ```javascript function softDrop() { if (!collide(board, { ...currentPiece, y: currentPiece.y + 1 })) { currentPiece.y++; } } ``` `hardDrop`: ```javascript function hardDrop() { while (!collide(board, { ...currentPiece, y: currentPiece.y + 1 })) { currentPiece.y++; } lockPiece(); } ``` `lockPiece`: ```javascript function lockPiece() { merge(board, currentPiece); const cleared = clearLines(board); if (cleared > 0) { score += cleared * 100 * level; lines += cleared; level = 1 + Math.floor(lines / 10); dropInterval = Math.max(100, 1000 - (level - 1) * 100); updateUI(); } currentPiece = createPiece(nextPiece); nextPiece = randomPiece(); if (collide(board, currentPiece)) { gameOver = true; showOverlay(); } else { updateUI(); } } ``` Wait, I should call `updateUI()` after score changes. I call it inside `if (cleared > 0)`. But I also need to update UI when level changes. That's inside the same block. Good. But what if no lines cleared? I still need to spawn next piece. The UI doesn't change, so no need to call `updateUI()`. Now, `createPiece`: ```javascript function createPiece(type) { const shape = PIECES[type].shape; const matrix = shape.map(row => [...row]); return { type, matrix, x: 3, y: 0, rotation: 0 }; } ``` Since all shapes are 4x4, x=3 centers them (10-4)/2 = 3. Now, `randomPiece`: ```javascript function randomPiece() { return Math.floor(Math.random() * PIECES.length); } ``` Now, the initial state. The board is empty. `currentPiece` and `nextPiece` are undefined until `startGame` is called. I need to initialize variables: ```javascript let started = false; let gameOver = false; let paused = false; let score = 0; let lines = 0; let level = 1; let dropInterval = 800; let fallTimer = 0; let lastTime = performance.now(); let board = []; let currentPiece = null; let nextPiece = null; ``` Now, the `loop` function. I need to call `requestAnimationFrame(loop)` initially after start. One issue: when `startGame` is called, it sets `lastTime = performance.now()` and calls `requestAnimationFrame(loop)`. The loop will then update. Now, the HTML structure. Let me write it out. ```htmlMove: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
Restart: Enter or Click
Final Score: ${score}
Lines Cleared: ${lines}
`; btn.textContent = 'Play Again'; btn.style.display = 'block'; } else if (!started) { title.textContent = 'Falling Blocks'; content.innerHTML = `Move: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
Restart: Enter or Click
`; btn.textContent = 'Start Game'; btn.style.display = 'block'; } else if (paused) { title.textContent = 'Paused'; content.innerHTML = 'Press P to resume
'; btn.style.display = 'none'; } } function hideOverlay() { document.getElementById('overlay').classList.add('hidden'); } function startGame() { if (started && !gameOver) return; started = true; gameOver = false; paused = false; score = 0; lines = 0; level = 1; dropInterval = 800; fallTimer = 0; board = Array.from({length: 20}, () => Array(10).fill(0)); currentPiece = createPiece(randomPiece()); nextPiece = randomPiece(); updateUI(); hideOverlay(); lastTime = performance.now(); requestAnimationFrame(loop); } function resetGame() { startGame(); } function loop(timestamp) { const deltaTime = timestamp - lastTime; lastTime = timestamp; if (!paused && !gameOver) { fallTimer += deltaTime; while (fallTimer >= dropInterval) { fallTimer -= dropInterval; if (!collide(board, { ...currentPiece, y: currentPiece.y + 1 })) { currentPiece.y++; } else { lockPiece(); } } } draw(); requestAnimationFrame(loop); } document.addEventListener('keydown', (e) => { if (!started) { e.preventDefault(); startGame(); return; } if (gameOver) { if (e.key === 'Enter') { e.preventDefault(); resetGame(); } return; } if (paused) { if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } return; } if (e.key === 'ArrowLeft') { e.preventDefault(); move(-1); } else if (e.key === 'ArrowRight') { e.preventDefault(); move(1); } else if (e.key === 'ArrowUp') { e.preventDefault(); rotate(); } else if (e.key === 'ArrowDown') { e.preventDefault(); softDrop(); } else if (e.code === 'Space') { e.preventDefault(); hardDrop(); } else if (e.key === 'P' || e.key === 'p') { e.preventDefault(); togglePause(); } }); document.addEventListener('click', (e) => { if (!started) { startGame(); } else if (gameOver) { resetGame(); } }); ``` Wait, I need to check for the forbidden word "Tetris". I used "Falling Blocks" and "the game". I didn't use "Tetris". Good. Now, check requirements: - 10x20 grid: yes. - 7 standard pieces: yes. - Pieces fall on their own and speed up: yes, `dropInterval` decreases with level. - Left/Right arrows move: yes. - Up rotates: yes. - Down moves down faster: yes, `softDrop`. - Space drops to bottom: yes, `hardDrop`. - P pauses: yes. - Arrow keys and space must not scroll: `preventDefault()` on those keys. Also on any key during start. Good. - Pieces cannot move through walls, floor, other pieces: `collide` checks. - Full row clears, rows above move down: `clearLines` does this. - Show score, lines, next piece: yes. - Before game starts, show controls: yes, overlay shows controls. - Game starts when player clicks page or presses any key: yes, document listeners. - When new piece cannot enter, show game over message: yes, `lockPiece` checks collision of new piece. - Player can start new game with Enter or click: yes. - Show every message on page itself, no alert/confirm/prompt: yes. - Sound optional: I didn't include sound. That's fine. - Keep all game state in memory: yes, no storage. - Whole page fits in 800x640: yes, CSS sets width/height. - All CSS and JS inline: yes. - No external resources: yes. - Do not use word "Tetris": I need to double-check. I used "Falling Blocks". Let me scan: "Falling Blocks", "Start Game", "Play Again", "Paused", "Game Over", "Final Score", "Lines Cleared", "Next", "Score", "Lines", "Level", "Move", "Rotate", "Soft Drop", "Hard Drop", "Pause", "Restart". No "Tetris". Good. One issue: the `draw` function uses `ctx.clearRect(0, 0, 300, 600)`. The canvas is 300x600. Good. Another issue: the `nextPiece` is drawn using its shape, but the shape is the initial spawn shape, not rotated. That's fine for next preview. Another issue: when the game is paused, the `draw` function still runs, so the ghost and piece are still drawn. That's fine. Another issue: the `fallTimer` is not reset when `dropInterval` changes. But since we subtract `dropInterval` from `fallTimer`, and `dropInterval` only decreases, the timer might be slightly off. But it's fine. Wait, there's a bug: when `lockPiece` is called, it spawns a new piece. But the `fallTimer` continues. The new piece will start falling after the remaining `fallTimer`. That's fine. Another bug: in `clearLines`, I use `board.splice(y, 1)` and `board.unshift(...)`. This modifies the array in place. Since `board` is a 2D array, this works. But I need to make sure that `board` is not a reference to a different array. It's fine. Another issue: the `collide` function checks `by >= 20` as collision. But what if `by < 0`? It's allowed. However, when checking if a piece can move down, if the piece is at y=0 and some blocks are at y=-1 (above board), moving down to y=1 would put those blocks at y=0. That's fine. But if the piece is at y=0 and we check collision for y+1, the blocks at y=-1 become y=0, which is on the board. So we check `board[0][bx]`. That's correct. But there's a subtlety: when a piece spawns at y=0, its blocks are at y=0 to y=3. Some might be above the board (y<0) if the piece shape has blocks in row 0. Actually, my shapes have the piece starting at row 1 or 2. For example, I piece: row 1 has blocks. So y=0 means blocks are at y=1 to y=4. So no blocks are above the board. But for other pieces, like T: row 1 has a block at x=1, row 2 has blocks at x=0,1,2. So at y=0, blocks are at y=1 and y=2. All on board. So `by >= 0` is always true for spawned pieces. But during rotation, a piece might have blocks at y<0. The collision check handles that by not checking board for `by < 0`. But it still checks walls. That's correct. However, when rotating, if the piece is at the top, rotating might cause blocks to go to y<0. That's fine. But if it goes to y<0 and x out of bounds, it's blocked. One more thing: the `move` function uses `{ ...currentPiece, x: currentPiece.x + dir }`. This creates a shallow copy. The `matrix` is shared, but we don't modify it. That's fine. Now, the `drawGhost` function uses `{ ...piece, y: ghostY + 1 }`. Same thing. Now, I need to ensure that the `loop` function is not called before the game starts. I only call `requestAnimationFrame(loop)` inside `startGame`. Good. But what if the user clicks or presses a key before the page is fully loaded? The event listeners are attached after the script runs. The script is at the end of the body, so the DOM is ready. Good. Now, the `overlay` div is initially visible. The `startGame` hides it. The `showOverlay` shows it when game over or pause. One issue: when the game is over, the `showOverlay` is called from `lockPiece`. But `lockPiece` is called from the loop. The loop will continue to run, but `!gameOver` is false, so it won't update the piece. It will still draw. That's fine. But the `fallTimer` might cause `lockPiece` to be called again? No, because `currentPiece` is now a new piece. If it collides immediately, `gameOver` is true. The loop won't try to move it. Good. Now, the `updateUI` function. I call it in `startGame` and `lockPiece`. Good. Now, the `drawNext` function. It uses `nextPiece` which is an index. Good. Now, I need to make sure the canvas is focused for keyboard events. The document listener catches keydown regardless of focus. Good. Now, the requirement: "The arrow keys and the space bar must not scroll the page." I prevent default on ArrowLeft, ArrowRight, ArrowUp, ArrowDown, and Space. Good. But what about the scroll when the game is not started and the user presses arrow keys? My keydown listener prevents default on all keys when not started. So no scrolling. Good. Now, the requirement: "Before the game starts, show the controls on the page." My overlay shows controls. Good. Now, the requirement: "The game starts when the player clicks the page or presses any key." My document listeners handle this. Good. Now, the requirement: "When a new piece cannot enter the grid, show a game over message on the page." My `lockPiece` checks if the new piece collides. If so, `gameOver = true` and `showOverlay()`. Good. Now, the requirement: "The player can start a new game with the Enter key or a click." My keydown listener checks for Enter when gameOver. My click listener checks for gameOver. Good. Now, the requirement: "Show every message on the page itself. Do not use alert, confirm or prompt." I use DOM manipulation. Good. Now, the requirement: "Sound is optional. If the game has sound, it must stay off until the player turns it on." I have no sound. Good. Now, the requirement: "Keep all game state in memory. Do not use localStorage, sessionStorage, IndexedDB or cookies." I use variables. Good. Now, the requirement: "The whole page must fit in a frame 800 pixels wide and 640 pixels high." My CSS sets body width/height to 800x640. Good. Now, the requirement: "Put all CSS and JavaScript inline in the file. Do not load any external scripts, fonts, images or other files, and do not make network requests." I have no external resources. Good. Now, the requirement: "Do not use the word 'Tetris' anywhere in the file." I need to verify. I'll search my text: I used "Falling Blocks". No "Tetris". Good. One potential issue: the `PIECES` array uses colors. I should make sure they are distinct. Another issue: the `drawBlock` function draws bevels. For the ghost, the bevels will also be alpha'd. That's fine. Now, let me think about the `clearLines` function again. When I do `board.splice(y, 1)`, the array length decreases by 1. Then `board.unshift(new Array(10).fill(0))` adds a row at the top. The array length is back to 20. The indices shift. The `y++` ensures we check the same index again because the row that was above has now shifted down to index `y`. This is correct. But there's a subtle bug: if we clear two consecutive lines, say y=19 and y=18. When y=19, we clear it. `board` now has 19 rows. y becomes 20 (after y++ and loop y--). Wait, let's trace: for (let y = 19; y >= 0; y--) { if (full) { board.splice(y, 1); board.unshift(...); cleared++; y++; // y becomes 20 } // loop decrement: y-- -> y becomes 19 } So after clearing y=19, y is set to 20, then loop decrements to 19. The board now has rows 0-18 (originally 0-18, with 19 removed and new row added at top). The row originally at 18 is now at 19. We check y=19 again. Good. If we clear y=19 and y=18 (originally), after clearing y=19, we check y=19 again (which is now original 18). If it's full, we clear it. Then y becomes 20, loop decrements to 19. The board now has original 17 at index 19. We check it. Good. So the logic is correct. Now, the `dropInterval` formula: `Math.max(100, 1000 - (level - 1) * 100)`. At level 1, 1000ms. Level 2, 900ms. Level 10, 100ms. Level 11, 100ms. That's fine. But the fall speed might be too fast at high levels. 100ms per block is 10 blocks per second. That's reasonable. Now, the `score` formula: `cleared * 100 * level`. For 1 line at level 1: 100. 4 lines at level 1: 400. Standard is 800 for 4 lines. But it's fine. Now, I need to ensure that the `nextPiece` is drawn correctly. The `drawNext` function uses `PIECES[nextPiece].shape`. This is the initial shape. Good. Now, one more thing: the `currentPiece` might have `y` negative. When drawing, `(currentPiece.y + y) * BLOCK_SIZE` could be negative. That's fine, it will be drawn off-screen. But the ghost calculation handles it. Now, the `collide` function: when checking if a piece can move down, if `by >= 20`, it's collision. But if `by < 0`, it's not collision with board. However, if the piece is at y=-2 and we move down to y=-1, the blocks are still above the board. That's allowed. But the piece should not be able to move down if it's already at the bottom. The check `by >= 20` catches when a block would be at y=20 or below. But what about when the piece is at y=19 and a block is at y=19 (the bottom row). Moving down would put it at y=20, which is collision. Good. But what if the piece is at y=18 and a block is at y=19 (because the piece is 4 tall). Moving down to y=19 would put that block at y=20? No, if the piece is at y=18, its blocks are at y=18,19,20,21? Wait, the piece matrix is 4x4. If the piece is at y=18, the blocks are at y=18 + matrix_row. If matrix_row is 3, then y=21. That would be out of bounds. But the piece should not be able to be at y=18 if it has blocks at row 3, because that would be y=21 which is >= 20. So the collision check prevents that. The piece will lock before it goes that low. Actually, the piece locks when it can't move down. So it will be at the highest position where moving down collides. So its blocks will be at y <= 19. Good. Now, I think the code is solid. Let me write the final HTML file. One more check: the `overlay` content. When game is over, I show "Game Over" and final score. The button says "Play Again". When not started, I show controls and "Start Game". When paused, I show "Paused" and no button. The `showOverlay` function sets `btn.style.display = 'block'` for game over and not started. For paused, it sets `btn.style.display = 'none'`. Good. But initially, the overlay is visible with controls. The `startGame` hides it. Good. Now, the `click` listener: if the game is not started, clicking starts it. If the game is over, clicking restarts it. If the game is running and not over, clicking does nothing. Good. But what if the user clicks on the "Start Game" button? The button is inside the overlay. The document click listener will fire. It will call `startGame`. That's fine. The button doesn't need its own onclick. However, there is a potential issue: the `overlay` div has `display: flex` and covers the whole page. Clicking on it will trigger the document click listener. That's fine. Now, the `keydown` listener: when the game is not started, any key starts it. But if the user presses, say, 'Enter', it starts the game. Then the game is running. If the user presses 'Enter' again while running, nothing happens (since `gameOver` is false and `paused` is false, and 'Enter' is not handled). That's fine. Now, I need to make sure that the `P` key works for pause. My keydown listener handles it. Now, the `loop` function: I use `requestAnimationFrame(loop)` at the end. This creates an infinite loop. When the game is over, the loop still runs but doesn't update. It just draws. That's fine. But I could cancel it when game over. Not necessary. Now, the `lastTime` is initialized to `performance.now()` before the loop starts. In `startGame`, I reset it. Good. Now, the `fallTimer` is initialized to 0. In `startGame`, I reset it. Good. Now, the `board` is initialized as empty array. In `startGame`, I create a new board. Good. Now, the `currentPiece` and `nextPiece` are initialized in `startGame`. Good. Now, the `draw` function uses `document.getElementById('gameCanvas')`. I should cache the canvas and context to avoid repeated lookups. But for simplicity, it's fine. However, `draw` is called every frame, so repeated `getElementById` is slightly inefficient but acceptable for a contest entry. I can cache them. Let me cache: ```javascript const gameCanvas = document.getElementById('gameCanvas'); const gameCtx = gameCanvas.getContext('2d'); const nextCanvas = document.getElementById('nextCanvas'); const nextCtx = nextCanvas.getContext('2d'); ``` Then use `gameCtx` and `nextCtx` in functions. Now, the `drawBlock` function uses `ctx`. I'll pass the context. Now, the `drawNext` function uses `nextCtx`. Now, the `draw` function uses `gameCtx`. Let me update the code accordingly. Also, I should make sure the `nextCanvas` is 100x100. The `drawNext` clears it and draws. Now, the `drawGhost` function: it uses `collide` which uses `board`. Good. Now, I think everything is good. Let me write the final HTML. Wait, I need to check if I used the word "Tetris" anywhere. I'll search my mental draft: no. One more requirement: "The game must also work correctly, and every requirement below must work." I think I covered all. Let me double-check the controls: - Left and right arrow keys move the piece: `move(-1)` and `move(1)`. - Up arrow rotates: `rotate()`. - Down arrow moves it down faster: `softDrop()`. - Space bar drops it to the bottom: `hardDrop()`. - P key pauses: `togglePause()`. All good. Now, the `softDrop` is just moving down by one. The requirement says "moves it down faster". In Tetris, down arrow is soft drop (one cell at a time but faster than normal fall). Since the normal fall is on a timer, pressing down immediately moves it down one cell. That's effectively faster. Good. Now, the `hardDrop` drops to the bottom instantly. Good. Now, the `rotate` function: if rotation is not possible due to collision, it does nothing. That's acceptable. Now, the `move` function: if move is not possible, it does nothing. Good. Now, the `collide` function: checks walls, floor, and other pieces. Good. Now, the `clearLines` function: clears full rows and moves rows above down. Good. Now, the `score`, `lines`, `level` are displayed. Good. Now, the `next piece` is displayed. Good. Now, the start screen shows controls. Good. Now, the game over screen shows message. Good. Now, the page fits in 800x640. Good. Now, no external resources. Good. Now, no "Tetris". Good. I think the code is ready. Let me format it nicely. One small thing: the `overlay` initially shows controls. But the requirement says "Before the game starts, show the controls on the page." My overlay shows controls. Good. But the overlay also has a button "Start Game". The requirement says "The game starts when the player clicks the page or presses any key." So clicking the button is a click on the page, which starts the game. Good. Now, I should ensure that the `overlay` is not hidden by the `hidden` class initially. It's visible. Good. Now, the `startGame` function hides the overlay. Good. Now, the `showOverlay` function is called when game over or pause. It removes the `hidden` class. Good. Now, the `hideOverlay` function adds the `hidden` class. Good. Now, the `togglePause` function: when pausing, it shows overlay. When resuming, it hides overlay and resets `lastTime`. Good. Now, the `loop` function: when paused, it doesn't update `fallTimer`. It still draws. Good. Now, the `draw` function: draws board, ghost, current piece, next piece. Good. Now, the `drawBlock` function: draws a block with bevels. Good. Now, the `drawGhost` function: draws ghost with alpha 0.3. Good. Now, the `drawNext` function: draws next piece on the next canvas. Good. Now, the `updateUI` function: updates score, lines, level. Good. Now, the `lockPiece` function: merges piece, clears lines, updates score/level, spawns next piece, checks game over. Good. Now, the `clearLines` function: clears full lines. Good. Now, the `merge` function: adds piece to board. Good. Now, the `collide` function: checks collision. Good. Now, the `rotateMatrix` function: rotates matrix. Good. Now, the `createPiece` function: creates a piece. Good. Now, the `randomPiece` function: returns random index. Good. Now, the `move`, `rotate`, `softDrop`, `hardDrop` functions: handle input. Good. Now, the event listeners: keydown and click. Good. Now, the `startGame` and `resetGame` functions: initialize game. Good. Now, the `loop` function: game loop. Good. I think it's complete. Let me write the final HTML. One more thing: the `body` has `width: 800px; height: 640px;`. But if the browser window is smaller, there might be scrollbars. I set `overflow: hidden;` on body. Good. Also, I set `display: flex; justify-content: center; align-items: center;` on body. But the container is 800x640, so it will be centered. Good. Actually, if body is 800x640 and container is 800x640, the flex centering is redundant but harmless. Now, I'll write the final code. Wait, I need to ensure that the `nextPiece` is drawn even before the game starts? No, `draw` is only called in the loop, which starts after `startGame`. So `nextPiece` is set in `startGame`. Good. Now, the `drawNext` function uses `nextCtx`. I need to make sure `nextCtx` is defined. I'll cache it at the top. Let me write the final code with cached contexts. ```javascript const gameCanvas = document.getElementById('gameCanvas'); const gameCtx = gameCanvas.getContext('2d'); const nextCanvas = document.getElementById('nextCanvas'); const nextCtx = nextCanvas.getContext('2d'); ``` Then in `draw`, use `gameCtx`. In `drawNext`, use `nextCtx`. Now, the `drawBlock` function takes `ctx` as parameter. Now, the `drawGhost` function takes `ctx` as parameter. Now, the `draw` function: ```javascript function draw() { gameCtx.clearRect(0, 0, 300, 600); // ... drawGhost(gameCtx, currentPiece); // ... drawNext(); } ``` Now, the `drawNext` function: ```javascript function drawNext() { nextCtx.clearRect(0, 0, 100, 100); // ... } ``` Now, everything is good. One last check: the `PIECES` array. I used 7 pieces. The order doesn't matter. Now, I'll produce the final HTML. Wait, I should also handle the case where the user presses a key that is not a control key while the game is running. My keydown listener ignores it. Good. Now, the `preventDefault` on `ArrowDown` prevents scrolling. Good. Now, the `preventDefault` on `Space` prevents scrolling. Good. Now, the `preventDefault` on `ArrowLeft`, `ArrowRight`, `ArrowUp` prevents scrolling. Good. Now, the `preventDefault` on any key when not started prevents scrolling. Good. Now, the `preventDefault` on `Enter` when game over prevents newline in any input? There are no inputs. But it's fine. Now, I think it's complete. Let me write the final HTML file. [answer]Move: Left / Right Arrows
Rotate: Up Arrow
Soft Drop: Down Arrow
Hard Drop: Space
Pause: P
Restart: Enter or Click