Jump to content

How to structure my code


spinnerbox
 Share

Recommended Posts

I am learning Phaser 2.2.2 for about 4 days now and I am trying to understand how to I structure my game code. I found that Phaser.State can be used as a screen i.e MainMenuScreen, HelpScreen, LevelsScreen, GameScreen as examples. I would like to separate my code into different files and load them in my index.html. Once the game is finished I can minify them into game.min.js

 

So I want to have spearate files MainMenuScreen.js, GameScreen.js etc... 

 

Phaser has too its own structure and perhaps it is best to follow it. I already have some structure using a namespace() function to create my subobjects but I am already duplicating code that exists in Phaser. For example in my custom states I add gameObject as reference to the Phaser.Game object, but there is already property created when using Phaser.State(game) constructor.

 

I could create prototype chain but then I should use "this" keyword everywhere. 

 

So can somebody point me to some tutorials how to structure my code, or I should continue as I started?

 

The code I have is working well but anyways I wanted to ask...

Link to comment
Share on other sites

Here is my index.html

 

<!doctype html><html>    <head>        <meta charset="UTF-8" />        <title>Game</title>    </head>    <body>        <script src="js/phaser.min.js"></script>        <script type="text/javascript" src="js/Game.js"></script>        <script type="text/javascript" src="js/Screen.js"></script>        <script type="text/javascript" src="js/MainMenuScreen.js"></script>        <script type="text/javascript" src="js/HelpScreen.js"></script>        <script type="text/javascript" src="js/GameScreen.js"></script>        <script type="text/javascript" src="js/LevelsScreen.js"></script>    </body></html>

Here is my Game.js

window.WML = window.WML || (function (windowDocumentObject) {'use strict';    var        documentObject = windowDocumentObject,        config = null,        parent = null,        GAME_NAME = "Game Name",        version = "4.0.0",        fadeDuration = 500,        phaserGame = new Phaser.Game(640, 480, Phaser.AUTO, '');    return {        Exceptions: {},        Constants: {            GAME_NAME: function () {                return GAME_NAME;            }        },        Events: {},        getFadeDuration: function () {            return fadeDuration;        },        getVersion: function () {            return version;        },        getGameObject: function () {            return phaserGame;        },        initApp: function (someObject, config) {            var i;            for (i in someObject) {                if (someObject[i] !== null && typeof someObject[i] === 'object') {                    if (someObject[i].hasOwnProperty('init')) {                        someObject[i].init(config);                    }                    this.initApp(someObject[i], config);                }            }        },        namespace: function (namespaceStr, inheritObject, newObject) {            var parts = namespaceStr.split('.'),                helpObject = Object.create(inheritObject),                _this = this,                i = 0,                prop = {};            if (parts[0] === _this.Constants.GAME_NAME()) {                parts = parts.slice(1);            }            for (i = 0; i < parts.length; i += 1) {                if (_this[parts[i]] === undefined) {                    for (prop in newObject) {                        if (newObject.hasOwnProperty(prop)) {                            helpObject[prop] = newObject[prop];                        }                    }                    _this[parts[i]] = helpObject;                }                _this = _this[parts[i]];            }            return _this;        },        init: function (configObject) {            config = configObject;            parent = this;            phaserGame.state.add(parent.MainMenuScreen.KEY(), parent.MainMenuScreen);            phaserGame.state.add(parent.HelpScreen.KEY(), parent.HelpScreen);            phaserGame.state.add(parent.GameScreen.KEY(), parent.GameScreen);            phaserGame.state.add(parent.LevelsScreen.KEY(), parent.LevelsScreen);            phaserGame.state.start(parent.MainMenuScreen.KEY());            //parent.initApp(parent, config);        }    };    }(window.document));window.document.addEventListener("DOMContentLoaded", function (event) {'use strict';    var wml = window.WML,        config = {"event": event};    wml.init(config);    });

In Screen.js I wanted to keep necessary stuff so all other screens could inherit from it.

 

window.WML.namespace('Screen', (function(wml) {    return {        gameObject: wml.getGameObject(),        fadeTween: null,        screenObjects: null    };}(window.WML)));

MainMenuScreen.js

 

window.WML.namespace('MainMenuScreen', window.WML.Screen, (function(wml) {    var        fadeTween = null,        screenObjects = null,        titlePage = null,        gameObject = wml.getGameObject(),        KEY = 'MainMenuScreen',        playButton = (function() {            return {                button: null,                click: function() {                    fadeTween = gameObject.add.tween(screenObjects).to( { alpha: 0 }, wml.getFadeDuration(), "Linear", true);                    fadeTween.onComplete.add(function () {                        gameObject.state.start(wml.LevelsScreen.KEY());                    }, this);                                    }            };        }()),        helpButton = (function() {            return {                button: null,                click: function() {                    fadeTween = gameObject.add.tween(screenObjects).to( { alpha: 0 }, wml.getFadeDuration(), "Linear", true);                    fadeTween.onComplete.add(function () {                        gameObject.state.start(wml.HelpScreen.KEY());                    });                }            };        }());    return {        Exceptions: {},        Constants: {},        KEY: function() {            return KEY;        },        Events: {},        preload: function() {            this.stage.backgroundColor = 0xC0C0C0;            gameObject.load.image('titlePage', 'assets/images/title-page-new.png');            gameObject.load.spritesheet('playButtonSheet', 'assets/images/UI/playButtonSheet.png', 73, 42, 2);            gameObject.load.spritesheet('helpButtonSheet', 'assets/images/UI/helpButtonSheet.png', 73, 42, 2);        },        create: function() {            screenObjects = gameObject.add.group();                        titlePage = gameObject.add.sprite(0, 0, 'titlePage');            screenObjects.add(titlePage);                        playButton.button = gameObject.add.button(275, 290, 'playButtonSheet', playButton.click, this, 1, 0, 0);            screenObjects.add(playButton.button);                        helpButton.button = gameObject.add.button(275, 340, 'helpButtonSheet', helpButton.click, this, 1, 0, 0);            screenObjects.add(helpButton.button);                        screenObjects.forEach(function (item) {                item.alpha = 0;                gameObject.add.tween(item).to( { alpha: 1 }, wml.getFadeDuration(), "Linear", true);            });        }    };}(window.WML)));

Can somebody understand what I am trying to do?

Link to comment
Share on other sites

I'm using multiple states.  The style was unfamiliar to me at first but it works.  There are some gotchas:

 

1. A lot of examples come from a single state world and the syntax is a bit different - you see a lot of game.blah instead of this.blah.

2. States have a life cycle.  If you dip in and out of your playable state and a menu, you need to deal with the fact that you have to build up and tear down each time.  There is much to learn here and I don't want to take the time to explain all that I have learned about this.   I will say that you should built up your state in create and reclaim memory in shutdown.  I also found it useful to keep some objects global, using a global name space, so that I did not trigger the garbage collector so much (For better or for worse - probably worse - my game architecture involved going back to the menu state a lot)

3. You'll run into lots of typical "this" pointer issues, lots of which can be resolved with ye olde "var that = this".

 

Good luck.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...