Let’s make a HTML5 Snake Game!

I’ve made my first game; Snake! It is a simple HTML5 Snake Game.

HTML5 Snake Game

Now we’ll look for how to make a HTML5 snake game.

Before start to coding, let’s look what do you need for making the game;

  • A code editor (I prefer Sublime Text. It is the best!)
  • Pixi.js (Pixi is a very simple 2D library. It is more clean than pure WebGL functions.)

Now, we can start coding!

The SnakeGame() class;

We need a SnakeGame.Game()  class;

..and let we write methods of SnakeGame.Game()  class;

We’ve created the Game.prototype.setSnake()  method, now we need a Snake()  class;

Init method of Snake()  objects. We’ll use this for restarting the game.

We set a property for direction d in Snake()  class, and a step list property ss.

Now we’re creating a method for set current direction;

These are okay. Now we have the real issue; collisions.. There are three collision types;

  1. Border Collision (Detecting collision when snake impact to walls..)
  2. Meal Collision (Detecting snake eating meals.)
  3. Self Collision (Detecting collision when snake impact to itself!

Border Collision

This is more simple than Self Collision and Meal Collision. We can implement this very simply;

Meal Collision

Now we need understand the snake is hungry; This is more difficult than Border Collision.

These are okay..and let’s make the the difficult!..

Self Collision

Three collision types are ok. We can continue..

The Snake Step Method

The game needs a step()  method. This is snake’s frame creation method.

Remember, we’ve already created a main frame creation method  for SnakeGame.Game()  class; SnakeGame.Game.step().

It was like such as;

Now we’re making a frame creation method for the snake;

FPS Synchronization

We need sync FPS with our specified snake speed.

This method has using parameters.delta (0 – 1] variable. This method takes into calculating the parameters.delta  variable.

We’ll get the delta from PIXI.ticker.Ticker()  object and pass it to this method.

Exporting a Game Controller Class

We need a class for exporting a controller class; Game(). We’ll able to control the game like;

  • Create new game
  • Pause or resume controls
  • Shortcuts binding
  • Drawing screen
  • Drawing game menus

We’re using Pixi.js‘s Ticker here.

All game controls is here. We’ll export this game controller class and use it.

Some Helpers

main.js that using Game Controller

Now we’re creating a main.js with using Game()  controller class.

We’ve already set keyboard shortcuts in Game()  controller class..  And make emitting some events from there; finish , begin , pause , coninue ..

A Simple HTML for Game Screen



We’ll include game screen (game.html) with iframe in here.

That’s all.. We creted a HTML5 Snake Game.

You can download source code from Github and play snake.

Share Button

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir