Making A Snake Game In Javascript

Snake game in javascript
Table of Contents

Snake game everyone must had played it when they were small so today I am going to make a snake game in javascript.

If you are a new programmer you should try to create a snake game if you have created or you have failed to create don’t worry today I will show you how to make a snake game in javascript.

Javascript is a programming language and we will use this language to create the snake game and I will give the source code of the game to you. So you just have to copy and paste.

You can get the source code from github this is the link – snake game source code

You cannot play this game on a mobile phone you need a laptop or a computer to play you have to use arrow keys to play.

It is a web game so you don’t have to install it you can run it in your browser. You can play or preview this game here –

Making a snake game in javascript

So inorder to follow along you need to have a code editor If you don’t have vs code than I will recommend you to download and install it – Download vs code.

Vs code is a code editor it is the best mostly used code editor.

Create index.html file

So your first step is to open a folder and create a index.html file this is where all the html code will go it is the structure of the snake game.

After creating paste this code

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SnakeMania - Ek Gaming Katha</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="body">
        <div id="scoreBox">Score: 0</div>
        <div id="hiscoreBox">HiScore: 0</div>
        <div id="board"></div>
    </div>
</body>
<script src="js/index.js"></script>
</html>
				
			

Create style.css

Now you have to create css file you can name it anything but it should be a .css file. In this file we will put all the css code which will make our snake game beautiful.

After creating the file paste this code

				
					@import url("https://fonts.googleapis.com/css2?family=New+Tegomin&display=swap");
* {
  padding: 0;
  margin: 0;
}

.body {
  min-height: 100vh;
  background-size: 100vw 100vh;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
}

#scoreBox {
  position: absolute;
  top: 9px;
  left: 20px;
  font-size: 35px;
  font-weight: bold;
}

#hiscoreBox {
  position: absolute;
  top: 9px;
  right: 20px;
  font-size: 35px;
  font-weight: bold;
}

#board {
  background: black;
  width: 90vmin;
  height: 92vmin;
  border: 2px solid black;
  display: grid;
  grid-template-rows: repeat(18, 1fr);
  grid-template-columns: repeat(18, 1fr);
}

.head {
  background: rgb(35, 185, 245);
  border: 2px solid rgb(34, 4, 34);
  transform: scale(1.02);
  border-radius: 9px;
}

.snake {
  background-color: white;
  border: 0.25vmin solid white;
  border-radius: 12px;
}

.food {
  background: red;
  border: 0.25vmin solid black;
  border-radius: 8px;
}

				
			

Create index.js file

Now create a javascript file which will hold the logic of the snake game

				
					// Game Constants & Variables
let inputDir = { x: 0, y: 0 };
const foodSound = new Audio('music/food.mp3');
const gameOverSound = new Audio('music/gameover.mp3');
const moveSound = new Audio('music/move.mp3');
const musicSound = new Audio('music/music.mp3');
let speed = 10;
let score = 0;
let lastPaintTime = 0;
let snakeArr = [
    { x: 13, y: 15 }
];

food = { x: 6, y: 7 };

// Game Functions
function main(ctime) {
    window.requestAnimationFrame(main);
    // console.log(ctime)
    if ((ctime - lastPaintTime) / 1000 < 1 / speed) {
        return;
    }
    lastPaintTime = ctime;
    gameEngine();
}

function isCollide(snake) {
    // If you bump into yourself 
    for (let i = 1; i < snakeArr.length; i++) {
        if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
            return true;
        }
    }
    // If you bump into the wall
    if (snake[0].x >= 18 || snake[0].x <= 0 || snake[0].y >= 18 || snake[0].y <= 0) {
        return true;
    }

    return false;
}

function gameEngine() {
    // Part 1: Updating the snake array & Food
    if (isCollide(snakeArr)) {
        gameOverSound.play();
        musicSound.pause();
        inputDir = { x: 0, y: 0 };
        alert("Game Over. Press any key to play again!");
        snakeArr = [{ x: 13, y: 15 }];
        musicSound.play();
        score = 0;
    }

    if (snakeArr[0].y === food.y && snakeArr[0].x === food.x) {
        foodSound.play();
        score += 1;
        if (score > hiscoreval) {
            hiscoreval = score;
            localStorage.setItem("hiscore", JSON.stringify(hiscoreval));
            hiscoreBox.innerHTML = "HiScore: " + hiscoreval;
        }
        scoreBox.innerHTML = "Score: " + score;
        snakeArr.unshift({ x: snakeArr[0].x + inputDir.x, y: snakeArr[0].y + inputDir.y });
        let a = 2;
        let b = 16;
        food = { x: Math.round(a + (b - a) * Math.random()), y: Math.round(a + (b - a) * Math.random()) }
    }

    for (let i = snakeArr.length - 2; i >= 0; i--) {
        snakeArr[i + 1] = { ...snakeArr[i] };
    }

    snakeArr[0].x += inputDir.x;
    snakeArr[0].y += inputDir.y;
    board.innerHTML = "";
    snakeArr.forEach((e, index) => {
        snakeElement = document.createElement('div');
        snakeElement.style.gridRowStart = e.y;
        snakeElement.style.gridColumnStart = e.x;

        if (index === 0) {
            snakeElement.classList.add('head');
        }
        else {
            snakeElement.classList.add('snake');
        }
        board.appendChild(snakeElement);
    });
    // Display the food
    foodElement = document.createElement('div');
    foodElement.style.gridRowStart = food.y;
    foodElement.style.gridColumnStart = food.x;
    foodElement.classList.add('food')
    board.appendChild(foodElement);


}


// Main logic starts here
musicSound.play();
let hiscore = localStorage.getItem("hiscore");
if (hiscore === null) {
    hiscoreval = 0;
    localStorage.setItem("hiscore", JSON.stringify(hiscoreval))
}
else {
    hiscoreval = JSON.parse(hiscore);
    hiscoreBox.innerHTML = "HiScore: " + hiscore;
}

window.requestAnimationFrame(main);
window.addEventListener('keydown', e => {
    inputDir = { x: 0, y: 1 } // Start the game
    moveSound.play();
    switch (e.key) {
        case "ArrowUp":
            console.log("ArrowUp");
            inputDir.x = 0;
            inputDir.y = -1;
            break;

        case "ArrowDown":
            console.log("ArrowDown");
            inputDir.x = 0;
            inputDir.y = 1;
            break;

        case "ArrowLeft":
            console.log("ArrowLeft");
            inputDir.x = -1;
            inputDir.y = 0;
            break;

        case "ArrowRight":
            console.log("ArrowRight");
            inputDir.x = 1;
            inputDir.y = 0;
            break;
        default:
            break;
    }

});
				
			

Add Sounds

I have also added sound effects to the snake game I have uploaded the source and sound on github you can download and put sound in music folder.

Remember if the sound doesn’t work you need to change the path of the music in the javascript file.

Play the snake game

Now you have done all the steps so you can play this game you run this game on a desktop. You can play this game by opening index.html file in chrome or if you are using vs code you can install the live server extension and you can play the game in chrome.  

Summary

So your we have made the snake game in javascript. You can also create games like flappy bird in javascript I will make a tutorial on that later so stay tuned.

If you want to become a game developer than you can read this article – Roadmap to become a game developer.

Thank you for reading this article I hope you found what you were looking for if you love our work do subscribe to coderzway newsletter thank you

Share This Post
Share on facebook
Share on twitter
Share on email
Share on whatsapp

Leave a Reply

Subscribe To Our Newsletter

Get updates and learn from the best

Latest Guides & Articles