Episode 5: Structure

Projects may vary on size. Here is gradation of Phaser projects and best practices to work with different type of games.

Smallest projects

If you use only one state you can do it really quick and dirty:

var game = new Phaser.Game(640, 480, Phaser.CANVAS, '', this);
function preload() {
// load some stuff
function create() {
// your program

Next step in evolution is to create one state app but without polluting global scope (window object):

var game = new Phaser.Game(640, 480);
var OneStateGame = function () {
this.img = null;
OneStateGame.prototype = {
preload: function () {
this.load.image('img', 'assets/photonstorm.png');
create: function () {
this.img = this.add.sprite(0, 0, 'img');
update: function () {
this.img.x = this.world.randomX;
this.img.y = this.world.randomY;
// add and run
game.state.add('Game', OneStateGame, true);

Medium sized projects

In such case we will separate every state in different files.

Let’s view what we should put in few basic files needed for almost every project:

  • Boot.js – here we’re setting environment for our game preloading files for preloader (Jesus!) and setting FPS or Scale Manager.
  • Preloader.js – here is the place to show a progress of loading other assets needed four our program. We should also decode any music needed in next state right here. Let’s check a source for basic preloader:
    MediumGame.Preloader = function(game) {
    this.preloader = null;
    this.ready = false;
    MediumGame.Preloader.prototype = {
    preload: function() {
    // create sprite object
    this.preloader = this.add.sprite(0,100, 'preloader');
    // load ya stuff here mate!
    update: function() {
    if(this.cache.isSoundDecoded('music') && this.ready == false) 
    this.ready = true;
  • Menu.js – nothing to add here 🙂
  • Game.js – let the fun begin! Remember to encapsulate different parts of game logic into different files for eg. you should put AI into other file. Reason for that is to not build large classes that are hard to maintain.

Large projects

In very big apps you should put everything into different files. This way you can reuse your code in many states. There is no strict guideline how to do this – you’ll find out this during development of your projects.

Well that’s all for now. In next episodes I’ll write about development of my first real game. I think there will be a lot of do’s and don’ts based on my experience so stay tuned!