Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

write a snake game using HTML, CSS, Javascript

  1. User

    write a snake game using HTML, CSS, Javascript

  2. Assistant

    Creating a simple Snake game involves using HTML for the structure, CSS for styling, and JavaScript for the game logic. Here is a basic implementation of the Snake game:

    HTML

    Create an HTML file (e.g., index.html) to contain the canvas element where the game will be rendered.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Snake Game</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <canvas id="snakeGame" width="400" height="400"></canvas>
        <script src="script.js"></script>
    </body>
    </html>
    

    CSS

    Create a CSS file (e.g., styles.css) to style the game canvas.

    body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        background-color: #20232a;
    }
    
    canvas {
        border: 1px solid #ddd;
        background-color: #282c34;
    }
    

    JavaScript

    Create a JavaScript file (e.g., script.js) for the game logic.

    const canvas = document.getElementById('snakeGame');
    const ctx = canvas.getContext('2d');
    
    const box = 20;
    const canvasSize = 400;
    
    let snake = [];
    snake[0] = { x: 9 * box, y: 9 * box };
    
    let direction;
    let score = 0;
    
    // Create food
    let food = {
        x: Math.floor(Math.random() * (canvasSize / box)) * box,
        y: Math.floor(Math.random() * (canvasSize / box)) * box,
    };
    
    // Control the snake
    document.addEventListener('keydown', directionEvent);
    
    function directionEvent(event) {
        if (event.keyCode === 37 && direction !== 'RIGHT') {
            direction = 'LEFT';
        } else if (event.keyCode === 38 && direction !== 'DOWN') {
            direction = 'UP';
        } else if (event.keyCode === 39 && direction !== 'LEFT') {
            direction = 'RIGHT';
        } else if (event.keyCode === 40 && direction !== 'UP') {
            direction = 'DOWN';
        }
    }
    
    // Check collision
    function collision(head, array) {
        return array.some(segment => segment.x === head.x && segment.y === head.y);
    }
    
    // Draw everything to the canvas
    function draw() {
        ctx.fillStyle = '#282c34';
        ctx.fillRect(0, 0, canvasSize, canvasSize);
    
        for (let i = 0; i < snake.length; i++) {
            ctx.fillStyle = (i === 0) ? '#4caf50' : '#8bc34a';
            ctx.fillRect(snake[i].x, snake[i].y, box, box);
    
            ctx.strokeStyle = '#ffffff';
            ctx.strokeRect(snake[i].x, snake[i].y, box, box);
        }
    
        ctx.fillStyle = '#ffeb3b';
        ctx.fillRect(food.x, food.y, box, box);
    
        let snakeX = snake[0].x;
        let snakeY = snake[0].y;
    
        // Direction: move snake
        if (direction === 'LEFT') snakeX -= box;
        if (direction === 'UP') snakeY -= box;
        if (direction === 'RIGHT') snakeX += box;
        if (direction === 'DOWN') snakeY += box;
    
        // If the snake eats food
        if (snakeX === food.x && snakeY === food.y) {
            score++;
            food = {
                x: Math.floor(Math.random() * (canvasSize / box)) * box,
                y: Math.floor(Math.random() * (canvasSize / box)) * box,
            };
        } else {
            snake.pop();
        }
    
        // New head position
        const newHead = { x: snakeX, y: snakeY };
    
        // Game over conditions
        if (snakeX < 0 || snakeY < 0 || snakeX >= canvasSize || snakeY >= canvasSize || collision(newHead, snake)) {
            clearInterval(game);
            alert(`Game Over! Your score: ${score}`);
        }
    
        snake.unshift(newHead);
    
        ctx.fillStyle = '#ffffff';
        ctx.font = '20px Arial';
        ctx.fillText('Score: ' + score, 10, canvasSize - 10);
    }
    
    // Call draw function every 100 ms
    let game = setInterval(draw, 100);
    

    Explanation

    • HTML: The <canvas> element is used to draw the game board.
    • CSS: Simple styling is applied to center the canvas and give it a dotted border.
    • JavaScript:
      • A snake is represented as an array of objects.
      • The snake's direction is determined by arrow key events.
      • The draw() function handles rendering the snake, food, and score, plus managing game over conditions and adding food consumption logic.
      • Game runs via setInterval, calling draw every 100ms to update the snake’s position and game state.

    This code provides the foundation for further enhancements, such as increasing the snake's speed over time, adding sound effects, or implementing a more sophisticated collision detection mechanism.