Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro-preview-03-25· GoogleHugging Face LMArena Human Preference 140K

Make the game tetris in html css js Make it functional and working Add particles

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-17b-128e-instruct’s answer.
  1. User

    Make the game tetris in html css js Make it functional and working Add particles

  2. Gemini Assistant

    Okay, here's a functional Tetris game using HTML, CSS, and JavaScript, including a simple particle effect when lines are cleared.

    1. index.html (HTML Structure)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Tetris with Particles</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h1>Tetris</h1>
        <div class="game-container">
            <canvas id="tetrisCanvas" width="200" height="400"></canvas>
            <div class="sidebar">
                <div>
                    <h2>Score</h2>
                    <p id="score">0</p>
                </div>
                <div>
                    <h2>Next</h2>
                    <canvas id="nextCanvas" width="80" height="80"></canvas>
                </div>
                <button id="startButton">Start Game</button>
                 <p id="gameOver" class="hidden">Game Over!</p>
            </div>
        </div>
        <script src="script.js"></script>
    </body>
    </html>
    

    2. style.css (Styling)

    body {
        font-family: sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 100vh;
        background-color: #f0f0f0;
        margin: 0;
    }
    
    h1 {
        color: #333;
        margin-bottom: 20px;
    }
    
    .game-container {
        display: flex;
        align-items: flex-start; /* Align items to the top */
        gap: 20px; /* Space between canvas and sidebar */
        background-color: #ddd;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    #tetrisCanvas {
        border: 5px solid #333;
        background-color: #000; /* Black background for the game board */
        display: block; /* Prevent extra space below canvas */
    }
    
    .sidebar {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
        min-width: 120px; /* Give sidebar some width */
    }
    
    .sidebar div {
        background-color: #eee;
        padding: 10px;
        margin-bottom: 15px;
        border-radius: 5px;
        width: 100%; /* Make divs fill sidebar width */
        box-sizing: border-box; /* Include padding in width */
    }
    
    h2 {
        margin-top: 0;
        margin-bottom: 5px;
        font-size: 1.1em;
        color: #555;
    }
    
    #score {
        font-size: 1.5em;
        font-weight: bold;
        color: #2a2a9e;
        margin: 0;
    }
    
    #nextCanvas {
        background-color: #000;
        border: 2px solid #555;
        margin-top: 5px;
    }
    
    #startButton {
        padding: 10px 20px;
        font-size: 1em;
        cursor: pointer;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        margin-top: 10px;
        transition: background-color 0.2s;
    }
    
    #startButton:hover {
        background-color: #45a049;
    }
    
    #gameOver {
        color: red;
        font-weight: bold;
        font-size: 1.2em;
        margin-top: 15px;
    }
    
    .hidden {
        display: none;
    }
    

    3. script.js (JavaScript Logic)

    const canvas = document.getElementById('tetrisCanvas');
    const context = canvas.getContext('2d');
    const nextCanvas = document.getElementById('nextCanvas');
    const nextContext = nextCanvas.getContext('2d');
    const scoreElement = document.getElementById('score');
    const startButton = document.getElementById('startButton');
    const gameOverElement = document.getElementById('gameOver');
    
    const COLS = 10;
    const ROWS = 20;
    const BLOCK_SIZE = canvas.width / COLS; // = 20
    const NEXT_BLOCK_SIZE = nextCanvas.width / 4; // For 4x4 grid
    
    // --- Colors ---
    const COLORS = [
        null,        // 0 - Empty
        '#FF0D72',   // 1 - T
        '#0DC2FF',   // 2 - I
        '#0DFF72',   // 3 - S
        '#F538FF',   // 4 - Z
        '#FF8E0D',   // 5 - L
        '#FFE138',   // 6 - J
        '#3877FF'    // 7 - O
    ];
    
    const SHAPES = [
        [], // Empty shape at index 0
        [[0, 1, 0], [1, 1, 1], [0, 0, 0]], // T
        [[0, 0, 0, 0], [2, 2, 2, 2], [0, 0, 0, 0], [0, 0, 0, 0]], // I
        [[0, 3, 3], [3, 3, 0], [0, 0, 0]], // S
        [[4, 4, 0], [0, 4, 4], [0, 0, 0]], // Z
        [[0, 0, 5], [5, 5, 5], [0, 0, 0]], // L
        [[6, 0, 0], [6, 6, 6], [0, 0, 0]], // J
        [[7, 7], [7, 7]]  // O
    ];
    
    // --- Game State ---
    let board = createBoard();
    let currentPiece;
    let nextPiece;
    let score = 0;
    let gameOver = false;
    let gameLoopInterval;
    let fallSpeed = 1000; // Milliseconds per drop
    let particles = [];
    
    // --- Particle Class ---
    class Particle {
        constructor(x, y, color) {
            this.x = x;
            this.y = y;
            this.size = Math.random() * 3 + 2; // Size between 2 and 5
            this.color = color;
            // Random velocity - slightly upwards and outwards
            this.vx = (Math.random() - 0.5) * 3;
            this.vy = (Math.random() - 0.5) * 3 - 1; // Bias upwards initially
            this.life = Math.random() * 30 + 30; // Lifespan frames (approx 0.5 - 1 sec)
            this.gravity = 0.1;
        }
    
        update() {
            this.x += this.vx;
            this.y += this.vy;
            this.vy += this.gravity; // Apply gravity
            this.life--;
        }
    
        draw(ctx) {
            if (this.life > 0) {
                ctx.fillStyle = this.color;
                ctx.globalAlpha = Math.max(0, this.life / 60); // Fade out
                ctx.fillRect(this.x, this.y, this.size, this.size);
                ctx.globalAlpha = 1.0; // Reset alpha
            }
        }
    }
    
    // --- Game Functions ---
    
    function createBoard() {
        // Initialize board with zeros
        return Array.from({ length: ROWS }, () => Array(COLS).fill(0));
    }
    
    function getRandomPiece() {
        const randomIndex = Math.floor(Math.random() * (SHAPES.length - 1)) + 1; // Exclude empty shape 0
        const shape = SHAPES[randomIndex];
        const colorIndex = randomIndex; // Use shape index for color
        return {
            x: Math.floor(COLS / 2) - Math.floor(shape[0].length / 2),
            y: 0, // Start at the top
            shape: shape,
            colorIndex: colorIndex
        };
    }
    
    function isValidMove(piece, newX, newY, newShape) {
        const shape = newShape || piece.shape;
        for (let y = 0; y < shape.length; y++) {
            for (let x = 0; x < shape[y].length; x++) {
                if (shape[y][x] !== 0) { // If it's part of the piece
                    const boardX = newX + x;
                    const boardY = newY + y;
    
                    // Check boundaries
                    if (boardX < 0 || boardX >= COLS || boardY >= ROWS) {
                        return false;
                    }
                    // Check collision with existing pieces (only if moving down or sideways, not initially)
                    if (boardY >= 0 && board[boardY] && board[boardY][boardX] !== 0) {
                         return false;
                    }
                }
            }
        }
        return true;
    }
    
    function rotatePiece(piece) {
        // Simple matrix rotation (transpose + reverse rows)
        const shape = piece.shape;
        const N = shape.length;
        const rotatedShape = Array.from({ length: N }, () => Array(N).fill(0));
    
        for (let y = 0; y < N; y++) {
            for (let x = 0; x < N; x++) {
                rotatedShape[x][N - 1 - y] = shape[y][x];
            }
        }
    
        // Check for valid move after rotation, attempt basic wall kick
        let newX = piece.x;
        if (!isValidMove(piece, newX, piece.y, rotatedShape)) {
           // Try shifting left or right slightly if blocked
           if (isValidMove(piece, newX + 1, piece.y, rotatedShape)) {
               newX++;
           } else if (isValidMove(piece, newX - 1, piece.y, rotatedShape)) {
               newX--;
           } else if (isValidMove(piece, newX + 2, piece.y, rotatedShape)) { // For I piece mostly
               newX += 2;
           } else if (isValidMove(piece, newX - 2, piece.y, rotatedShape)) {
               newX -= 2;
           } else {
               return; // Can't rotate
           }
        }
    
        piece.shape = rotatedShape;
        piece.x = newX; // Apply position change from wall kick if any
    }
    
    
    function lockPiece(piece) {
        piece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                    // Check if piece locked above the visible area
                    if (piece.y + y < 0) {
                        gameOver = true;
                        return; // Stop locking if game over condition met immediately
                    }
                    if (board[piece.y + y] !== undefined) { // Ensure row exists
                       board[piece.y + y][piece.x + x] = piece.colorIndex;
                    }
                }
            });
        });
        if (gameOver) return; // Don't proceed if game ended
    
        clearLines();
        spawnNewPiece();
    }
    
    
    function clearLines() {
        let linesCleared = 0;
        for (let y = ROWS - 1; y >= 0; y--) {
            if (board[y].every(cell => cell !== 0)) {
                // Line is full
                const clearedRowColorIndices = board[y]; // Get colors before clearing
    
                // Create particles for the cleared line
                for (let x = 0; x < COLS; x++) {
                    const color = COLORS[clearedRowColorIndices[x]]; // Get color of the block
                    if (color) {
                         // Create multiple particles per block
                        for (let i = 0; i < 5; i++) { // Create 5 particles per block
                            particles.push(new Particle(
                                (x + Math.random()) * BLOCK_SIZE, // Start within the block's column
                                (y + Math.random()) * BLOCK_SIZE, // Start within the block's row
                                color
                            ));
                        }
                    }
                }
    
                // Remove the line and add a new empty line at the top
                board.splice(y, 1);
                board.unshift(Array(COLS).fill(0));
                linesCleared++;
                y++; // Re-check the current row index as rows shifted down
            }
        }
    
        // Update score based on lines cleared
        if (linesCleared > 0) {
            score += linesCleared * 100 * linesCleared; // Bonus for multiple lines
            scoreElement.textContent = score;
    
            // Increase speed (optional)
            if (fallSpeed > 200) { // Set a minimum speed limit
                 fallSpeed -= linesCleared * 10;
                 resetInterval(); // Apply new speed
            }
        }
    }
    
    function spawnNewPiece() {
        currentPiece = nextPiece || getRandomPiece(); // Use next or get random if first piece
        nextPiece = getRandomPiece();
        if (!isValidMove(currentPiece, currentPiece.x, currentPiece.y)) {
            // If the new piece immediately collides, game over
            gameOver = true;
        }
        drawNextPiece();
    }
    
    function movePiece(dx, dy) {
        if (gameOver) return;
        const newX = currentPiece.x + dx;
        const newY = currentPiece.y + dy;
        if (isValidMove(currentPiece, newX, newY)) {
            currentPiece.x = newX;
            currentPiece.y = newY;
            return true; // Move was successful
        }
        return false; // Move failed
    }
    
    function hardDrop() {
        if (gameOver) return;
        while (movePiece(0, 1)) {
            // Keep moving down until collision
        }
        // Once it can't move down anymore, lock it
        lockPiece(currentPiece);
    }
    
    
    // --- Drawing ---
    
    function drawSquare(ctx, x, y, colorIndex, blockSize = BLOCK_SIZE) {
        ctx.fillStyle = COLORS[colorIndex];
        ctx.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
        ctx.strokeStyle = '#555'; // Border color for blocks
        ctx.lineWidth = 1;
        ctx.strokeRect(x * blockSize, y * blockSize, blockSize, blockSize);
    }
    
    function drawBoard() {
        // Clear board area
        context.fillStyle = '#000';
        context.fillRect(0, 0, canvas.width, canvas.height);
    
        // Draw existing locked pieces
        board.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                    drawSquare(context, x, y, value);
                }
            });
        });
    }
    
    function drawPiece(ctx, piece, blockSize = BLOCK_SIZE, offsetX = 0, offsetY = 0) {
         if (!piece) return;
         piece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                    drawSquare(ctx, piece.x + x + offsetX, piece.y + y + offsetY, piece.colorIndex, blockSize);
                }
            });
        });
    }
    
    function drawNextPiece() {
        // Clear next piece canvas
        nextContext.fillStyle = '#000';
        nextContext.fillRect(0, 0, nextCanvas.width, nextCanvas.height);
    
        if (!nextPiece) return;
    
        // Center the piece in the preview area
        const shape = nextPiece.shape;
        const shapeWidth = shape[0].length;
        const shapeHeight = shape.length;
        const offsetX = Math.floor((4 - shapeWidth) / 2); // Center horizontally in 4x4 grid
        const offsetY = Math.floor((4 - shapeHeight) / 2); // Center vertically
    
        shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value !== 0) {
                     drawSquare(nextContext, x + offsetX, y + offsetY, nextPiece.colorIndex, NEXT_BLOCK_SIZE);
                }
            });
        });
    }
    
    
    function drawParticles() {
        particles.forEach((p, index) => {
            p.update();
            if (p.life <= 0) {
                particles.splice(index, 1); // Remove dead particles
            } else {
                p.draw(context);
            }
        });
    }
    
    // --- Game Loop ---
    
    function gameLoop() {
        if (gameOver) {
            clearInterval(gameLoopInterval);
            gameOverElement.classList.remove('hidden');
            startButton.textContent = "Restart Game"; // Change button text
            startButton.disabled = false;
            console.log("Game Over!");
            return;
        }
    
        // 1. Update game state (try moving down)
        if (!movePiece(0, 1)) {
            // If piece can't move down, lock it
            lockPiece(currentPiece);
            // Check for game over again after locking (in case locking itself caused it)
            if (gameOver) {
                gameLoop(); // Call again to handle game over display
                return;
            }
        }
    
        // 2. Draw everything
        drawBoard();
        drawPiece(context, currentPiece);
        drawParticles(); // Draw particles on top
    
    }
    
    function resetInterval() {
        clearInterval(gameLoopInterval);
        if (!gameOver) {
            gameLoopInterval = setInterval(gameLoop, fallSpeed);
        }
    }
    
    function startGame() {
        console.log("Starting game...");
        // Reset state
        board = createBoard();
        score = 0;
        particles = [];
        scoreElement.textContent = score;
        gameOver = false;
        fallSpeed = 1000; // Reset speed
        gameOverElement.classList.add('hidden');
        startButton.textContent = "Start Game"; // Reset button text
        startButton.disabled = true; // Disable button while playing
    
        // Spawn initial pieces
        spawnNewPiece(); // Sets up current and next piece
        spawnNewPiece(); // Call again to ensure nextPiece is populated for the first draw
    
        // Start the loop
        resetInterval();
        // Initial draw
        drawBoard();
        drawPiece(context, currentPiece);
        drawNextPiece();
    
    }
    
    // --- Event Listeners ---
    
    document.addEventListener('keydown', (event) => {
        if (gameOver) return; // Ignore input if game is over
    
        switch (event.key) {
            case 'ArrowLeft':
            case 'a': // Add WASD alternative
                movePiece(-1, 0);
                break;
            case 'ArrowRight':
            case 'd':
                movePiece(1, 0);
                break;
            case 'ArrowDown':
            case 's':
                if (!movePiece(0, 1)) {
                    // If moving down manually causes a lock, lock immediately
                    lockPiece(currentPiece);
                }
                // Optionally reset interval to make it feel responsive
                // resetInterval();
                break;
            case 'ArrowUp':
            case 'w': // Rotate
                rotatePiece(currentPiece);
                break;
            case ' ': // Space bar for hard drop
                event.preventDefault(); // Prevent page scrolling
                hardDrop();
                break;
            // Add pause functionality if desired
            // case 'p':
            //    togglePause();
            //    break;
        }
        // Re-draw immediately after player input for responsiveness
        if (!gameOver) {
            drawBoard();
            drawPiece(context, currentPiece);
            drawParticles(); // Still draw particles
        }
    });
    
    startButton.addEventListener('click', startGame);
    
    // Initial message or state
    gameOverElement.textContent = "Press Start Game";
    gameOverElement.classList.remove('hidden');
    startButton.disabled = false;
    
    

    Explanation:

    1. HTML (index.html):

      • Sets up the main canvas (tetrisCanvas) for the game board.
      • Adds a sidebar for the score (score) and the next piece preview (nextCanvas).
      • Includes a "Start Game" button (startButton) and a "Game Over" message (gameOver).
      • Links the CSS and JavaScript files.
    2. CSS (style.css):

      • Provides basic styling to center the game.
      • Styles the game canvas with a border and black background.
      • Arranges the sidebar elements.
      • Styles the score, next piece preview, button, and game over text.
      • The .hidden class is used to hide the game over message initially.
    3. JavaScript (script.js):

      • Constants & Setup: Defines board dimensions (ROWS, COLS), block size, colors (COLORS), and tetromino shapes (SHAPES). Gets canvas contexts and DOM elements.
      • Game State: Initializes variables like the board, currentPiece, nextPiece, score, gameOver flag, gameLoopInterval, fallSpeed, and the particles array.
      • Particle Class: Defines how particles behave (position, velocity, color, lifespan, gravity, drawing).
      • Core Functions:
        • createBoard(): Creates the empty 2D array for the board.
        • getRandomPiece(): Selects a random tetromino shape and color.
        • isValidMove(): Checks if a piece's potential new position/shape is valid (within bounds and not colliding with locked blocks).
        • rotatePiece(): Rotates the current piece's shape matrix. Includes basic "wall kick" logic to shift the piece slightly if the rotated position is blocked near edges.
        • lockPiece(): Copies the current piece's blocks onto the main board. Calls clearLines() and spawnNewPiece(). Checks for game over if a piece locks at the very top.
        • clearLines(): Checks for and removes completed rows. Shifts rows above down. Updates the score. Crucially, this function now creates Particle objects for each block in the cleared row and adds them to the particles array.
        • spawnNewPiece(): Sets the nextPiece as the currentPiece, generates a new nextPiece, and checks for immediate game over.
        • movePiece(): Attempts to move the piece horizontally or vertically.
        • hardDrop(): Moves the piece down instantly until it locks.
      • Drawing Functions:
        • drawSquare(): Helper to draw a single colored block.
        • drawBoard(): Clears the canvas and draws the locked blocks from the board array.
        • drawPiece(): Draws the currently falling currentPiece.
        • drawNextPiece(): Draws the nextPiece in the preview canvas.
        • drawParticles(): Iterates through the particles array, updates their positions, and draws them (with fading alpha based on lifespan). Removes dead particles.
      • Game Loop (gameLoop()):
        • Called repeatedly by setInterval.
        • Attempts to move the piece down (movePiece(0, 1)).
        • If it can't move down, calls lockPiece().
        • Checks for the gameOver condition.
        • Calls drawBoard(), drawPiece(), and drawParticles() to render the current state.
      • startGame(): Resets the game state, spawns the first pieces, and starts the gameLoopInterval.
      • Event Listeners:
        • Handles keyboard input (keydown) for moving left/right/down, rotating, and hard dropping.
        • Listens for clicks on the startButton.

    How to Run:

    1. Save the three code blocks as index.html, style.css, and script.js in the same folder.
    2. Open the index.html file in your web browser.
    3. Click the "Start Game" button.
    4. Use the arrow keys (or WASD) to move, Up arrow (or W) to rotate, and Spacebar to hard drop.

    Enjoy your Tetris game with line-clearing particle effects!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.