[reasoning, returned separately by llama-server] The user wants a complete falling-block puzzle game (Tetris clone) in a single self-contained HTML file. Let me go through all requirements carefully: 1. 10x20 grid, 7 standard tetrominoes. 2. Pieces fall on their own and speed up as lines cleared. 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. Before game starts, show controls. Game starts on click or key press. 9. Game over message when new piece can't enter. New game with Enter or click. 10. All messages on page, no alert/confirm/prompt. 11. Sound optional, must stay off until player turns on. 12. No localStorage/sessionStorage/IndexedDB/cookies. 13. Frame 800x640. 14. All CSS/JS inline, no external resources. 15. Do not use the word "Tetris" anywhere. I need to make it visually impressive and fun. Since I can't use external images, I'll use CSS for graphics, maybe canvas for rendering. Canvas is good for smooth animation and effects. Let me design: - Canvas for the game board (10x20 grid). - Side panel for next piece, score, lines, level. - Visual effects: particles on line clear, ghost piece, smooth movement (lerp or CSS transitions? Canvas with interpolation is better). - Colors for each piece. - Sound: I can use Web Audio API for simple beeps, but must be off until user enables. I'll add a sound toggle button that starts off. Wait, requirement: "Sound is optional. If the game has sound, it must stay off until the player turns it on." So I can include sound but it must be off by default. I'll add a toggle. Let me think about the visual style: - Dark background with neon grid lines. - Pieces with glow/shadow. - Particle effects when lines clear. - Smooth falling animation (interpolate between grid positions). - Next piece preview in a small canvas. - Hold piece? Not required, but could add. Let's stick to requirements but maybe add hold for polish? The requirement says 7 standard pieces, doesn't forbid hold. But to keep it clean and ensure correctness, I'll focus on core mechanics with high polish. Actually, to be safe and impressive, I'll implement: - Canvas rendering with requestAnimationFrame. - Fixed time step for game logic, interpolated rendering for smooth movement. - Ghost piece (where it would land). - Particles on line clear. - Screen shake? Maybe too much. - Score, lines, level, next piece. - Controls overlay at start. - Game over overlay. - Pause overlay. Grid: 10 columns, 20 rows. Cell size: maybe 24px? Canvas width 240px, height 480px. Centered in 800x640 frame. Side panel: 300px wide. Let's calculate layout: - Canvas: 10 * 24 = 240px wide, 20 * 24 = 480px tall. - Add some borders. - Side panel to the right. - Total width maybe 600px, centered. - Height 480px + margins fits in 640. Wait, 800x640 frame. I can make the game area larger. Let's say cell size 28px -> 280x560. That's nice. Pieces: 7 standard tetrominoes: I, O, T, S, Z, J, L. Colors: I: cyan O: yellow T: purple S: green Z: red J: blue L: orange Rotation: Standard SRS (Super Rotation System) or simple rotation with wall kicks. For simplicity and correctness, I'll implement basic rotation with wall kicks (try rotate, if collision, try alternative positions). Actually, to keep it robust, I'll implement a simple rotate function that tries to rotate and if it collides, pushes the piece out. Or use a predefined set of rotated states for each piece with kick tables. That's more code but more accurate. Given the contest nature, I should make it feel good. I'll implement a basic rotation system with wall kicks: try to rotate clockwise, check 4 possible kick positions (0,0), (-1,0), (-1,1), (0,-1) etc. Actually standard SRS has specific kicks. I'll implement a simplified version: try rotate, if collision, try shifting up, left, right, etc. Let me define piece shapes as relative coordinates. Piece definitions: I: [[0,0],[1,0],[2,0],[3,0]] horizontal, [[1,-1],[1,0],[1,1],[1,2]] vertical O: [[0,0],[1,0],[0,1],[1,1]] T: [[1,0],[0,1],[1,1],[2,1]] etc. S: [[1,0],[2,0],[0,1],[1,1]] Z: [[0,0],[1,0],[1,1],[2,1]] J: [[0,0],[0,1],[1,1],[2,1]] L: [[2,0],[0,1],[1,1],[2,1]] Better to define each piece with its 4 rotations explicitly to avoid rotation math complexity and ensure wall kicks are handled well. Let me define pieces as arrays of rotations, each rotation is array of [x,y] offsets. I piece: 0: [[0,0],[1,0],[2,0],[3,0]] 1: [[1,-1],[1,0],[1,1],[1,2]] 2: same as 0 3: same as 1 O piece: All same: [[0,0],[1,0],[0,1],[1,1]] T piece: 0: [[1,0],[0,1],[1,1],[2,1]] 1: [[1,-1],[1,0],[2,0],[1,1]] 2: [[1,0],[0,1],[1,1],[1,2]]? Wait let's be careful. Standard T rotations: Spawn: . T . T T T Coords: (1,0), (0,1), (1,1), (2,1) Rotate CW: T . T T T . Coords: (0,0), (0,1), (1,1), (0,2)? No. Let's use a standard representation. Actually, I'll define them using a common pattern. Let me look up standard tetromino coordinates relative to center. Better approach: define shape as string matrix for each rotation, then parse. I piece: "....." ".###." "....." "....." "....." Wait, I is 4 long. Let's define each piece by its 4 rotations as arrays of (x,y) where x is -1..2 and y is -1..2 or similar. I'll use this standard set: const PIECES = [ // I [ [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:1,y:2}] ], // O [ [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}] ], // T [ [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:1,y:0},{x:2,y:0},{x:1,y:1}], [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:1,y:1}] ], // S [ [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:-1},{x:1,y:0},{x:0,y:0},{x:0,y:1}], [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:-1},{x:1,y:0},{x:0,y:0},{x:0,y:1}] ], // Z [ [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}] ], // J [ [{x:0,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:0,y:1},{x:1,y:1},{x:2,y:1},{x:2,y:2}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:1,y:2}] ], // L [ [{x:2,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:0,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:0,y:1}], [{x:1,y:-1},{x:1,y:0},{x:2,y:0},{x:2,y:1}] ] ]; Wait, I need to verify these are correct. Let me think about J piece. J (blue): Spawn: X . . X X X Coords: (0,0), (0,1), (1,1), (2,1). Yes. Rotate CW: . X X . X . . X . Coords: (1,0), (1,1), (2,1), (1,2)? No. Let's do it properly. J piece in spawn orientation: (0,0), (0,1), (1,1), (2,1) Rotate 90 deg CW around center (1,0.5)? Actually rotation is usually around a point. Standard rotation for J: 0: (0,0), (1,0), (2,0), (2,1) -- wait that's L maybe. Let me use a reliable source mentally. Tetrominoes (using 0,0 as top-left of bounding box): I: #### O: ## ## T: .T. TTT S: .ST ST. Z: Z. ZZ .Z J: J.. JJJ L: ..L LLL Now rotations: I: 0: (0,0),(1,0),(2,0),(3,0) 1: (1,0),(1,1),(1,2),(1,3) but relative to piece center? Usually we want coordinates relative to a pivot. Let's use coordinates where the piece is centered as much as possible. Actually, for collision and drawing, I can use any consistent coordinate system. Let's define each piece's blocks relative to its "center" or spawn position. The spawn position is typically x=3 (center of 10-wide grid), y=0 or y=1 (above the grid). The piece's blocks are offset from its anchor. Let me define pieces with coordinates relative to the piece's anchor point (the position we track). The anchor is typically the block at a specific location. For simplicity, I'll define coordinates such that (0,0) is a logical reference, and when spawning, I place the piece at (3, 0) or (3, 1) and the blocks appear at anchor + offset. But for rotation, it's easier if the coordinates are centered. Let me define each piece shape as a set of (x,y) offsets from the piece's center of rotation. I'll use a standard set from a known implementation. Here's a standard set I recall: const shapes = [ // I [ [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:1,y:2}] ], // O [ [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}] ], // T [ [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:1,y:0},{x:2,y:0},{x:1,y:1}], [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:1,y:1}] ], // S [ [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:-1},{x:1,y:0},{x:0,y:0},{x:0,y:1}], [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:-1},{x:1,y:0},{x:0,y:0},{x:0,y:1}] ], // Z [ [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}] ], // J [ [{x:0,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:-1},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:0,y:1},{x:1,y:1},{x:2,y:1},{x:2,y:2}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:1,y:2}] ], // L [ [{x:2,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:0,y:-1},{x:0,y:0},{x:1,y:0},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:0,y:1}], [{x:1,y:-1},{x:1,y:0},{x:2,y:0},{x:2,y:1}] ] ]; Let me verify J rotation 1: Spawn J: X.. XXX Coords: (0,0), (0,1), (1,1), (2,1). This matches my J[0]. Rotate CW: .XX .X. .X. Coords relative to original: (1,0), (2,0), (1,1), (1,2)? No. If we rotate the matrix: X.. -> .X. XXX -> XX. Wait, rotating the shape: Original: (0,0) (0,1) (1,1) (2,1) After 90 deg CW rotation around some center, it becomes: . X X X . X Which is (1,0), (0,1), (1,1), (1,2). But my J[1] is (1,-1),(1,0),(1,1),(2,1). That doesn't look right. Let me reconsider. The coordinates I listed might be using a different anchor. Let's not worry about exact standard rotation as long as it's a valid tetromino and rotates consistently. The player won't notice minor differences if it feels right. But I should ensure rotations are valid (4 connected blocks). Actually, I can generate rotations programmatically from a base shape to avoid errors. But wall kicks are harder. Alternative: Use a well-known library-like definition. Let me define pieces using the "standard" relative coordinates from the classic Tetris guidance. I'll use this set (from many implementations): const PIECES = [ // I [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}] ], // O [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}] ], // T [ [{x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 1, y: 1}], [{x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 1, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 1, y: 1}] ], // S [ [{x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 0, y: 0}, {x: 0, y: 1}], [{x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 0, y: 0}, {x: 0, y: 1}] ], // Z [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: -1}, {x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: -1}, {x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}] ], // J [ [{x: 0, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 2, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}] ], // L [ [{x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 0, y: -1}, {x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}], [{x: 1, y: -1}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 2, y: 1}] ] ]; Wait, I need to check if these are actually valid rotations. Let's check J[1]: (1,-1), (1,0), (1,1), (2,1). This is: . X . X . X X X That's not a J piece. That's weird. Let me instead define pieces using a simple string-based rotation system. I'll define the 4 states for each piece manually, ensuring they are correct. Standard tetrominoes in their 4 rotations (using coordinates where x is horizontal, y is vertical, and the piece is placed such that these are offsets from the top-left of its bounding box or center): Actually, I'll use the definition from the "Tetris Guidelines" which is widely used. Piece definitions (relative to center of rotation, using matrix coordinates): I: 0: (0,0), (1,0), (2,0), (3,0) -> but this is not centered. Better: use coordinates relative to a pivot point. Let's use the "Super Rotation System" kick tables but simplified. You know what, to save time and ensure correctness, I'll define each piece's 4 rotations as hardcoded arrays that I know are correct. Let me derive them carefully. I'll use a coordinate system where (0,0) is the top-left of the piece's bounding box in spawn orientation. But for rotation, I'll just define the 4 shapes manually. Spawn orientations (top-left is (0,0)): I (cyan): #### Coords: (0,0), (1,0), (2,0), (3,0) O (yellow): ## ## Coords: (0,0), (1,0), (0,1), (1,1) T (purple): .T. TTT Coords: (1,0), (0,1), (1,1), (2,1) S (green): .ST ST. Coords: (1,0), (2,0), (0,1), (1,1) Z (red): Z. ZZ .Z Coords: (0,0), (1,0), (1,1), (2,1) J (blue): J.. JJJ Coords: (0,0), (0,1), (1,1), (2,1) L (orange): ..L LLL Coords: (2,0), (0,1), (1,1), (2,1) Now rotations (90 deg clockwise): I vertical: ..X.. ..X.. ..X.. ..X.. Coords: (1,0), (1,1), (1,2), (1,3) if we keep top-left. But to make it consistent, let's shift so min x and min y are 0. Actually, for collision detection, absolute offsets don't matter as long as they are consistent. But for rotation, we need to know the shape. Let's define each piece as an array of 4 rotation arrays. I'll compute them by rotating the spawn shape. Rotation function: given a set of (x,y), rotate 90 deg CW: (x,y) -> (y, -x). Then normalize by subtracting min x and min y so it fits in a bounding box starting at 0. Let's do this for each piece. I spawn: (0,0),(1,0),(2,0),(3,0) Rotate CW: (0,0),(0,-1),(0,-2),(0,-3). Normalize y: add 3 -> (0,3),(0,2),(0,1),(0,0). So vertical: (0,0),(0,1),(0,2),(0,3). But x is 0 for all. That's a vertical line at x=0. Rotate again: (0,0),(-1,0),(-2,0),(-3,0). Normalize x: add 3 -> (3,0),(2,0),(1,0),(0,0). Horizontal again. So I piece rotations: 0: [(0,0),(1,0),(2,0),(3,0)] 1: [(0,0),(0,1),(0,2),(0,3)] 2: [(0,0),(1,0),(2,0),(3,0)] 3: [(0,0),(0,1),(0,2),(0,3)] But this means the piece is always at the left edge of its bounding box. When we place it at (3,0), the blocks are at (3,0),(4,0)... which is fine. But the center of rotation is off. For wall kicks, it might be okay if we handle it. Actually, for a better feel, I should center the pieces. But it's not strictly required. Let's keep it simple: use the normalized coordinates after rotation. The piece will spawn at x=3 (or centered) and the blocks will be at anchor + offset. Wait, if I spawn I horizontally at x=3, blocks are at 3,4,5,6. That's fine. If I rotate to vertical, blocks are at x=3, y=0,1,2,3. That's fine. But the rotation pivot is at (0,0) of the piece, which is a corner. This might cause weird wall kicks. However, for a simple implementation, we can just try to rotate and if collision, try to move the piece. Let's use a simpler approach: define the 4 rotations explicitly with coordinates that are somewhat centered. I'll use these (from a reliable mental model): I: 0: [{-1,0},{0,0},{1,0},{2,0}] 1: [{0,-1},{0,0},{0,1},{0,2}] 2: [{-1,0},{0,0},{1,0},{2,0}] 3: [{0,-1},{0,0},{0,1},{0,2}] O: All: [{0,0},{1,0},{0,1},{1,1}] T: 0: [{0,0},{1,0},{2,0},{1,1}] 1: [{1,0},{1,1},{1,2},{0,1}] 2: [{1,0},{0,1},{1,1},{2,1}]? No. Let's do T properly. Spawn T: .T. TTT Centered: (-1,0),(0,0),(1,0),(0,1) Rotate CW: .X. .X. XX. Wait. Original matrix: . X . X X X Rotate 90 CW: X X X . X . Which is (-1,-1),(0,-1),(0,0),(0,1)? Let's use matrix rotation. Matrix: [0,1,0] [1,1,1] Rotate CW: [1,0] [1,1] [1,0] Coords: (0,0),(0,1),(0,2),(1,1). Relative to center? Let's just use bounding box coords. I think I'm overcomplicating. Let me use a known correct set from a simple Tetris implementation. I'll define them as follows (these are common): const PIECES = [ // I [ [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:0},{x:1,y:1},{x:1,y:2},{x:1,y:3}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:3,y:0}], [{x:1,y:0},{x:1,y:1},{x:1,y:2},{x:1,y:3}] ], // O [ [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}], [{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}] ], // T [ [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:0},{x:1,y:1},{x:2,y:1},{x:1,y:2}], [{x:1,y:0},{x:0,y:1},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:1,y:1}] ], // S [ [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:0},{x:1,y:1},{x:0,y:1},{x:0,y:2}], [{x:1,y:0},{x:2,y:0},{x:0,y:1},{x:1,y:1}], [{x:1,y:0},{x:1,y:1},{x:0,y:1},{x:0,y:2}] ], // Z [ [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:0},{x:1,y:1},{x:2,y:1},{x:2,y:2}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:2,y:1}], [{x:1,y:0},{x:1,y:1},{x:2,y:1},{x:2,y:2}] ], // J [ [{x:0,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:1,y:0},{x:1,y:1},{x:1,y:2},{x:2,y:2}], [{x:0,y:1},{x:1,y:1},{x:2,y:1},{x:2,y:2}], [{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:1,y:2}] ], // L [ [{x:2,y:0},{x:0,y:1},{x:1,y:1},{x:2,y:1}], [{x:0,y:0},{x:0,y:1},{x:0,y:2},{x:1,y:2}], [{x:0,y:0},{x:1,y:0},{x:2,y:0},{x:0,y:1}], [{x:1,y:0},{x:1,y:1},{x:1,y:2},{x:2,y:0}] ] ]; Let me verify J[1]: (1,0),(1,1),(1,2),(2,2). This is: .X. .X. .X. ..X That's an L shape, not J. Hmm. Let me check J spawn: (0,0),(0,1),(1,1),(2,1). Matrix: X.. .XX Wait, that's: Row 0: X at (0,0) Row 1: X at (0,1), (1,1), (2,1) So: X.. XXX Rotate CW: .XX .X. .X. Which is (1,0),(2,0),(1,1),(1,2). So J[1] should be [(1,0),(2,0),(1,1),(1,2)]. Let me recompute all rotations properly using matrix rotation and normalization. I'll write a mental rotation function: Given a set of cells, to rotate 90 deg CW: new_x = y new_y = -x Then normalize by subtracting min(new_x) and min(new_y). Piece I spawn: (0,0),(1,0),(2,0),(3,0) Rotate: (0,0),(0,-1),(0,-2),(0,-3) Normalize y (+3): (0,3),(0,2),(0,1),(0,0) -> sorted: (0,0),(0,1),(0,2),(0,3) Rotate again: (0,0),(-1,0),(-2,0),(-3,0) Normalize x (+3): (3,0),(2,0),(1,0),(0,0) -> (0,0),(1,0),(2,0),(3,0) So I: 0: [(0,0),(1,0),(2,0),(3,0)] 1: [(0,0),(0,1),(0,2),(0,3)] 2: [(0,0),(1,0),(2,0),(3,0)] 3: [(0,0),(0,1),(0,2),(0,3)] Piece O spawn: (0,0),(1,0),(0,1),(1,1) Rotate: (0,0),(0,-1),(1,0),(1,-1) Normalize y (+1): (0,1),(0,0),(1,1),(1,0) -> (0,0),(0,1),(1,0),(1,1) Same shape. So all rotations same. Piece T spawn: (1,0),(0,1),(1,1),(2,1) Matrix: . X . X X X Rotate CW: X X X . X . Cells: (0,0),(1,0),(0,1),(0,2) Normalize: already min 0. So T[1]: [(0,0),(1,0),(0,1),(0,2)] Rotate again (180 from spawn): Original rotated 180: X X X . X . Cells: (0,0),(1,0),(2,0),(1,1) So T[2]: [(0,0),(1,0),(2,0),(1,1)] Rotate again (270 CW / 90 CCW): .X. .X. XX. Cells: (1,0),(1,1),(0,2),(1,2) Normalize: (0,0),(0,1),(1,2),(1,1)? Wait. From T[2] rotate CW: (0,0)->(0,0) (1,0)->(0,-1) (2,0)->(0,-2) (1,1)->(1,-1) Normalize y (+2): (0,2),(0,1),(0,0),(1,1) So T[3]: [(0,0),(0,1),(0,2),(1,1)] Let's list T: 0: [(1,0),(0,1),(1,1),(2,1)] 1: [(0,0),(1,0),(0,1),(0,2)] 2: [(0,0),(1,0),(2,0),(1,1)] 3: [(0,0),(0,1),(0,2),(1,1)] Check T[1]: X X X . X . That's a T rotated. Yes. Piece S spawn: (1,0),(2,0),(0,1),(1,1) Matrix: . X X X X . Rotate CW: X . X X . X Cells: (0,0),(0,1),(1,1),(1,2) Normalize: (0,0),(0,1),(1,1),(1,2) So S[1]: [(0,0),(0,1),(1,1),(1,2)] Rotate again (180): X X . . X X Cells: (0,0),(1,0),(1,1),(2,1) So S[2]: [(0,0),(1,0),(1,1),(2,1)] Rotate again: . X X X X . Cells: (1,0),(0,1),(1,1),(0,2) Normalize: (0,0),(1,1),(1,0),(0,2) -> sorted: (0,0),(0,2),(1,0),(1,1) Wait, let's do properly. From S[2] rotate CW: (0,0)->(0,0) (1,0)->(0,-1) (1,1)->(1,-1) (2,1)->(1,-2) Normalize y (+2): (0,2),(0,1),(1,1),(1,0) So S[3]: [(0,0),(0,1),(1,0),(1,1)]? No, that's O. Wait: (0,2),(0,1),(1,1),(1,0). That's: . X X X X . Which is S rotated 270. Yes. So S[3]: [(0,1),(0,2),(1,0),(1,1)] Let's list S: 0: [(1,0),(2,0),(0,1),(1,1)] 1: [(0,0),(0,1),(1,1),(1,2)] 2: [(0,0),(1,0),(1,1),(2,1)] 3: [(0,1),(0,2),(1,0),(1,1)] Piece Z spawn: (0,0),(1,0),(1,1),(2,1) Matrix: X X . . X X Rotate CW: . X X X X . Cells: (1,0),(0,1),(1,1),(0,2) Normalize: (0,0),(1,1),(1,0),(0,2) -> (0,0),(0,2),(1,0),(1,1) Wait: (1,0),(0,1),(1,1),(0,2). That's: .X. XX. .X. Which is Z rotated. Yes. Z[1]: [(0,0),(0,2),(1,0),(1,1)]? No, the cells are (1,0),(0,1),(1,1),(0,2). Let's keep as is: [(0,1),(1,0),(1,1),(0,2)]. Rotate again (180): . X X X X . Cells: (1,0),(2,0),(0,1),(1,1) Z[2]: [(0,1),(1,0),(1,1),(2,0)]? Wait, that's same as spawn but mirrored? No. Spawn Z: X X . . X X 180 rot: . X X X X . Which is actually S shape! But Z rotated 180 should look like Z again? No, Z rotated 180 is still Z. Wait: Z: XX. .XX Rotate 180: .XX XX. That's S! No, that's not right. Z rotated 180 is: .XX XX. Which is indeed S? No, S is: .XX XX. Yes! So Z rotated 180 is S? That can't be. Let me draw Z: Z Z .Z Z Wait, standard Z: Z. ZZ .Z That's: Row0: Z at (0,0) Row1: Z at (1,0), (1,1)? No. Standard Z tetromino: Z Z . Z Z No, that's 4 blocks: (0,0), (1,0), (1,1), (2,1). Matrix: Z Z . . Z Z Rotate 180: . Z Z Z Z . Which is: . Z Z Z Z . That's the S piece! But Z and S are mirror images. Rotating Z 180 degrees gives: Original: XX. .XX 180: .XX XX. Yes, that's S. But in Tetris, Z rotated 180 should still be Z (it's symmetric under 180? No, Z is not symmetric under 180. Wait: Z: XX. .XX Rotate 180: .XX XX. That's S. But S is: .XX XX. Yes. So Z rotated 180 is S? That means Z and S are the same piece rotated? No, they are distinct pieces. But if you rotate Z 180, you get a shape that looks like S. However, in Tetris, the Z piece rotated 180 is still considered Z, but it looks like S. Wait, no: Z piece: XX. .XX If you rotate this 180 degrees around its center, you get: .XX XX. Which is indeed the S shape. But since Z and S are chiral, rotating Z 180 gives a shape that is congruent to S? No, let's think. Z coordinates: (0,0),(1,0),(1,1),(2,1). Rotate 180 around center (1,0.5): (0,0) -> (2,1) (1,0) -> (1,1) (1,1) -> (1,0) (2,1) -> (0,0) So the set is {(2,1),(1,1),(1,0),(0,0)} which is the same as original! Because it's symmetric under 180? Let's check: original has (0,0),(1,0),(1,1),(2,1). The rotated set is {(0,0),(1,0),(1,1),(2,1)}. Yes! It's the same set. So Z is symmetric under 180 rotation. My matrix visualization was wrong. Matrix of Z: Row0: X X . Row1: . X X Rotate 180: Row0: . X X Row1: X X . But that's a different arrangement. However, the set of coordinates after 180 rotation (x,y)->(2-x, 1-y) if bounding box is 3x2: (0,0)->(2,1) (1,0)->(1,1) (1,1)->(1,0) (2,1)->(0,0) Set: {(2,1),(1,1),(1,0),(0,0)} = {(0,0),(1,0),(1,1),(2,1)}. Same set! So yes, Z is 180-symmetric. The matrix looks different because I'm not translating back to origin. After rotation, the bounding box might shift. Okay, this is getting too bogged down. I'll use a predefined set that I know works. I'll use the following definitions which are standard in many simple Tetris clones: const PIECES = [ // I [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}, {x: 1, y: 3}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}, {x: 1, y: 3}] ], // O [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}] ], // T [ [{x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 1, y: 2}], [{x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 1, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 1, y: 1}] ], // S [ [{x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 0, y: 1}, {x: 0, y: 2}], [{x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 0, y: 1}, {x: 0, y: 2}] ], // Z [ [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 2, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 2, y: 2}] ], // J [ [{x: 0, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}, {x: 2, y: 2}], [{x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 2, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}] ], // L [ [{x: 2, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}, {x: 2, y: 1}], [{x: 0, y: 0}, {x: 0, y: 1}, {x: 0, y: 2}, {x: 1, y: 2}], [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}, {x: 1, y: 2}, {x: 2, y: 0}] ] ]; Let me verify J[1]: (1,0),(1,1),(1,2),(2,2). Matrix: .X. .X. .X. ..X That's an L shape, not J. But J rotated should be: .X. .X. XX. Which is (1,0),(1,1),(0,2),(1,2). So my J[1] is wrong. I think the safest is to define pieces using a simple function that generates rotations from a base shape using matrix rotation, and then I don't have to manually verify each one. I can write a helper `rotateShape(shape)` that rotates coordinates 90 deg CW and normalizes. Then for each piece, I define the spawn shape and generate the 4 rotations. But wall kicks with generated rotations might be okay if I just try to rotate and if collision, try to adjust position. Let's do this: - Define `SHAPES` as an array of 7 base shapes (spawn orientation). - `getRotations(shape)` generates 4 rotations by applying rotate 90 deg CW repeatedly. - Each rotation is an array of {x,y}. Base shapes (using coordinates where min x=0, min y=0): I: [[0,0],[1,0],[2,0],[3,0]] O: [[0,0],[1,0],[0,1],[1,1]] T: [[1,0],[0,1],[1,1],[2,1]] S: [[1,0],[2,0],[0,1],[1,1]] Z: [[0,0],[1,0],[1,1],[2,1]] J: [[0,0],[0,1],[1,1],[2,1]] L: [[2,0],[0,1],[1,1],[2,1]] Rotate function: function rotate(points) { return points.map(p => ({x: p.y, y: -p.x})); } Then normalize: find minX, minY, subtract. Let's compute I: Spawn: (0,0),(1,0),(2,0),(3,0) Rot1: (0,0),(0,-1),(0,-2),(0,-3) -> normalize y: (0,3),(0,2),(0,1),(0,0) -> (0,0),(0,1),(0,2),(0,3) Rot2: (0,0),(-1,0),(-2,0),(-3,0) -> normalize x: (3,0),(2,0),(1,0),(0,0) -> (0,0),(1,0),(2,0),(3,0) Rot3: same as Rot1. So I rotations: horizontal, vertical, horizontal, vertical. Good. O: Spawn: (0,0),(1,0),(0,1),(1,1) Rot1: (0,0),(0,-1),(1,0),(1,-1) -> normalize y: (0,1),(0,0),(1,1),(1,0) -> (0,0),(0,1),(1,0),(1,1). Same. All same. Good. T: Spawn: (1,0),(0,1),(1,1),(2,1) Rot1: (0,-1),(1,0),(1,-1),(1,-2) -> normalize: add (0,2) to y? min y is -2, min x is 0. (0,1),(1,2),(1,1),(1,0) -> sorted: (0,1),(1,0),(1,1),(1,2). So T[1]: [(0,1),(1,0),(1,1),(1,2)]. Matrix: .X. XXX .X. Wait, that's: (1,0) is top middle. (0,1),(1,1),(2,1)? No, we have (0,1),(1,0),(1,1),(1,2). That's: .X. X.X .X. Which is not T. Something is wrong with my rotation math. Let's recalculate T rotation. Spawn T: (1,0), (0,1), (1,1), (2,1). Rotate 90 CW: (x,y) -> (y, -x). (1,0) -> (0, -1) (0,1) -> (1, 0) (1,1) -> (1, -1) (2,1) -> (1, -2) Points: (0,-1), (1,0), (1,-1), (1,-2). Normalize: min x=0, min y=-2. Subtract min: (0,1), (1,2), (1,1), (1,0). So points: (0,1), (1,0), (1,1), (1,2). This is: Row0: . X Row1: X X Row2: . X Which is: .X XX .X That's not a T. It's a different shape. What happened? Ah, the issue is that the spawn shape I chose for T is not centered at (0,0). When I rotate, the shape orbits around (0,0), which is a corner of the bounding box, not the center. This causes the shape to swing wide. To fix this, I should center the shapes before rotating, or use a rotation pivot. But for simplicity, I can just define the 4 rotations manually for each piece. It's only 7 pieces * 4 rotations = 28 arrays. I can get them right. Let me look up standard tetromino rotation coordinates. I'll use the ones from the "tetromino" npm package or similar. Standard definitions (using x,y where x is column, y is row): I: 0: [ [0,0], [1,0], [2,0], [3,0] ] 1: [ [1,0], [1,1], [1,2], [1,3] ] 2: [ [0,0], [1,0], [2,0], [3,0] ] 3: [ [1,0], [1,1], [1,2], [1,3] ] O: All: [ [0,0], [1,0], [0,1], [1,1] ] T: 0: [ [1,0], [0,1], [1,1], [2,1] ] 1: [ [1,0], [1,1], [2,1], [1,2] ] 2: [ [1,0], [0,1], [1,1], [1,2] ] 3: [ [0,0], [1,0], [2,0], [1,1] ] Let's verify T[1]: (1,0),(1,1),(2,1),(1,2). Matrix: .X. XX. .X. That's: Row0: . X . Row1: X X . Row2: . X . That's not T. T rotated should be: .X. XX. .X. Wait, that IS a T rotated! Let's see: Original T: .T. TTT Rotate CW: .T. TT. .T. No. Original: . X . X X X Rotate 90 CW: X X X . X . Which is: X X X . X . Coords: (0,0),(1,0),(0,1),(0,2). So T[1] should be [(0,0),(1,0),(0,1),(0,2)]. Let's use the matrix method properly. I'll define each piece by its spawn matrix (list of strings), then write a function to generate rotations from the matrix. This is foolproof. Spawn matrices: I: "...." "####" "...." "...." O: ".##." ".##." "...." "...." T: ".#.." "###." "...." "...." S: ".##." "##.." "...." "...." Z: "##.." ".##." "...." "...." J: "#..." "###." "...." "...." L: "...#" "###." "...." "...." Now, to rotate a matrix 90 deg CW: newMatrix[i][j] = oldMatrix[n-1-j][i] Or for coordinates: collect all (x,y) where char is block. Rotate: (x,y) -> (y, width-1-x). Then normalize. Let's implement this in code. I'll define the spawn shapes as 2D arrays of booleans, then a function `shapeFromMatrix(matrix)` that returns the coordinates. Then `rotateShape(coords, width, height)` that rotates the coordinate set. Actually, I can just hardcode the 4 rotations for each piece by reasoning. But to avoid errors, I'll write the code to generate them from matrices at initialization. Since it's a one-time setup, it's fine. Let's do that in the code: const SPAWN_SHAPES = [ // I [ [0,0,0,0], [1,1,1,1], [0,0,0,0], [0,0,0,0] ], // O [ [0,1,1,0], [0,1,1,0], [0,0,0,0], [0,0,0,0] ], // T [ [0,1,0,0], [1,1,1,0], [0,0,0,0], [0,0,0,0] ], // S [ [0,1,1,0], [1,1,0,0], [0,0,0,0], [0,0,0,0] ], // Z [ [1,1,0,0], [0,1,1,0], [0,0,0,0], [0,0,0,0] ], // J [ [1,0,0,0], [1,1,1,0], [0,0,0,0], [0,0,0,0] ], // L [ [0,0,1,0], [1,1,1,0], [0,0,0,0], [0,0,0,0] ] ]; Then a function to get all rotations: function getRotations(matrix) { const rotations = []; let current = matrix; for (let r = 0; r < 4; r++) { rotations.push(matrixToCoords(current)); current = rotateMatrix(current); } return rotations; } function matrixToCoords(matrix) { const coords = []; for (let y = 0; y < matrix.length; y++) { for (let x = 0; x < matrix[y].length; x++) { if (matrix[y][x]) coords.push({x, y}); } } return coords; } function rotateMatrix(matrix) { const rows = matrix.length; const cols = matrix[0].length; const result = []; for (let x = 0; x < cols; x++) { result[x] = []; for (let y = rows - 1; y >= 0; y--) { result[x].push(matrix[y][x]); } } return result; } This will generate correct rotations. The coordinates will have min x=0, min y=0 because the matrix is trimmed? No, the matrix is 4x4 with padding. So coords might have x from 0 to 3, y from 0 to 3. That's fine. When we place the piece, we add the anchor position. The anchor can be (3, 0) or similar. The piece will occupy cells anchor.x + coord.x, anchor.y + coord.y. But for rotation, the pivot is at (0,0) of the matrix, which is top-left. This means when rotating, the piece will swing around the top-left corner. This can cause wall kicks issues but is manageable. To make it better, I could trim the matrix to remove empty rows/cols before storing, so the piece is more compact. But it's okay. Actually, for the I piece, the matrix is 4x4. Spawn coords: (1,0),(2,0),(3,0)? No, row 1 (index 1) has [1,1,1,1], so coords are (0,1),(1,1),(2,1),(3,1). That's fine. When we spawn at (3, 0) (anchor x=3, y=0), the blocks are at (3,1),(4,1),(5,1),(6,1). That's centered horizontally (grid is 10 wide, so 3 to 6 is center). Good. For rotation, if we rotate I, the matrix becomes vertical. Coords might be (1,0),(1,1),(1,2),(1,3) or similar. Placed at anchor (3,0), blocks at (3,0),(3,1),(3,2),(3,3). Good. The issue is that the anchor point (3,0) might not be the center of rotation. But for a simple game, we can just try to rotate at the current anchor, and if collision, try to shift the piece. Wall kick algorithm: - Try to rotate at current position. - If collision, try moving the piece by (dx, dy) in a set of kick offsets, e.g., [(0,0), (-1,0), (1,0), (0,-1), (0,1), (-1,-1), (1,-1), (-1,1), (1,1)]. - If any works, move there and set rotation. This is simple and effective. Now, game mechanics: - Grid: 10x20. Represent as 2D array or 1D array of size 200. 0 = empty, 1-7 = piece type (or color index). - Current piece: type, rotation, x, y (anchor position). - Next piece: random type. - Fall timer: piece falls every `fallInterval` ms. Speed increases with level. - Level: based on lines cleared. Level = Math.floor(lines / 10) + 1. Speed formula: 1000 - (level * 100) or something. Classic Tetris: 48 * (0.8^level) or similar. I'll use: fallInterval = Math.max(100, 1000 - (level - 1) * 100). Start at 1000ms (1 second per level). Actually classic starts at 500ms? Let's use 1000ms start, decrease by 100ms per level, min 100ms. - Input: left/right move by 1 cell. Down soft drop (increase fall speed or move down 1 cell immediately). Space hard drop (lock immediately). Up rotate. P pause. - Lock: when piece collides below or after hard drop, lock piece into grid, check line clears, spawn new piece. - Line clear: if a row is full, remove it, add score, shift rows above down. - Score: 100 * level for single, 300 * level for double, 500 * level for triple, 800 * level for tetris. Or simpler: 100 + 50*level per line. I'll use classic-ish: lines * 100 * level. - Next piece: show in side panel. - Ghost piece: show where piece would land (alpha). - Particles: on line clear, create particles at the cleared rows. Visuals: - Canvas element. - Draw grid lines. - Draw locked pieces with color and slight glow. - Draw current piece with brighter color. - Draw ghost piece with outline or lighter color. - Draw particles. - Use `requestAnimationFrame` for rendering, but game logic on timer or frame-based. Since we need smooth falling, I'll interpolate the current piece's position between grid cells. The piece has a target grid position (tx, ty) and a visual position (vx, vy) that lerps towards it. When moving left/right, it snaps or slides? Sliding is nicer. When falling, it slides down. Actually, for simplicity and to ensure correctness, I can make the piece snap to grid but use a timer for falling. However, smooth movement is more impressive. Let's do interpolation. Game state: - `pieceX`, `pieceY`: target grid coordinates (float maybe). - `renderX`, `renderY`: visual coordinates. - On move left/right, update target and start lerp. - On fall timer, increment target Y by 1. - Render draws at renderX, renderY. Collision check: - Given piece type, rotation, x, y (grid coords), check if any block is outside grid or overlaps locked cells. - Grid coordinates are integers. The piece occupies cells at x + offset.x, y + offset.y. Spawn new piece: - At x = 3 (centered), y = 0 (or y = -4 so it spawns above and falls in). Actually standard is y=0 or y=1. If y=0, the piece might be partially visible at top. I'll spawn at y = -4 (above grid) and it falls into view. But collision check must allow it. Or spawn at y=0 and if it collides, game over. Let's spawn at x=3, y=0. If the piece's blocks have y offsets that are negative, they might be above. For I vertical, offsets are (0,0),(0,1),(0,2),(0,3) if using matrix coords. So at y=0, blocks are at y=0..3. That's fine. For I horizontal, blocks at y=1. So spawn at y=0 means top of piece is at y=1. That's okay. Wait, if I spawn at y=0, and the piece has blocks at y=0, it's at the top row. That's fine. But some pieces might have blocks at y=0 and x=0..3. That's okay. Game over: when spawning a new piece, if collision at spawn position, game over. Lines cleared: - Check each row from bottom to top. If full, remove. - Add score. - Shift rows above down. - Spawn particles. Sound: - Use Web Audio API. Oscillator for simple beeps. - `soundEnabled` starts false. Button to toggle. - On line clear, move, rotate, lock, play sound if enabled. UI: - Start screen: controls text, click/key to start. - Game over screen: message, score, lines, press Enter or click to restart. - Pause screen: "Paused", press P to resume. - HUD: score, lines, level, next piece. - Sound toggle button. Layout: - Canvas centered. - Side panel on right with next piece, score, lines, level, sound button. - Overlays for start, pause, game over. Colors: - Background: #1a1a2e (dark blue) - Grid: #16213e - Piece colors: I: #00f0ff (cyan) O: #f0e000 (yellow) T: #a000f0 (purple) S: #00f000 (green) Z: #f00000 (red) J: #0000f0 (blue) L: #f0a000 (orange) I'll add glow using `shadowColor` and `shadowBlur`. Particles: - Array of particles with x, y, vx, vy, life, color. - Update and draw each frame. Next piece preview: - Small canvas or draw on main canvas? I'll draw on a separate small canvas or just draw blocks on the main canvas in the side area. Since side panel is separate, I can draw next piece using the same drawing function but at a different offset. Let's structure the HTML: ```html Block Puzzle

BLOCK PUZZLE

Use ARROWS to move and rotate.
DOWN to soft drop.
SPACE to hard drop.
P to pause.

Click or press any key to start.

``` Wait, the canvas width: grid is 10 cells. If cell size is 28px, grid is 280px. Sidebar is 200px. Total 480px. But I set canvas width 500. Let's make canvas 300x560 to have some margin. Cell size = 300/10 = 30px. Height 560/20 = 28px. Not square. Better to make canvas square cells. Let's do 280x560 (10x20 cells of 28px). Then sidebar 200px. Total width 480px. Centered in 800px. Actually, I can make the canvas larger for visual impact. Let's do cell size 32px. Canvas: 320x640. But height 640 might exceed 640 frame with borders. Let's do 300x600. 30 columns? No, 10 columns. 300/10 = 30px. 600/20 = 30px. Perfect. Canvas 300x600. Sidebar 200px. Total 500px. Fits in 800x640. Wait, 600 height + some padding fits in 640. Yes. Let's set canvas width="300" height="600". Game area: 10x20 grid, cell 30px. Now, the game loop: - `lastTime` for frame rate. - `fallTimer` accumulator. - `fallInterval` in ms. Input handling: - `keydown`: preventDefault for arrows and space. Update input state. - `keyup`: reset input state. - `mousedown`/`click`: start/restart. Game states: - `MENU`: show controls. - `PLAYING`: game running. - `PAUSED`: show pause. - `GAMEOVER`: show game over. State machine in `update()`: - If MENU, wait for start. - If PAUSED, wait for P. - If GAMEOVER, wait for Enter/click. - If PLAYING, update fall, move, lock, etc. Piece movement: - `move(dx)`: if no collision at (x+dx, y), update x. - `drop()`: if no collision at (x, y+1), y++. Else lock. - `rotate()`: try rotate. If collision, wall kick. Lock: - Add piece blocks to grid. - Check lines. - If lines cleared, clear them, add score, spawn particles. - Spawn next piece. - If new piece collides at spawn, game over. Spawn: - `currentPiece = nextPiece; nextPiece = randomPiece();` - Reset rotation to 0. - Position: x = 3, y = 0 (or y = -4 to spawn above). Let's use y = 0. But if the piece has blocks at y=0, it's at top. That's fine. However, for pieces that are tall, they might extend above. But since grid starts at y=0, blocks at y=0 are visible. I'll spawn at y = -4 so the piece appears above the grid and falls in. This looks nicer. But collision check must allow negative y. The grid is 20 rows (0-19). If y is negative, blocks with y+offset < 0 are ignored (above grid). Blocks with y+offset >= 20 are below floor (collision). Blocks with x+offset < 0 or >= 10 are wall collision. So spawn at x=3, y=-4. The piece will fall into view. Line clear: - `clearLines()`: find full rows. Remove them. Shift rows above down. Add new empty row at top. - Score: `linesCleared * 100 * level`. - Lines: add to total. Level = Math.floor(totalLines / 10) + 1. - Update fall interval. Particles: - When lines cleared, create particles at each cell of cleared rows. - Particle: x, y (pixel coords), vx, vy, life (frames), color. - Update: x += vx, y += vy, life--. Draw as small squares. Rendering: - Clear canvas. - Draw grid: for each cell, if locked, draw block with color. - Draw ghost piece: calculate where current piece would land (max y such that no collision). Draw at that position with alpha 0.3. - Draw current piece: at interpolated render position. - Draw particles. - Draw grid lines (subtle). Interpolation: - `renderX` and `renderY` track visual position. - Target is `pieceX * cellSize`, `pieceY * cellSize`. - Each frame, `renderX += (targetX - renderX) * 0.25`, same for Y. - This gives smooth sliding. But pieceX and pieceY are grid coordinates (can be float during interpolation? No, target is integer grid. Visual is float). When moving left/right, targetX changes by ±1 cell. The visual slides. When falling, targetY increases by 1 every fallInterval. Visual slides down. Hard drop (space): instantly set targetY to max possible (ghost position), lock immediately. Soft drop (down): increase fall speed temporarily or move down 1 cell immediately. I'll make it move down 1 cell immediately if possible, and also increase fall rate. Actually, classic soft drop makes it fall faster. I'll implement: if down held, fall interval is reduced (e.g., 50ms). But to keep it simple, I'll just move down 1 cell immediately on key press (with repeat). But the requirement says "down arrow key moves it down faster". So I should make it fall faster. I'll implement a `softDrop` flag that reduces fall interval. Let's implement: - `fallInterval`: normal. - `softDropInterval`: e.g., 50ms. - If down key held, use softDropInterval. But input repeat: I need to handle key repeat. I'll use a `keys` object and check in the game loop. Or use keydown/keyup to set flags, and a timer for repeat. Simpler: in the update loop, if `keys.down`, accelerate fall. Actually, for smooth control, I'll track key states: - `keys = { left: false, right: false, down: false, ... }` - On keydown, set true and preventDefault. Also handle immediate action for rotation and hard drop (to avoid repeat issues). - On keyup, set false. For movement, I can use a `moveTimer` accumulator. If left/right held, move after a delay (e.g., 100ms initial, 50ms repeat). This feels better. Let's implement movement with timers: - `moveTimer` accumulator. - `moveDelay` = 150ms initially, then 50ms. - In update, if `keys.left` and `moveTimer > moveDelay`, try move left, reset timer, set moveDelay = 50. - Same for right. For down: - `softDropTimer`. If `keys.down`, every 50ms try move down 1. For fall: - `fallTimer`. Every `fallInterval`, try move down 1. This is a solid approach. Rotation: - On keydown up (once, not repeat), try rotate. Hard drop: - On keydown space (once), set piece to ghost position and lock. Pause: - On keydown p (once), toggle pause. Game start: - On click or any keypress, if in MENU, start game. Game over restart: - On Enter or click, if in GAMEOVER, reset game. Sound: - `soundEnabled = false`. - Button toggles. - Functions: `playSound(type)` where type is 'move', 'rotate', 'lock', 'clear', 'gameover'. - Use `AudioContext` (needs user gesture? In modern browsers, AudioContext requires user interaction. But since the game starts with a click, we can init AudioContext on start. Or just create oscillator on demand. Browsers allow creating AudioContext without gesture but playing sound might be blocked. To be safe, I'll init audio on first user interaction (start button click). But the requirement says sound must stay off until player turns it on. So I'll have a button. When clicked, if `soundEnabled` becomes true, I can resume/create audio context. Actually, I can use the Web Audio API simply: ```javascript function playTone(freq, duration, type) { if (!soundEnabled) return; const ctx = new AudioContext(); const osc = ctx.createOscillator(); osc.type = type; osc.frequency.setValueAtTime(freq, ctx.currentTime); osc.connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + duration); } ``` Creating AudioContext each time is a bit heavy but okay for simple beeps. Better to create one global context on first sound enable. Let's do: ```javascript let audioCtx = null; function initAudio() { if (!audioCtx) { audioCtx = new AudioContext(); } if (audioCtx.state === 'suspended') audioCtx.resume(); } function playSound(type) { if (!soundEnabled || !audioCtx) return; initAudio(); const now = audioCtx.currentTime; const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.connect(gain); gain.connect(audioCtx.destination); if (type === 'move') { osc.frequency.value = 400; gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.05); osc.type = 'square'; osc.start(now); osc.stop(now + 0.05); } else if (type === 'rotate') { ... } else if (type === 'lock') { ... } else if (type === 'clear') { ... } else if (type === 'gameover') { ... } } ``` This is fine. Now, the "Do not use the word Tetris" requirement. I must ensure the word "Tetris" does not appear anywhere. I'll title it "BLOCK PUZZLE" or "FALLING BLOCKS". I'll avoid the word entirely. Let's write the code. Constants: ```javascript const COLS = 10; const ROWS = 20; const CELL = 30; const COLORS = [ null, '#00f0ff', // I '#f0e000', // O '#a000f0', // T '#00f000', // S '#f00000', // Z '#0000f0', // J '#f0a000' // L ]; ``` Piece shapes: I'll generate from matrices. ```javascript const SPAWN_MATRICES = [ // I [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]], // O [[0,1,1,0],[0,1,1,0],[0,0,0,0],[0,0,0,0]], // T [[0,1,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]], // S [[0,1,1,0],[1,1,0,0],[0,0,0,0],[0,0,0,0]], // Z [[1,1,0,0],[0,1,1,0],[0,0,0,0],[0,0,0,0]], // J [[1,0,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]], // L [[0,0,1,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]] ]; function getPieceRotations(matrix) { const rotations = []; let m = matrix; for (let i = 0; i < 4; i++) { rotations.push(matrixToCoords(m)); m = rotateMatrix(m); } return rotations; } function matrixToCoords(m) { const coords = []; for (let y = 0; y < m.length; y++) { for (let x = 0; x < m[y].length; x++) { if (m[y][x]) coords.push({x, y}); } } return coords; } function rotateMatrix(m) { const rows = m.length; const cols = m[0].length; const result = []; for (let x = 0; x < cols; x++) { result[x] = []; for (let y = rows - 1; y >= 0; y--) { result[x].push(m[y][x]); } } return result; } const PIECES = SPAWN_MATRICES.map(getPieceRotations); ``` This gives correct rotations. Grid: `grid = Array(ROWS).fill().map(() => Array(COLS).fill(0));` Piece object: ```javascript let piece = { type: 0, // 1-7 rot: 0, x: 3, y: -4, targetX: 3, targetY: -4, renderX: 3 * CELL, renderY: -4 * CELL }; ``` Next piece: `nextType = 1 + Math.floor(Math.random() * 7);` Collision: ```javascript function collides(piece, x, y, rot) { const shape = PIECES[piece.type - 1][rot]; for (const offset of shape) { const cx = x + offset.x; const cy = y + offset.y; if (cx < 0 || cx >= COLS || cy >= ROWS) return true; if (cy >= 0 && grid[cy][cx] !== 0) return true; } return false; } ``` Note: cy < 0 is allowed (above grid). Lock: ```javascript function lock() { const shape = PIECES[piece.type - 1][piece.rot]; for (const offset of shape) { const cx = piece.x + offset.x; const cy = piece.y + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { grid[cy][cx] = piece.type; } } clearLines(); spawn(); } ``` Spawn: ```javascript function spawn() { piece.type = nextType; nextType = 1 + Math.floor(Math.random() * 7); piece.rot = 0; piece.x = 3; piece.y = -4; piece.targetX = 3; piece.targetY = -4; // renderX/Y will interpolate if (collides(piece, piece.x, piece.y, piece.rot)) { gameOver(); } updateNext(); } ``` Wait, if we spawn at y=-4, and the piece has blocks at y=0..3, they are at -4..-1, all above grid. So no collision. As it falls, y increases. When y=0, blocks at 0..3 are in grid. Good. But for O piece, shape is (0,0),(1,0),(0,1),(1,1). At y=-4, blocks at -4,-3. Above grid. Good. Clear lines: ```javascript function clearLines() { let linesCleared = 0; for (let y = ROWS - 1; y >= 0; y--) { if (grid[y].every(cell => cell !== 0)) { grid.splice(y, 1); grid.unshift(Array(COLS).fill(0)); linesCleared++; y++; // check same row again because we shifted } } if (linesCleared > 0) { score += linesCleared * 100 * level; totalLines += linesCleared; level = Math.floor(totalLines / 10) + 1; fallInterval = Math.max(100, 1000 - (level - 1) * 100); // particles for (let y = 0; y < ROWS; y++) { // actually we need to know which rows were cleared. The above loop modifies grid. // Better to collect cleared rows first. } } } ``` I need to collect cleared rows before modifying. Let's rewrite: ```javascript function clearLines() { const cleared = []; for (let y = ROWS - 1; y >= 0; y--) { if (grid[y].every(cell => cell !== 0)) { cleared.push(y); } } if (cleared.length === 0) return 0; for (const y of cleared) { grid.splice(y, 1); grid.unshift(Array(COLS).fill(0)); // particles at this row for (let x = 0; x < COLS; x++) { spawnParticle(x * CELL + CELL/2, y * CELL + CELL/2, COLORS[grid[y+1]? ...]); } } const lines = cleared.length; score += lines * 100 * level; totalLines += lines; level = Math.floor(totalLines / 10) + 1; fallInterval = Math.max(100, 1000 - (level - 1) * 100); playSound('clear'); return lines; } ``` Particle color: use the color of the block that was there. But since we spliced, we lost it. We can store the color before splicing. Or just use white/random. Let's use the piece color that locked. But we don't have it. I'll just use a bright color like #00f0ff. Actually, we can create particles before modifying grid, using the current grid colors. ```javascript for (const y of cleared) { for (let x = 0; x < COLS; x++) { const color = COLORS[grid[y][x]]; spawnParticle(x * CELL + CELL/2, y * CELL + CELL/2, color); } grid.splice(y, 1); grid.unshift(Array(COLS).fill(0)); } ``` Ghost piece: ```javascript function getGhostY() { let y = piece.y; while (!collides(piece, piece.x, y + 1, piece.rot)) { y++; } return y; } ``` Draw function: ```javascript function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // draw grid for (let y = 0; y < ROWS; y++) { for (let x = 0; x < COLS; x++) { if (grid[y][x] !== 0) { drawBlock(x * CELL, y * CELL, COLORS[grid[y][x]]); } } } // draw ghost const ghostY = getGhostY(); const shape = PIECES[piece.type - 1][piece.rot]; for (const offset of shape) { const cx = piece.x + offset.x; const cy = ghostY + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { drawBlock(cx * CELL, cy * CELL, '#ffffff', 0.3); } } // draw current piece for (const offset of shape) { const cx = piece.x + offset.x; const cy = piece.y + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { drawBlock(piece.renderX + offset.x * CELL, piece.renderY + offset.y * CELL, COLORS[piece.type]); } } // draw particles for (const p of particles) { p.draw(); } // draw grid lines ctx.strokeStyle = 'rgba(255,255,255,0.1)'; ctx.lineWidth = 1; for (let x = 0; x <= COLS; x++) { ctx.beginPath(); ctx.moveTo(x * CELL, 0); ctx.lineTo(x * CELL, canvas.height); ctx.stroke(); } for (let y = 0; y <= ROWS; y++) { ctx.beginPath(); ctx.moveTo(0, y * CELL); ctx.lineTo(canvas.width, y * CELL); ctx.stroke(); } } ``` `drawBlock`: ```javascript function drawBlock(x, y, color, alpha = 1) { ctx.save(); ctx.globalAlpha = alpha; ctx.shadowColor = color; ctx.shadowBlur = 10; ctx.fillStyle = color; ctx.fillRect(x + 1, y + 1, CELL - 2, CELL - 2); // lighter center ctx.fillStyle = 'rgba(255,255,255,0.2)'; ctx.fillRect(x + 3, y + 3, CELL - 6, CELL - 6); ctx.restore(); } ``` Next piece preview: - Draw on a separate canvas or on the main canvas at sidebar position. Since sidebar is a div, I can overlay a small canvas. Let's create a canvas for next piece. ```html ``` Draw next piece: ```javascript function drawNext() { const ctx = nextCanvas.getContext('2d'); ctx.clearRect(0, 0, 120, 120); const shape = PIECES[nextType - 1][0]; const cell = 24; // center in 120x120 const offsetX = (120 - 4 * cell) / 2; const offsetY = (120 - 4 * cell) / 2; for (const offset of shape) { ctx.fillStyle = COLORS[nextType]; ctx.shadowColor = COLORS[nextType]; ctx.shadowBlur = 10; ctx.fillRect(offsetX + offset.x * cell + 2, offsetY + offset.y * cell + 2, cell - 4, cell - 4); } } ``` Particles: ```javascript const particles = []; function spawnParticle(x, y, color) { for (let i = 0; i < 5; i++) { particles.push({ x, y, vx: (Math.random() - 0.5) * 4, vy: (Math.random() - 0.5) * 4, life: 30 + Math.random() * 20, color }); } } function updateParticles() { for (let i = particles.length - 1; i >= 0; i--) { const p = particles[i]; p.x += p.vx; p.y += p.vy; p.life--; if (p.life <= 0) particles.splice(i, 1); } } function drawParticles() { for (const p of particles) { ctx.globalAlpha = p.life / 30; ctx.fillStyle = p.color; ctx.fillRect(p.x - 2, p.y - 2, 4, 4); } } ``` Game loop: ```javascript let lastTime = 0; let fallTimer = 0; let moveTimer = 0; let softDropTimer = 0; const MOVE_DELAY = 150; const MOVE_REPEAT = 50; const SOFT_DROP_DELAY = 50; function update(dt) { if (state !== 'PLAYING') return; fallTimer += dt; if (fallTimer >= fallInterval) { fallTimer = 0; if (!collides(piece, piece.x, piece.y + 1, piece.rot)) { piece.y++; piece.targetY = piece.y; playSound('move'); } else { lock(); } } if (keys.down) { softDropTimer += dt; if (softDropTimer >= SOFT_DROP_DELAY) { softDropTimer = 0; if (!collides(piece, piece.x, piece.y + 1, piece.rot)) { piece.y++; piece.targetY = piece.y; } } } if (keys.left) { moveTimer += dt; if (moveTimer >= (moveTimer > 500 ? MOVE_REPEAT : MOVE_DELAY)) { moveTimer = 0; if (!collides(piece, piece.x - 1, piece.y, piece.rot)) { piece.x--; piece.targetX = piece.x; playSound('move'); } } } if (keys.right) { moveTimer += dt; if (moveTimer >= (moveTimer > 500 ? MOVE_REPEAT : MOVE_DELAY)) { moveTimer = 0; if (!collides(piece, piece.x + 1, piece.y, piece.rot)) { piece.x++; piece.targetX = piece.x; playSound('move'); } } } // interpolate render position const targetX = piece.targetX * CELL; const targetY = piece.targetY * CELL; piece.renderX += (targetX - piece.renderX) * 0.2; piece.renderY += (targetY - piece.renderY) * 0.2; updateParticles(); } function loop(timestamp) { const dt = timestamp - lastTime; lastTime = timestamp; update(dt); draw(); requestAnimationFrame(loop); } ``` Input handling: ```javascript const keys = { left: false, right: false, down: false }; window.addEventListener('keydown', e => { if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'ArrowDown' || e.key === ' ') { e.preventDefault(); } if (e.key === 'ArrowLeft') keys.left = true; if (e.key === 'ArrowRight') keys.right = true; if (e.key === 'ArrowDown') keys.down = true; if (e.key === 'ArrowUp') { e.preventDefault(); if (state === 'PLAYING') rotate(); } if (e.key === ' ') { e.preventDefault(); if (state === 'PLAYING') hardDrop(); } if (e.key === 'p' || e.key === 'P') { if (state === 'PLAYING') { state = 'PAUSED'; showOverlay('pause'); } else if (state === 'PAUSED') { state = 'PLAYING'; hideOverlay(); } } if (state === 'MENU') { startGame(); } if (state === 'GAMEOVER' && e.key === 'Enter') { startGame(); } }); window.addEventListener('keyup', e => { if (e.key === 'ArrowLeft') keys.left = false; if (e.key === 'ArrowRight') keys.right = false; if (e.key === 'ArrowDown') keys.down = false; }); ``` Wait, if any key starts the game, then pressing arrow keys to move will also start the game. That's fine per requirement: "The game starts when the player clicks the page or presses any key." But once started, we don't want to restart on every key. So I need to check state. ```javascript window.addEventListener('keydown', e => { if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'ArrowDown' || e.key === ' ') { e.preventDefault(); } if (state === 'MENU') { startGame(); // don't process game keys this frame? Or process? It's okay to process. // But if they press left to start, the piece might move left immediately. // That's acceptable. } if (state === 'PLAYING') { if (e.key === 'ArrowLeft') keys.left = true; if (e.key === 'ArrowRight') keys.right = true; if (e.key === 'ArrowDown') keys.down = true; if (e.key === 'ArrowUp') rotate(); if (e.key === ' ') hardDrop(); if (e.key === 'p' || e.key === 'P') { state = 'PAUSED'; showOverlay('pause'); } } if (state === 'GAMEOVER' && e.key === 'Enter') { startGame(); } }); ``` But if state is MENU and they press left, we start game and set keys.left = true? The code above only sets keys if state === PLAYING. So it's fine. The game starts, and the key is not held. Good. Click handling: ```javascript window.addEventListener('mousedown', () => { if (state === 'MENU' || state === 'GAMEOVER') startGame(); if (state === 'PAUSED') { state = 'PLAYING'; hideOverlay(); } }); ``` Also, clicking on the canvas or page should start/restart. The requirement says "clicks the page". So any click. ```javascript document.addEventListener('click', () => { if (state === 'MENU' || state === 'GAMEOVER') startGame(); if (state === 'PAUSED') { state = 'PLAYING'; hideOverlay(); } }); ``` But we need to prevent clicking buttons from triggering game start? The start button is inside overlay. If overlay is visible, clicking it starts game. That's fine. But if we click the sound button during game, it shouldn't pause. The sound button is in sidebar. Clicking it should toggle sound. We need to check if click target is a button. ```javascript document.addEventListener('click', e => { if (e.target.tagName === 'BUTTON') return; // let buttons handle their own clicks if (state === 'MENU' || state === 'GAMEOVER') startGame(); if (state === 'PAUSED') { state = 'PLAYING'; hideOverlay(); } }); ``` Start button: ```javascript document.getElementById('start-btn').addEventListener('click', startGame); ``` Sound button: ```javascript document.getElementById('sound-btn').addEventListener('click', () => { soundEnabled = !soundEnabled; const btn = document.getElementById('sound-btn'); btn.textContent = soundEnabled ? 'Sound: ON' : 'Sound: OFF'; btn.classList.toggle('on', soundEnabled); if (soundEnabled) initAudio(); }); ``` Rotate: ```javascript function rotate() { const nextRot = (piece.rot + 1) % 4; if (!collides(piece, piece.x, piece.y, nextRot)) { piece.rot = nextRot; playSound('rotate'); } else { // wall kick: try to move piece const kicks = [[0,0], [-1,0], [1,0], [0,-1], [-1,-1], [1,-1], [-1,1], [1,1]]; for (const [dx, dy] of kicks) { if (!collides(piece, piece.x + dx, piece.y + dy, nextRot)) { piece.x += dx; piece.y += dy; piece.rot = nextRot; piece.targetX = piece.x; piece.targetY = piece.y; playSound('rotate'); return; } } } } ``` Hard drop: ```javascript function hardDrop() { const ghostY = getGhostY(); piece.y = ghostY; piece.targetY = ghostY; lock(); } ``` Lock calls spawn, which checks game over. Game over: ```javascript function gameOver() { state = 'GAMEOVER'; showOverlay('gameover'); playSound('gameover'); } ``` Overlay: ```javascript function showOverlay(type) { const overlay = document.getElementById('overlay'); overlay.classList.remove('hidden'); const title = document.querySelector('#overlay h1'); const msg = document.querySelector('#overlay p'); const btn = document.getElementById('start-btn'); if (type === 'start') { title.textContent = 'BLOCK PUZZLE'; msg.innerHTML = 'Use ARROWS to move and rotate.
' + 'DOWN to soft drop.
' + 'SPACE to hard drop.
' + 'P to pause.

' + 'Click or press any key to start.'; btn.textContent = 'Start Game'; btn.style.display = 'block'; } else if (type === 'pause') { title.textContent = 'PAUSED'; msg.textContent = 'Press P or click to resume.'; btn.style.display = 'none'; } else if (type === 'gameover') { title.textContent = 'GAME OVER'; msg.textContent = `Score: ${score} Lines: ${totalLines} Level: ${level}
Press Enter or click to restart.`; btn.textContent = 'Play Again'; btn.style.display = 'block'; } } function hideOverlay() { document.getElementById('overlay').classList.add('hidden'); } ``` Start game: ```javascript function startGame() { state = 'PLAYING'; hideOverlay(); score = 0; totalLines = 0; level = 1; fallInterval = 1000; grid = Array(ROWS).fill().map(() => Array(COLS).fill(0)); particles = []; nextType = 1 + Math.floor(Math.random() * 7); spawn(); updateHUD(); drawNext(); lastTime = performance.now(); requestAnimationFrame(loop); } ``` Wait, if we start game, we need to cancel any existing animation frame. But `loop` is recursive. We can use a flag `running` and check in loop. Or just let it run; when state is MENU, update does nothing but draw still runs. That's fine. But we need to initialize `lastTime`. Actually, simpler: only call `requestAnimationFrame(loop)` when playing. But loop needs to keep running to draw. I can have loop always running, but update only if PLAYING. Let's have `loop` always running once started. But before start, we don't need it. So: ```javascript let running = false; function loop(timestamp) { if (!running) return; const dt = timestamp - lastTime; lastTime = timestamp; update(dt); draw(); requestAnimationFrame(loop); } ``` And in startGame: `running = true; lastTime = performance.now(); requestAnimationFrame(loop);` In gameOver: `running = false;` (or let it finish, but state is GAMEOVER so update does nothing). HUD update: ```javascript function updateHUD() { document.getElementById('score').textContent = score; document.getElementById('lines').textContent = totalLines; document.getElementById('level').textContent = level; } ``` Call updateHUD when score/lines/level change. Now, the canvas size. I set width="300" height="600". But the sidebar is 200px. The container is 700px. The body is 800px. This fits. Wait, the requirement: "The whole page must fit in a frame 800 pixels wide and 640 pixels high." My body has height: 640px, width: 800px. But if content overflows, it might scroll. I set `overflow: hidden` on body. The canvas is 300x600. Sidebar 200px. Total width 500px. Height 600px + some padding. Should fit in 640. Let's adjust CSS to ensure it fits. ```css body { width: 800px; height: 640px; overflow: hidden; background: #0f0f1a; color: #fff; font-family: 'Courier New', Courier, monospace; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; } ``` Canvas: 300x600. Sidebar: 200px wide. Container: 500px. This is fine. But the game canvas height 600 might be too tall if there are margins. 600 + 40 padding = 640. Exactly fits. But borders might add. Let's make canvas 280x560 (cell 28px). Then height 560 + padding fits easily. Let's use CELL = 28. Canvas: 280x560. Sidebar 200px. Total 480px. Height 560. Fits in 640 with room. Actually, to make it more impressive, I can scale up. Let's use CELL = 30. Canvas 300x600. Height 600. Body 640. 40px for margins. Should be okay. Let's set canvas width="300" height="600". Now, I need to ensure no external resources. All inline. Check for the word "Tetris": I must not use it. I'll use "BLOCK PUZZLE". Let's write the complete HTML. One issue: `document.addEventListener('click', ...)` might interfere with button clicks. I'll check `e.target` and if it's a button or inside a button, ignore. Also, the start button is inside the overlay. When overlay is hidden, clicking the page starts game only if MENU or GAMEOVER. During PLAYING, clicking does nothing (except maybe pause? No, P pauses). The requirement says "The player can start a new game with the Enter key or a click." So click should restart when game over. During play, click does nothing. Let's refine click handler: ```javascript document.addEventListener('click', e => { if (e.target.tagName === 'BUTTON') return; if (state === 'MENU' || state === 'GAMEOVER') { startGame(); } else if (state === 'PAUSED') { state = 'PLAYING'; hideOverlay(); } }); ``` But the start button is a button, so clicking it won't trigger this. The start button has its own listener. Also, the sound button is a button, so it won't trigger game start. Now, the `keydown` for start: "The game starts when the player clicks the page or presses any key." So any key press while in MENU starts the game. But if they press 'p' in MENU, it starts game and pauses? That's weird. Better: any key starts game. Then if it's 'p', we could pause immediately. But let's just start the game. The key press that starts the game is consumed. ```javascript if (state === 'MENU') { startGame(); return; // don't process further } ``` But if they press left to start, the piece won't move because we returned. That's fine. Now, the `keys` object for left/right/down. I need to make sure that when game starts, keys are reset. Let's write the full code now. I need to be careful with variable scoping. I'll wrap everything in a script. Let's also add a simple "hold" feature? Not required. Skip to keep code manageable and correct. Let's verify collision for spawn: piece at x=3, y=-4. For I horizontal, shape coords from matrix: Matrix I: [0,0,0,0] [1,1,1,1] [0,0,0,0] [0,0,0,0] Coords: (0,1),(1,1),(2,1),(3,1). At x=3, y=-4: blocks at (3,-3),(4,-3),(5,-3),(6,-3). All y < 0, so no collision. Good. As it falls, y increases. When y = -1, blocks at (3,0),(4,0),(5,0),(6,0). In grid. Good. When it locks, y might be 16 or so. Blocks at y+1 = 17..20. If y+1 >= 20, collision. So it locks when it can't fall further. Line clear: when a row is full, remove it. Particles: spawn at center of cleared cells. Sound: I'll implement simple tones. Let's write the sound functions: ```javascript let audioCtx = null; let soundEnabled = false; function initAudio() { if (!audioCtx) { audioCtx = new AudioContext(); } if (audioCtx.state === 'suspended') { audioCtx.resume(); } } function playSound(type) { if (!soundEnabled) return; initAudio(); const now = audioCtx.currentTime; const osc = audioCtx.createOscillator(); const gain = audioCtx.createGain(); osc.connect(gain); gain.connect(audioCtx.destination); if (type === 'move') { osc.type = 'square'; osc.frequency.setValueAtTime(200, now); gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.05); osc.start(now); osc.stop(now + 0.05); } else if (type === 'rotate') { osc.type = 'sine'; osc.frequency.setValueAtTime(400, now); gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.1); osc.start(now); osc.stop(now + 0.1); } else if (type === 'lock') { osc.type = 'sawtooth'; osc.frequency.setValueAtTime(100, now); osc.frequency.exponentialRampToValueAtTime(50, now + 0.2); gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.2); osc.start(now); osc.stop(now + 0.2); } else if (type === 'clear') { osc.type = 'triangle'; osc.frequency.setValueAtTime(600, now); gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.2); osc.start(now); osc.stop(now + 0.2); } else if (type === 'gameover') { osc.type = 'sawtooth'; osc.frequency.setValueAtTime(150, now); osc.frequency.linearRampToValueAtTime(50, now + 0.5); gain.gain.setValueAtTime(0.05, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.5); osc.start(now); osc.stop(now + 0.5); } } ``` This is fine. Now, the `draw` function needs to draw the sidebar next piece. I'll use a separate canvas. HTML for next canvas: ```html ``` Wait, I had a div wrapper. Let's just use the canvas directly. Sidebar: ```html ``` CSS for sidebar: ```css #sidebar { position: absolute; top: 20px; right: 20px; width: 140px; display: flex; flex-direction: column; align-items: center; } ``` Canvas main: ```css #gameCanvas { display: block; background: #16213e; border: 4px solid #0f3460; box-shadow: 0 0 30px rgba(0,240,255,0.3); } ``` Container: ```css #game-container { position: relative; width: 460px; height: 600px; } ``` This should fit. Now, let's think about the `drawBlock` function. I want it to look nice. ```javascript function drawBlock(x, y, color, alpha = 1) { ctx.save(); ctx.globalAlpha = alpha; ctx.shadowColor = color; ctx.shadowBlur = 15; ctx.fillStyle = color; ctx.fillRect(x + 2, y + 2, CELL - 4, CELL - 4); // highlight ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(x + 4, y + 4, CELL - 8, 4); ctx.fillRect(x + 4, y + 4, 4, CELL - 8); // shadow ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(x + 4, y + CELL - 8, CELL - 8, 4); ctx.fillRect(x + CELL - 8, y + 4, 4, CELL - 8); ctx.restore(); } ``` This gives a beveled look. Ghost piece: draw with alpha 0.2 and no fill, just outline? Or lighter fill. I'll draw with alpha 0.3. Current piece: draw at renderX, renderY. Grid lines: subtle. Background: dark. Let's also add a "scanline" effect or something? Not necessary. Now, the `update` function needs to handle `moveTimer` correctly. I should reset `moveTimer` when key is released. I'll do that in keyup. ```javascript window.addEventListener('keyup', e => { if (e.key === 'ArrowLeft') keys.left = false; if (e.key === 'ArrowRight') keys.right = false; if (e.key === 'ArrowDown') keys.down = false; if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') moveTimer = 0; }); ``` Actually, when key is released, we should stop the movement timer so next press starts with initial delay. ```javascript if (e.key === 'ArrowLeft') { keys.left = false; moveTimer = 0; } if (e.key === 'ArrowRight') { keys.right = false; moveTimer = 0; } ``` Now, the fall timer: when piece locks and spawns, fallTimer should continue. That's fine. One more thing: when the piece is moving left/right, the `targetX` changes, but `piece.x` is the grid target. The render interpolates. Collision uses `piece.x` (integer). Good. When rotating, we might change `piece.x` and `piece.y` due to wall kicks. We should update `targetX` and `targetY` to match so it doesn't slide back. In rotate: ```javascript piece.targetX = piece.x; piece.targetY = piece.y; ``` In hard drop: ```javascript piece.targetY = piece.y; ``` In spawn: ```javascript piece.targetX = piece.x; piece.targetY = piece.y; ``` Now, the `getGhostY` function: ```javascript function getGhostY() { let y = piece.y; while (true) { if (collides(piece, piece.x, y + 1, piece.rot)) break; y++; } return y; } ``` This could infinite loop if piece is already at bottom? No, because collides will be true when y+1 hits floor or blocks. So it stops. Now, line clear and particles: I need to spawn particles for each cleared cell. The color should be the block color. ```javascript function clearLines() { const cleared = []; for (let y = ROWS - 1; y >= 0; y--) { if (grid[y].every(cell => cell !== 0)) { cleared.push(y); } } if (cleared.length === 0) return; for (const y of cleared) { for (let x = 0; x < COLS; x++) { spawnParticle(x * CELL + CELL/2, y * CELL + CELL/2, COLORS[grid[y][x]]); } grid.splice(y, 1); grid.unshift(Array(COLS).fill(0)); } const lines = cleared.length; score += lines * 100 * level; totalLines += lines; level = Math.floor(totalLines / 10) + 1; fallInterval = Math.max(100, 1000 - (level - 1) * 100); updateHUD(); playSound('clear'); } ``` Wait, `grid.splice(y, 1)` removes the row. Then `unshift` adds a new row at top. The rows above shift down. This is correct. But we need to be careful: if we clear multiple rows, splicing one by one from bottom to top is okay because we collected `cleared` from bottom to top (y descending). If we splice row 19, then row 18 becomes 19, but we already processed 19. Actually, we collected all cleared rows first. Then we process them. If we process from highest to lowest, splicing doesn't affect lower indices. But `cleared` is in descending order (19, 18, ...). If we splice 19, then 18 is still 18. Good. If we splice 18, then 17 is still 17. Good. So descending order is fine. Actually, if we clear rows 5 and 10. `cleared` = [10, 5]. Splice 10: row 10 removed, rows 11+ shift down. Row 5 is still 5. Splice 5: row 5 removed. Good. Now, the `spawn` function: ```javascript function spawn() { piece.type = nextType; nextType = 1 + Math.floor(Math.random() * 7); piece.rot = 0; piece.x = 3; piece.y = -4; piece.targetX = 3; piece.targetY = -4; if (collides(piece, piece.x, piece.y, piece.rot)) { gameOver(); return; } drawNext(); } ``` But `collides` checks `cy >= ROWS` as collision. At y=-4, cy = -4 + offset.y. For I horizontal, offset.y=1, so cy=-3. That's < 0, so allowed. For cy >= ROWS (20), collision. So no issue. However, what if the piece is tall and y=-4, but some block has offset.y=4, so cy=0. That's fine. Now, `lock` function: ```javascript function lock() { const shape = PIECES[piece.type - 1][piece.rot]; for (const offset of shape) { const cx = piece.x + offset.x; const cy = piece.y + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { grid[cy][cx] = piece.type; } } clearLines(); spawn(); playSound('lock'); } ``` Wait, `spawn` might trigger game over. If so, we shouldn't play lock sound? Or play it anyway. It's fine. Now, the `draw` function should also draw the next piece on the side canvas. I'll call `drawNext()` once when next piece changes, and also in `spawn`. `drawNext`: ```javascript function drawNext() { const ctx = nextCanvas.getContext('2d'); ctx.clearRect(0, 0, 100, 100); const shape = PIECES[nextType - 1][0]; const cell = 20; const offsetX = (100 - 4 * cell) / 2; const offsetY = (100 - 4 * cell) / 2; for (const offset of shape) { ctx.save(); ctx.shadowColor = COLORS[nextType]; ctx.shadowBlur = 10; ctx.fillStyle = COLORS[nextType]; ctx.fillRect(offsetX + offset.x * cell + 2, offsetY + offset.y * cell + 2, cell - 4, cell - 4); ctx.restore(); } } ``` Now, the `loop` function: ```javascript let running = false; let lastTime = 0; function loop(timestamp) { if (!running) return; const dt = timestamp - lastTime; lastTime = timestamp; update(dt); draw(); requestAnimationFrame(loop); } ``` `update(dt)`: ```javascript function update(dt) { if (state !== 'PLAYING') return; fallTimer += dt; if (fallTimer >= fallInterval) { fallTimer = 0; if (!collides(piece, piece.x, piece.y + 1, piece.rot)) { piece.y++; piece.targetY = piece.y; playSound('move'); } else { lock(); } } if (keys.down) { softDropTimer += dt; if (softDropTimer >= SOFT_DROP_DELAY) { softDropTimer = 0; if (!collides(piece, piece.x, piece.y + 1, piece.rot)) { piece.y++; piece.targetY = piece.y; } } } if (keys.left) { moveTimer += dt; const delay = moveTimer > 500 ? MOVE_REPEAT : MOVE_DELAY; if (moveTimer >= delay) { moveTimer = 0; if (!collides(piece, piece.x - 1, piece.y, piece.rot)) { piece.x--; piece.targetX = piece.x; playSound('move'); } } } if (keys.right) { moveTimer += dt; const delay = moveTimer > 500 ? MOVE_REPEAT : MOVE_DELAY; if (moveTimer >= delay) { moveTimer = 0; if (!collides(piece, piece.x + 1, piece.y, piece.rot)) { piece.x++; piece.targetX = piece.x; playSound('move'); } } } // interpolate const targetX = piece.targetX * CELL; const targetY = piece.targetY * CELL; piece.renderX += (targetX - piece.renderX) * 0.2; piece.renderY += (targetY - piece.renderY) * 0.2; updateParticles(); } ``` Wait, `moveTimer` is shared between left and right. If I press left, then right, the timer continues. That's okay. But if I release left, `moveTimer` is reset to 0 in keyup. Good. But there's a bug: if I hold left, `moveTimer` accumulates. When it exceeds delay, we move and reset `moveTimer` to 0. Then it continues accumulating. The delay check uses `moveTimer > 500` to switch to repeat. But since we reset to 0 after each move, it will always be < 500 until 500ms have passed. So after 500ms of holding, it switches to 50ms repeat. That's correct. However, `moveTimer` is shared. If I hold left for 600ms, it moves at 150ms, then resets. Then at 300ms (total 450), moves again. Then at 150ms (total 600), moves again. Then delay becomes 50ms. So it moves at 650, 700, 750... Good. Now, `softDropTimer` is separate. One issue: `fallTimer` and `softDropTimer` can both move the piece down. If soft drop is active, it moves down every 50ms. The fall timer might also trigger. That's fine, but we might move down twice in one frame. The collision check prevents moving into occupied cells. Now, the `draw` function: ```javascript function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // draw locked blocks for (let y = 0; y < ROWS; y++) { for (let x = 0; x < COLS; x++) { if (grid[y][x] !== 0) { drawBlock(x * CELL, y * CELL, COLORS[grid[y][x]]); } } } // draw ghost const ghostY = getGhostY(); const shape = PIECES[piece.type - 1][piece.rot]; for (const offset of shape) { const cx = piece.x + offset.x; const cy = ghostY + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { drawBlock(cx * CELL, cy * CELL, '#fff', 0.2); } } // draw current piece for (const offset of shape) { const cx = piece.x + offset.x; const cy = piece.y + offset.y; if (cy >= 0 && cy < ROWS && cx >= 0 && cx < COLS) { drawBlock(piece.renderX + offset.x * CELL, piece.renderY + offset.y * CELL, COLORS[piece.type]); } } // draw particles drawParticles(); // grid lines ctx.strokeStyle = 'rgba(255,255,255,0.05)'; ctx.lineWidth = 1; for (let x = 0; x <= COLS; x++) { ctx.beginPath(); ctx.moveTo(x * CELL, 0); ctx.lineTo(x * CELL, canvas.height); ctx.stroke(); } for (let y = 0; y <= ROWS; y++) { ctx.beginPath(); ctx.moveTo(0, y * CELL); ctx.lineTo(canvas.width, y * CELL); ctx.stroke(); } } ``` `drawParticles`: ```javascript function drawParticles() { for (const p of particles) { ctx.globalAlpha = p.life / 40; ctx.fillStyle = p.color; ctx.fillRect(p.x - 2, p.y - 2, 4, 4); } } ``` `updateParticles`: ```javascript function updateParticles() { for (let i = particles.length - 1; i >= 0; i--) { const p = particles[i]; p.x += p.vx; p.y += p.vy; p.vy += 0.1; // gravity p.life--; if (p.life <= 0) particles.splice(i, 1); } } ``` `spawnParticle`: ```javascript function spawnParticle(x, y, color) { for (let i = 0; i < 6; i++) { particles.push({ x, y, vx: (Math.random() - 0.5) * 6, vy: (Math.random() - 0.5) * 6, life: 40 + Math.random() * 20, color }); } } ``` Now, the `collides` function: ```javascript function collides(piece, x, y, rot) { const shape = PIECES[piece.type - 1][rot]; for (const offset of shape) { const cx = x + offset.x; const cy = y + offset.y; if (cx < 0 || cx >= COLS) return true; if (cy >= ROWS) return true; if (cy >= 0 && grid[cy][cx] !== 0) return true; } return false; } ``` This allows cy < 0 (above grid). Now, the `getGhostY`: ```javascript function getGhostY() { let y = piece.y; while (!collides(piece, piece.x, y + 1, piece.rot)) { y++; } return y; } ``` Now, the `rotate` function with wall kicks: ```javascript function rotate() { const nextRot = (piece.rot + 1) % 4; if (!collides(piece, piece.x, piece.y, nextRot)) { piece.rot = nextRot; piece.targetX = piece.x; piece.targetY = piece.y; playSound('rotate'); } else { const kicks = [[0,0], [-1,0], [1,0], [0,-1], [-1,-1], [1,-1], [-1,1], [1,1]]; for (const [dx, dy] of kicks) { if (!collides(piece, piece.x + dx, piece.y + dy, nextRot)) { piece.x += dx; piece.y += dy; piece.rot = nextRot; piece.targetX = piece.x; piece.targetY = piece.y; playSound('rotate'); return; } } } } ``` Now, `hardDrop`: ```javascript function hardDrop() { const ghostY = getGhostY(); piece.y = ghostY; piece.targetY = ghostY; lock(); } ``` Now, `startGame`: ```javascript function startGame() { state = 'PLAYING'; hideOverlay(); score = 0; totalLines = 0; level = 1; fallInterval = 1000; fallTimer = 0; moveTimer = 0; softDropTimer = 0; grid = Array(ROWS).fill().map(() => Array(COLS).fill(0)); particles = []; nextType = 1 + Math.floor(Math.random() * 7); piece = { type: 0, rot: 0, x: 3, y: -4, targetX: 3, targetY: -4, renderX: 3 * CELL, renderY: -4 * CELL }; spawn(); updateHUD(); drawNext(); running = true; lastTime = performance.now(); requestAnimationFrame(loop); } ``` Wait, `spawn` sets `piece.type = nextType` and picks a new nextType. But I already set `nextType` before spawn. So `spawn` will use that nextType as the current piece, and then pick a new nextType. That's correct. But in `startGame`, I set `nextType` randomly, then call `spawn`. `spawn` does: ```javascript piece.type = nextType; nextType = 1 + Math.floor(Math.random() * 7); ``` So the first piece is the randomly chosen nextType, and a new nextType is chosen. Good. `gameOver`: ```javascript function gameOver() { state = 'GAMEOVER'; running = false; showOverlay('gameover'); playSound('gameover'); } ``` `showOverlay`: ```javascript function showOverlay(type) { const overlay = document.getElementById('overlay'); overlay.classList.remove('hidden'); const title = overlay.querySelector('h1'); const msg = overlay.querySelector('p'); const btn = document.getElementById('start-btn'); if (type === 'start') { title.textContent = 'BLOCK PUZZLE'; msg.innerHTML = 'Use ARROWS to move and rotate.
' + 'DOWN to soft drop.
' + 'SPACE to hard drop.
' + 'P to pause.

' + 'Click or press any key to start.'; btn.textContent = 'Start Game'; btn.style.display = 'block'; } else if (type === 'pause') { title.textContent = 'PAUSED'; msg.textContent = 'Press P or click to resume.'; btn.style.display = 'none'; } else if (type === 'gameover') { title.textContent = 'GAME OVER'; msg.textContent = `Score: ${score} Lines: ${totalLines} Level: ${level}
Press Enter or click to restart.`; btn.textContent = 'Play Again'; btn.style.display = 'block'; } } ``` `hideOverlay`: ```javascript function hideOverlay() { document.getElementById('overlay').classList.add('hidden'); } [answer] Block Puzzle

BLOCK PUZZLE