Implement the States for the Game

Understand and implement the different states in our game logic.

Introduction

In this game, we are going to use many concepts and implementations from the Phaser library that we discussed in the Introduction to Phaser.js lesson. To implement this game, we'll be using different states, several tile sprites, various physics concepts to move the objects, and so on. But before all of that, we need to create all the game states and the initialization logic for our game. Let's start by creating a function that will be called every time the web page is loaded.

Create the game states

We'll create a function and set it to the onload event. In this function, we will mainly perform the following steps:

  1. Create a Game object by specifying the width, height, the rendering mode (namely AUTO to detect either to use webGL or canvas, depending on the browser), and the HTML element's ID (to render the game).

  2. Create a state named BootState to set the background color and the scale mode to display the complete game world (the term used by Phaser to denote a game). We will also start the next state of our game to load the assets required.

  3. Create another state named PreloadState to load all the required assets in the game. Then, we'll also start the next state of the game.

  4. Create our final state named GameState, which will call two functions:

    1. createGame(): For initialization and rendering the game when the page gets loaded.

    2. updateState(): To update the game continuously.

Let's look at the code below:

Get hands-on with 1200+ tech skills courses.