Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Design Dragon's World Game using HTML CSS and JavaScript
Next article icon

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:

  • HTML
  • CSS
  • JavaScript

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
/* Write CSS Here */ body {     text-align: center; } .geeks {     font-size: 40px;     font-weight: bold;     color: green; } 
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;  } 

Output:

1

Next Article
Design Dragon's World Game using HTML CSS and JavaScript

S

snehaaagupta2002
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2022
  • JavaScript-Projects

Similar Reads

    Create a snake game using HTML, CSS and JavaScript
    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.Prerequ
    4 min read
    Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.  The project will contain HTML, CSS and JavaScript files. The H
    6 min read
    Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
    Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
    Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over.Prerequisite
    5 min read
    Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
    Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image
    3 min read
    Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
    Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to
    5 min read
    Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences