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

write a snake game in javascript

  1. User

    write a snake game in javascript

  2. Assistant

    Certainly! Below is a simple implementation of the classic Snake game using JavaScript and HTML5 Canvas. You can copy the code into your own HTML and JavaScript files to run and play the game.


    HTML File (index.html):

    <!DOCTYPE html>
    <html>
    <head>
      <title>Snake Game</title>
      <style>
        body {
          text-align: center;
          background-color: #111;
          color: #fff;
        }
        canvas {
          border: 1px solid #fff;
          background-color: #000;
        }
      </style>
    </head>
    <body onload="init();">
      <h1>Snake Game</h1>
      <canvas id="gameCanvas" width="400" height="400"></canvas>
      <p>Use the arrow keys to move the snake.</p>
      <script src="snake.js"></script>
    </body>
    </html>
    

    JavaScript File (snake.js):

    // Get the canvas and context
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // Game settings
    const gridSize = 20; // Size of each cell in the grid
    const tileCount = canvas.width / gridSize;
    
    let snake = [{ x: tileCount / 2, y: tileCount / 2 }]; // Initial snake position
    let velocity = { x: 0, y: 0 }; // Initial movement direction
    let food = getRandomFoodPosition(); // Initial food position
    let score = 0;
    
    // Listen for keyboard events to move the snake
    document.addEventListener('keydown', keyPush);
    
    // Initialize the game
    function init() {
      // Start the game loop
      setInterval(gameLoop, 1000 / 15); // Game loop runs 15 times per second
    }
    
    // Game loop function
    function gameLoop() {
      update();
      draw();
    }
    
    // Update game state
    function update() {
      // Move the snake by adding a new head based on the velocity
      const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
    
      // Wrap the snake position on the edges (uncomment below to enable wall collision)
      head.x = (head.x + tileCount) % tileCount;
      head.y = (head.y + tileCount) % tileCount;
    
      // Uncomment the lines below to end the game when hitting the wall
      /*
      if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
        return gameOver();
      }
      */
    
      // Check collision with self
      for (let segment of snake) {
        if (segment.x === head.x && segment.y === head.y) {
          return gameOver();
        }
      }
    
      snake.unshift(head); // Add new head to the front of the snake
    
      // Check if snake has eaten the food
      if (head.x === food.x && head.y === food.y) {
        score++;
        // Place new food at random position
        food = getRandomFoodPosition();
      } else {
        snake.pop(); // Remove the tail segment if no food eaten
      }
    }
    
    // Draw everything on the canvas
    function draw() {
      // Clear the canvas
      ctx.fillStyle = 'black';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    
      // Draw the snake
      ctx.fillStyle = 'lime';
      for (let segment of snake) {
        ctx.fillRect(
          segment.x * gridSize,
          segment.y * gridSize,
          gridSize - 2,
          gridSize - 2
        );
      }
    
      // Draw the food
      ctx.fillStyle = 'red';
      ctx.fillRect(
        food.x * gridSize,
        food.y * gridSize,
        gridSize - 2,
        gridSize - 2
      );
    
      // Draw the score
      ctx.fillStyle = 'white';
      ctx.font = '20px Arial';
      ctx.fillText('Score: ' + score, 10, 20);
    }
    
    // Handle keyboard input to control the snake
    function keyPush(event) {
      switch (event.keyCode) {
        case 37: // Left arrow key
          if (velocity.x !== 1) {
            velocity = { x: -1, y: 0 };
          }
          break;
        case 38: // Up arrow key
          if (velocity.y !== 1) {
            velocity = { x: 0, y: -1 };
          }
          break;
        case 39: // Right arrow key
          if (velocity.x !== -1) {
            velocity = { x: 1, y: 0 };
          }
          break;
        case 40: // Down arrow key
          if (velocity.y !== -1) {
            velocity = { x: 0, y: 1 };
          }
          break;
      }
    }
    
    // Get a random position for the food
    function getRandomFoodPosition() {
      return {
        x: Math.floor(Math.random() * tileCount),
        y: Math.floor(Math.random() * tileCount),
      };
    }
    
    // Handle game over state
    function gameOver() {
      alert('Game Over! Your score: ' + score);
      // Reset game
      snake = [{ x: tileCount / 2, y: tileCount / 2 }];
      velocity = { x: 0, y: 0 };
      score = 0;
      food = getRandomFoodPosition();
    }
    

    Explanation:

    • Canvas Setup: We use an HTML5 Canvas element to draw the game. The canvas is 400x400 pixels in size.
    • Game Grid: The canvas is divided into a grid, where each cell is 20x20 pixels, making it a 20x20 grid.
    • Snake Representation: The snake is represented as an array of objects, each with x and y properties corresponding to grid positions.
    • Movement Control: The velocity object controls the direction of the snake's movement, which is updated based on user input from the arrow keys.
    • Game Loop: The gameLoop() function is called repeatedly to update the game state and render the graphics.
    • Food Generation: Food is placed at random positions on the grid using the getRandomFoodPosition() function.
    • Collision Detection:
      • Wall Collision: The snake wraps around the canvas edges. You can uncomment the provided code to enable game-over on wall collision.
      • Self-Collision: If the snake's head collides with any part of its body, the game ends.
    • Score Tracking: The player's score increases by 1 each time the snake eats food.
    • Rendering: The draw() function handles all the drawing of the snake, food, and score on the canvas.

    How to Run the Game:

    1. Create the Files:

      • Save the HTML code in a file named index.html.
      • Save the JavaScript code in a file named snake.js in the same directory.
    2. Open the Game:

      • Open index.html in your web browser.
    3. Play:

      • Use the arrow keys (left, up, right, down) to control the snake's movement.
      • Try to eat the red food squares to grow the snake and increase your score.
      • Avoid running into the snake's own body.

    Optional Enhancements:

    • Wall Collision: To make the game more challenging, you can uncomment the code that ends the game when the snake hits the wall.
    • Speed Increase: Gradually increase the speed of the game as the score increases.
    • High Scores: Implement a high score system using localStorage to save the player's best score.

    Enjoy your game!


    Feel free to customize and expand upon this code to add more features or improve the game's appearance.