Snake & How it Works

By Paul Farr

During winter break, I want to do any extra project for myself. I had been learning about JavaScript and HTML5’s canvas element. It is used to draw graphics using JavaScript. I used this to make two other games (a typing game and canyon racing game). As my 3rd game, I wanted a larger challenge. So, I created a snake game in 7 hours, in one day. I have worked on the game more since the first 7 hours, but it was mainly to refactor code.

After working with JavaScript, I’m very disappointed in how OOP in implemented JavaScript. If you go back in the snake games history on Github, you will see that it work more like a C program with a structure that is passed around by functions. I did go back and refactor my code to use OOP and I’m very proud of myself after two years was able to do it in less than an hour.

How the game works on the backend is simple. There are four methods with a small set of helper functions. A ‘setup’ method, ‘display’ method, and a ‘mainLoop’ method.

The setup method would be the contractor in OOP. It sets the default values, all of which are constants at the top of the program and starts the “setInterval()” function that runs the “mainloop” method every game cycle. The setup method also displays some simple instruction to the user about what buttons to press to start the game.

The display method is very straight forward. It draws the screen based on the gameObject. It starts by filling the background; drawing the hub, food, and the full body. When the game ends, it will still draw everything but, will add an end of the game overlay.

The “mainloop” method is called by the “setInterval()” function in from the “setup” function. This method is where all the logic of the program happens. It adds body parts to the snake when the player gets the food; it moves all the body parts forward and checks to see if the player ran into himself or off the map.

There are a few helper functions that would be private functions. One is a random integer function because JavaScript doesn’t have one; a function to spawn food and an on-key-down event function.

This was a fun project, and I also had fun playing it too.