Open In App

Create a snake game using HTML, CSS and JavaScript

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

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 JavaScript

Output:

1

Similar Reads