Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

write snake game in html css js

  1. User

    write snake game in html css js

  2. Assistant

    Sure! Below is a step-by-step guide to creating a simple Snake game using HTML, CSS, and JavaScript. The game will be played on a grid, and you control the snake using the arrow keys.

    HTML

    First, create an index.html file and add the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Snake Game</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <h1>Snake Game</h1>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <script src="script.js"></script>
    </body>
    </html>
    

    This HTML sets up:

    • A title for the page.
    • A link to an external CSS file (styles.css).
    • A <canvas> element where the game will be drawn.
    • A reference to an external JavaScript file (script.js).

    CSS

    Create a styles.css file for basic styling:

    body {
        text-align: center;
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
    }
    
    h1 {
        color: #333;
    }
    
    #gameCanvas {
        border: 1px solid #333;
        background-color: #fff;
    }
    

    This CSS styles:

    • The body to center content and set a background color.
    • The heading.
    • The canvas element with a border and background color.

    JavaScript

    Create a script.js file with the game logic:

    // Get the canvas and context
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // Game settings
    const gridSize = 20; // Size of each grid cell
    const canvasSize = canvas.width; // Assuming square canvas
    const tileCount = canvasSize / gridSize;
    
    // Snake settings
    let snakeX = snakeY = 10;
    let velocityX = velocityY = 0;
    let snakeTrail = [];
    let tailLength = 5;
    
    // Food settings
    let foodX = foodY = Math.floor(Math.random() * tileCount);
    
    // Game loop
    function game() {
        // Move the snake
        snakeX += velocityX;
        snakeY += velocityY;
    
        // Wrap snake position horizontally on edge of screen
        if (snakeX < 0) {
            snakeX = tileCount - 1;
        }
        if (snakeX > tileCount - 1) {
            snakeX = 0;
        }
    
        // Wrap snake position vertically on edge of screen
        if (snakeY < 0) {
            snakeY = tileCount - 1;
        }
        if (snakeY > tileCount - 1) {
            snakeY = 0;
        }
    
        // Draw background
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        // Draw snake
        ctx.fillStyle = '#33aa33';
        for (let i = 0; i < snakeTrail.length; i++) {
            ctx.fillRect(
                snakeTrail[i].x * gridSize,
                snakeTrail[i].y * gridSize,
                gridSize - 2,
                gridSize - 2
            );
    
            // Snake bites its tail
            if (snakeTrail[i].x === snakeX && snakeTrail[i].y === snakeY) {
                tailLength = 5; // Reset tail length
            }
        }
    
        // Add snake head to trail
        snakeTrail.push({ x: snakeX, y: snakeY });
    
        // Remove snake tail segments beyond current length
        while (snakeTrail.length > tailLength) {
            snakeTrail.shift();
        }
    
        // Snake eats food
        if (snakeX === foodX && snakeY === foodY) {
            tailLength++;
            foodX = Math.floor(Math.random() * tileCount);
            foodY = Math.floor(Math.random() * tileCount);
        }
    
        // Draw food
        ctx.fillStyle = '#aa3333';
        ctx.fillRect(
            foodX * gridSize,
            foodY * gridSize,
            gridSize - 2,
            gridSize - 2
        );
    }
    
    // Keyboard controls
    document.addEventListener('keydown', keyPush);
    
    function keyPush(evt) {
        switch (evt.keyCode) {
            case 37: // Left arrow
                if (velocityX !== 1) {
                    velocityX = -1;
                    velocityY = 0;
                }
                break;
            case 38: // Up arrow
                if (velocityY !== 1) {
                    velocityX = 0;
                    velocityY = -1;
                }
                break;
            case 39: // Right arrow
                if (velocityX !== -1) {
                    velocityX = 1;
                    velocityY = 0;
                }
                break;
            case 40: // Down arrow
                if (velocityY !== -1) {
                    velocityX = 0;
                    velocityY = 1;
                }
                break;
        }
    }
    
    // Start the game loop
    setInterval(game, 1000 / 15); // Run the game 15 times per second
    

    Explanation:

    • Canvas Setup: We get the canvas element and set up the drawing context.
    • Game Settings: We define the size of the grid and the canvas, and calculate how many tiles fit on the canvas.
    • Snake Initialization: The snake starts in the middle with an initial tail length.
    • Food Initialization: Food is placed at a random position on the grid.
    • Game Function: This function is called repeatedly to update the game state and redraw everything.
      • Snake Movement: The snake's position is updated based on its velocity.
      • Screen Wrapping: If the snake goes off one edge, it appears on the opposite side.
      • Drawing: The background, snake, and food are drawn on the canvas.
      • Collision Detection: If the snake eats the food, its tail grows, and new food appears.
      • Self-Collision: If the snake runs into itself, the game resets (tail length resets).
    • Controls: The keyPush function updates the snake's velocity based on arrow key presses. It also prevents the snake from reversing direction directly.
    • Game Loop: setInterval is used to call the game function at a regular interval, effectively creating the game loop.

    Running the Game

    1. Save all three files (index.html, styles.css, and script.js) in the same directory.
    2. Open index.html in a web browser.
    3. Use the arrow keys to control the snake.

    Optional Enhancements

    • Score Display: Add a score counter to display how many pieces of food the snake has eaten.
    • Game Over Screen: Instead of resetting immediately, display a "Game Over" message.
    • Mobile Controls: Add on-screen buttons for mobile device compatibility.
    • Speed Increase: Increase the game speed as the snake gets longer.
    • Walls: Prevent the snake from wrapping around the screen, making the game harder.

    Adding a Score Display

    To display the player's score, you can modify the HTML and JavaScript as follows.

    HTML (Add a score display after the heading):

    <h1>Snake Game</h1>
    <p>Your Score: <span id="score">0</span></p>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    

    JavaScript (Update the score when the snake eats food):

    Add a variable to keep track of the score:

    let score = 0;
    const scoreElement = document.getElementById('score');
    

    Update the score when the snake eats food:

    if (snakeX === foodX && snakeY === foodY) {
        tailLength++;
        score++;
        scoreElement.textContent = score;
        foodX = Math.floor(Math.random() * tileCount);
        foodY = Math.floor(Math.random() * tileCount);
    }
    

    Reset the score when the game resets (e.g., when the snake bites its tail):

    if (snakeTrail[i].x === snakeX && snakeTrail[i].y === snakeY) {
        tailLength = 5; // Reset tail length
        score = 0;
        scoreElement.textContent = score;
    }
    

    Feel free to customize the game further to add new features or improve the graphics. Enjoy coding your own Snake game!