How to Create A Snake Game with
HTML,CSS, JavaScript
Snake is an exemplary game that large number of individuals have played. Have you at any point contemplated making your own Snake Game? Making a Snake Game utilizing HTML, CSS, and vanilla JavaScript is a tomfoolery and instructive venture that can further develop your web improvement abilities.
In this blog entry, I'll direct you through the means of making your own Snake Game without any preparation. You can play this game on a PC utilizing console bolt keys or on a cell phone utilizing contact based bolt fastens.
Video Tutorial of Snake Game
Snake Game [Source Codes]
To Create A Snake Game follow the given steps line by line:
Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
Create an index.html file. The file name must be index and its extension .html
Create a style.css file. The file name must be style and its extension .css
Create a script.js file. The file name must be style and its extension .js
Once you create these files, paste the given codes into the specified files. If you don’t want to do these then download the source code.
First, paste the following codes into your index.html file
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Snake Game</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
- </head>
- <body>
- <div class="wrapper">
- <div class="game-details">
- <span class="score">Score: 0</span>
- <span class="high-score">High Score: 0</span>
- </div>
- <div class="play-board"></div>
- <div class="controls">
- <i data-key="ArrowLeft" class="fa-solid fa-arrow-left-long"></i>
- <i data-key="ArrowUp" class="fa-solid fa-arrow-up-long"></i>
- <i data-key="ArrowRight" class="fa-solid fa-arrow-right-long"></i>
- <i data-key="ArrowDown" class="fa-solid fa-arrow-down-long"></i>
- </div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
Now paste the following codes into your style.css file
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- font-family: Arial, sans-serif;
- }
- body {
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 100vh;
- background: #1EA8EF;
- }
- .wrapper {
- width: 95vmin;
- height: 70vmin;
- display: flex;
- overflow: hidden;
- flex-direction: column;
- justify-content: center;
- border-radius: 5px;
- background: #606060;
- box-shadow: 0 20px 40px rgba(52, 87, 220, 0.2);
- }
- .game-details {
- color: #f2f2f2;
- font-weight: 500;
- font-size: 1.2rem;
- padding: 20px 27px;
- display: flex;
- justify-content: space-between;
- }
- .play-board {
- height: 100%;
- width: 100%;
- display: grid;
- background: #282A35;
- grid-template: repeat(30, 1fr) / repeat(30, 1fr);
- }
- .play-board .food {
- background: #FEFE33;
- border-radius: 50%;
- box-shadow: 0 0 10px rgba(254, 254, 51, 0.9);
- }
- .play-board .head {
- background: #3674A4;
- border-radius: 20%;
- font-size: 50px;
- }
-
-
- .controls {
- display: none;
- justify-content: space-between;
- }
- .controls i {
- padding: 25px 0;
- text-align: center;
- font-size: 1.3rem;
- color: #B8C6DC;
- width: calc(100% / 4);
- cursor: pointer;
- border-right: 1px solid #171B26;
- }
-
- @media screen and (max-width: 800px) {
- .wrapper {
- width: 90vmin;
- height: 115vmin;
- }
- .game-details {
- font-size: 1rem;
- padding: 15px 27px;
- }
- .controls {
- display: flex;
- }
- .controls i {
- padding: 15px 0;
- font-size: 1rem;
- }
- }
Now paste the following codes into your script.js file
- const playBoard = document.querySelector(".play-board");
- const scoreElement = document.querySelector(".score");
- const highScoreElement = document.querySelector(".high-score");
- const controls = document.querySelectorAll(".controls i");
-
- let gameOver = false;
- let foodX, foodY;
- let snakeX = 5, snakeY = 5;
- let velocityX = 0, velocityY = 0;
- let snakeBody = [];
- let setIntervalId;
- let score = 0;
-
- let highScore = localStorage.getItem("high-score") || 0;
- highScoreElement.innerText = `High Score: ${highScore}`;
-
- const updateFoodPosition = () => {
-
- foodX = Math.floor(Math.random() * 30) + 1;
- foodY = Math.floor(Math.random() * 30) + 1;
- }
-
- const handleGameOver = () => {
-
- clearInterval(setIntervalId);
- alert("Game Over! Press OK to replay...");
- location.reload();
- }
-
- const changeDirection = e => {
-
- if(e.key === "ArrowUp" && velocityY != 1) {
- velocityX = 0;
- velocityY = -1;
- } else if(e.key === "ArrowDown" && velocityY != -1) {
- velocityX = 0;
- velocityY = 1;
- } else if(e.key === "ArrowLeft" && velocityX != 1) {
- velocityX = -1;
- velocityY = 0;
- } else if(e.key === "ArrowRight" && velocityX != -1) {
- velocityX = 1;
- velocityY = 0;
- }
- }
-
- controls.forEach(button => button.addEventListener("click", () => changeDirection({ key: button.dataset.key })));
-
- const initGame = () => {
- if(gameOver) return handleGameOver();
- let html = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`;
-
- if(snakeX === foodX && snakeY === foodY) {
- updateFoodPosition();
- snakeBody.push([foodY, foodX]);
- score++;
- highScore = score >= highScore ? score : highScore;
- localStorage.setItem("high-score", highScore);
- scoreElement.innerText = `Score: ${score}`;
- highScoreElement.innerText = `High Score: ${highScore}`;
- }
-
- snakeX += velocityX;
- snakeY += velocityY;
-
- for (let i = snakeBody.length - 1; i > 0; i--) {
- snakeBody[i] = snakeBody[i - 1];
- }
- snakeBody[0] = [snakeX, snakeY];
- if(snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
- return gameOver = true;
- }
-
- for (let i = 0; i < snakeBody.length; i++) {
-
- html += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`;
-
- if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
- gameOver = true;
- }
- }
- playBoard.innerHTML = html;
- }
-
- updateFoodPosition();
- setIntervalId = setInterval(initGame, 100);
- document.addEventListener("keyup", changeDirection);
If you face any difficulties while creating Snake Game with JavaScript or your code is not working as expected, you can download the source code files by clicking download button.