Snake Game in 110 lines of code
Tags: javascript, tutorial, game
Published: 2020-09-30 08:34:02

---
title: Snake Game in 110 lines of code
published: true
description: Snake Game in 110 lines of code 
tags: JavaScript, Tutorial, Game
//cover_image: https://dev-to-uploads.s3.amazonaws.com/i/3f1fezhx8q6u06y07fvd.gif[main]
---

In this article, I will build a simple snake game in JavaScript from scratch. The player can control the snake by keyboard. Whenever the snake collides with food(a red circle), it gets 1 point and food moves to a random position.

You can view the finished application [here](https://bibhuticoder.github.io/snakefromscratch/). And the source code is [here](https://github.com/bibhuticoder/snakefromscratch).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/530ff2hv2svv3s6tjdc1.gif)

>This article originally appeared 4 years ago at [bibhuticoder.blogspot.com](https://bibhuticoder.blogspot.com/2016/08/buildsnake-game-in-javascript-from.html). It was re-written for the demonstration of an awesome tool [RamroCode](https://ramrocode.netlify.app/#/). Hope you like the beautiful code snippets 🙂

The requirements for this application are basic knowledge of HTML, JavaScript, and some prior knowledge of HTML canvas.
The file structure of the application looks something like this:

**index.html**: contains the HTML code

**script.js**: contains the main logic of the application

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dpbscchb4v1rr4n5980s.png)

The canvas is given the height and width of `500px` and border-style ‘solid’ so we can view it clearly. It is given the id ‘canvas’ to reference it from `script.js` file. That’s all for HTML. Open it in your browser and you will see an empty white box. That’s our canvas.

Now let’s move on to the scripting part. Initially, we get reference to the canvas so that we can draw on it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p27qp77dwtgepme0s16a.png)

In order to use canvas, we get reference to the context of the canvas. The parameter `2d` is passed, which specifies that we are working in 2D. Next, we declare some variables which will hold our snake, food, score, direction, speed etc. Information of each variable is in the comments.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vtf641s5chptl1loe521.png)

Now we have our variables ready, we initialize our snake. Initially, snake array is empty. It’s supposed to contain the coordinates of the snake. Let’s do that now.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5znu4gsdoo4a848yt7cr.png)

The for loop goes from 0 to `length`. Each time it adds a circle to the snake array so that the circle lies exactly to the left of the previous circle. For that, the x-coordinate of the circle is decreased each time by (size*2) and the y-coordinate is kept constant. After the snake is made ready we call the `setInterval` function which takes two parameters: a function to call each interval and an integer number which is the interval in milliseconds. In our case, it’s 100. i.e the function draw is called once in every 100 milliseconds.

The `draw` function is the main part of our program where the magic happens. In every 100 milliseconds, the draw function is invoked which clears the canvas, updates the position of the snake based on its direction, and redraws it. This happens so quickly that we don’t even notice. At the same time, it checks the collision of snake and food and updates the score too.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jdwx37r3bysw9z9kbk5l.png)

`ctx.clearRect()` method clears the canvas before redrawing. The successive for-loop loops over the circles of the snake from its tail to head (from the last index to the first index). If the current index is not the head, it sets it to its preceding circle. i.e. the last circle takes the position of second last circle, second last takes the position of third last, and so on… so that the snake seems as if it’s moving.

If the current index is head, first it checks the direction(at switch case) and increases the coordinate of the circle according to that direction.

**Right**: increase x-coordinate
**Left**: decrease x-coordinate
**Up**: decrease y-coordinate
**Down**: increase y-coordinate

After adding and subtracting the coordinate it should be drawn on the canvas so that the player can see the moving snake. The code below draws each circle of the snake with its updated coordinates.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iszwavb9kv2fqvun0v3m.png)

Now the snake is drawn on the canvas. But it’s not the only thing to draw, we still need to draw the food and score. Drawing the food is similar to drawing the circles of the snake. In case of food, we fill it with red color. The next issue is checking the collision. The function `checkCollission()` does the job and returns a Boolean value. It takes two circles as its parameter, in our case, it’s the snake’s head and the food.

![7](https://dev-to-uploads.s3.amazonaws.com/i/czl78lffz9x2t5niyzf0.png)

The logic for the above function is quite simple. It what we studied in our school. First, we take the distance between the central points of two circles and compare it with the sum of their radii. If it is greater: no collision; else: they collided. The illustration will clear the concept.

![8](https://dev-to-uploads.s3.amazonaws.com/i/vycqve47mu4ek39zp4tf.png)

If `checkCollission()` returns true, first the score is increased and the food is placed on any random position between 0 to width/height of the canvas. The random function takes two parameter min, max, and gives a random number between them.

![9](https://dev-to-uploads.s3.amazonaws.com/i/f0dkl6ig6xlebz0usrpr.png)

Now we have come to the end. The last piece of the puzzle is the `keydown` event handler. We need to control the direction of the snake according to the keyboard button pressed. 

![10](https://dev-to-uploads.s3.amazonaws.com/i/vi7qpjf1ku6mjztzlu9m.png)

The `onkeydown` handler is invoked whenever a key is pressed down. Then we check if the key is right, left, up or down arrow and assign the respective direction. `37`, `38`, `39` and `40` are the keyCode (ASCII value) for left, up, right and down arrows. Now save the file and open it in your browser.

The code doesn’t work yet. It’s because, for the code to work the `timer` should start, which we haven’t done yet. As you have noticed, the timer is set in `init()` function. So call the init function at the last line of your code, save it, and refresh the browser. You can see a moving snake that you can control with the keyboard’s arrow keys.

Happy Coding !