Making A Snake Game In Javascript

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

Free Ethical Hacking Course Free

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 –

Free Ethical Hacking Course Free

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

Free Ethical Hacking Course Free
					<!DOCTYPE html>
<html lang="en">
    <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">
        Score: 0
        HiScore: 0

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("");
* {
  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) {
    // console.log(ctime)
    if ((ctime - lastPaintTime) / 1000 < 1 / speed) {
    lastPaintTime = ctime;
function isCollide(snake) {
    // If you bump into yourself
    for (let i = 1; i < snakeArr.length; i++) {
        if (snake[i].x === snake[0].x &#038;&#038; 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 &#038; Food
    if (isCollide(snakeArr)) {;
        inputDir = { x: 0, y: 0 };
        alert("Game Over. Press any key to play again!");
        snakeArr = [{ x: 13, y: 15 }];;
        score = 0;
    if (snakeArr[0].y === food.y &#038;&#038; snakeArr[0].x === food.x) {;
        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'); = e.y; = e.x;
        if (index === 0) {
        else {
    // Display the food
    foodElement = document.createElement('div'); = food.y; = food.x;
// Main logic starts here;
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.addEventListener('keydown', e => {
    inputDir = { x: 0, y: 1 } // Start the game;
    switch (e.key) {
        case "ArrowUp":
            inputDir.x = 0;
            inputDir.y = -1;
        case "ArrowDown":
            inputDir.x = 0;
            inputDir.y = 1;
        case "ArrowLeft":
            inputDir.x = -1;
            inputDir.y = 0;
        case "ArrowRight":
            inputDir.x = 1;
            inputDir.y = 0;

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.  


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

Spread the love
Free Ethical Hacking Course Free

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Ethical Hacking Course Free