Game Development

Snake Game using Phaser

Loading an Image

Right now, our game doesn't do anything. Let's code the Menu state, and make it display the title screen. During the setup we included the Phaser library in our HTML file. This gives us a global object called Phaser. Through it, we can access the library's methods and functions for building games. Now we will use the global Phaser object, and create a new game instance. This is an object which represents our entire game. We will add the states to it.

main.js


var game;

// Create a new game instance 600px wide and 450px tall:
game = new Phaser.Game(600, 450, Phaser.AUTO, '');

// First parameter is how our state will be called.
// Second parameter is an object containing the needed methods for state functionality
game.state.add('Menu', Menu);

game.state.start('Menu');

menu.js

Now we need to initialize our Menu state object. In menu.js define a new object and add the functions below. When the state is started, the preload function will be called first, loading all the needed assets for our game. Once preloading finishes, create gets called, initializing the playing field and everything we want on it:


var Menu = {

    preload : function() {
    // Loading images is required so that later on we can create sprites based on the them.
    // The first argument is how our image will be refered to, 
    // the second one is the path to our file.
    game.load.image('menu', './assets/images/menu.png');
    },
        
    create: function () {
    // Add a sprite to your game, here the sprite will be the game's logo
    // Parameters are : X , Y , image name (see above) 
    this.add.sprite(0, 0, 'menu');
    }
        
};

Because of browser security restrictions, to start the game you'll need a locally running web server. This page from the Phaser guidelines has plenty of options for all operating systems - here. In other words, it won't work if you simply double click your index.html.
If everything has been done right, a page with the the start screen should appear in your browser.