Open In App

Create a snake game using HTML, CSS and JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over.

Game Rules:

  • If the snake goes out of the boundary or eats its own body the game will be over.

Prerequisites:

Approach

  • Select the board id from the HTML and add functionality to that board using JavaScript like board size, snake color, food color, Snake size, food size snake position.
  • Create the background of a game using the JavaScript fillstyle() method.
  • Place food on the board using Math.random().
  • Select the speed of the snake using setInterval().

Example: Below is the implementation of the above approach.

Javascript




let blockSize = 25;
let total_row = 17; //total row number
let total_col = 17; //total column number
let board;
let context;
 
let snakeX = blockSize * 5;
let snakeY = blockSize * 5;
 
// Set the total number of rows and columns
let speedX = 0;  //speed of snake in x coordinate.
let speedY = 0;  //speed of snake in Y coordinate.
 
let snakeBody = [];
 
let foodX;
let foodY;
 
let gameOver = false;
 
window.onload = function () {
    // Set board height and width
    board = document.getElementById("board");
    board.height = total_row * blockSize;
    board.width = total_col * blockSize;
    context = board.getContext("2d");
 
    placeFood();
    document.addEventListener("keyup", changeDirection);  //for movements
    // Set snake speed
    setInterval(update, 1000 / 10);
}
 
function update() {
    if (gameOver) {
        return;
    }
 
    // Background of a Game
    context.fillStyle = "green";
    context.fillRect(0, 0, board.width, board.height);
 
    // Set food color and position
    context.fillStyle = "yellow";
    context.fillRect(foodX, foodY, blockSize, blockSize);
 
    if (snakeX == foodX && snakeY == foodY) {
        snakeBody.push([foodX, foodY]);
        placeFood();
    }
 
    // body of snake will grow
    for (let i = snakeBody.length - 1; i > 0; i--) {
        // it will store previous part of snake to the current part
        snakeBody[i] = snakeBody[i - 1];
    }
    if (snakeBody.length) {
        snakeBody[0] = [snakeX, snakeY];
    }
 
    context.fillStyle = "white";
    snakeX += speedX * blockSize; //updating Snake position in X coordinate.
    snakeY += speedY * blockSize;  //updating Snake position in Y coordinate.
    context.fillRect(snakeX, snakeY, blockSize, blockSize);
    for (let i = 0; i < snakeBody.length; i++) {
        context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
    }
 
    if (snakeX < 0
        || snakeX > total_col * blockSize
        || snakeY < 0
        || snakeY > total_row * blockSize) {
         
        // Out of bound condition
        gameOver = true;
        alert("Game Over");
    }
 
    for (let i = 0; i < snakeBody.length; i++) {
        if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {
             
            // Snake eats own body
            gameOver = true;
            alert("Game Over");
        }
    }
}
 
// Movement of the Snake - We are using addEventListener
function changeDirection(e) {
    if (e.code == "ArrowUp" && speedY != 1) {
        // If up arrow key pressed with this condition...
        // snake will not move in the opposite direction
        speedX = 0;
        speedY = -1;
    }
    else if (e.code == "ArrowDown" && speedY != -1) {
        //If down arrow key pressed
        speedX = 0;
        speedY = 1;
    }
    else if (e.code == "ArrowLeft" && speedX != 1) {
        //If left arrow key pressed
        speedX = -1;
        speedY = 0;
    }
    else if (e.code == "ArrowRight" && speedX != -1) {
        //If Right arrow key pressed
        speedX = 1;
        speedY = 0;
    }
}
 
// Randomly place food
function placeFood() {
 
    // in x coordinates.
    foodX = Math.floor(Math.random() * total_col) * blockSize;
     
    //in y coordinates.
    foodY = Math.floor(Math.random() * total_row) * blockSize;
}


HTML




<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport",
          content="width=device-width, initial-scale=1.0">
    <title>Snake Game with GFG</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>
 
<body>
    <h1>Snake Game with
          <div class="geeks">Geeks For Geeks</div>
    </h1>
    <canvas id="board"></canvas>
</body>
 
</html>


CSS




/* Write CSS Here */
body {
    text-align: center;
}
.geeks {
    font-size: 40px;
    font-weight: bold;
    color: green;
}


Output:

Snake Game with GFG



Last Updated : 26 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads