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:HTMLCSSJavaScriptApproachSelect 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: Comment More infoAdvertise with us Next Article Design Dragon's World Game using HTML CSS and JavaScript snehaaagupta2002 Follow Improve Article Tags : Technical Scripter JavaScript Web Technologies Technical Scripter 2022 JavaScript-Projects +1 More 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 Like