javascripthtml5-canvascode-structure

An strucure to share data between scopes


I am just learning JS and try to write a simple game. So I made a basic structure witch should look something like this (pseudo c++ code):

if (!game.game_stage)
    game.reset_game(); // initialize game objects
if (player1.score > MAX_SCORE || player2.score > MAX_SCORE)
    game.end_round(); stop(1000);
else
    game.update();
game.render();

Then I try to write it in JS:

function main() {
    if (gamest != true) {
        resetgame();
        gamest = true;
    }
    /* UPDATE SECTION */
    if (score1 > 9 || score2 > 9) {
        endround();
        setTimeOut(update, 1000);
    }
    else {
        update();
    }
    /* RENDER SECTION */
    draw();
}

Other functions in main() does now have access to objects initialized in resetgame() function. The other problem that appears is that setTimeOut(update, 1000) does not work when I put all object to global scope for testing.

resetgame() procedure looks pretty much like this:

function resetgame() {
    var paddle1 = new GameObject(20, 80, "LEFT");
    [...]

Does that structure makes any sens?


Solution

  • The problem

    function main() {
        if (gamest != true) {
            resetgame();
            gamest = true;
        }
    

    The resetgame() function is bound inside an if scope. It cause the objects initialized inside this scope to be destroyed after program leaves that scope.

    Closure solution

    To get use of closure concept we need:

    So in this example, we would need a bunch of free object inside the function main() body to save data evaluated by resetgame(). One option will be to pass all those object by arguments to the resetgame() and rewrite it to initialize all arguments to its inner objects.

    Simple OOP solution

    In a game we usually have a lot of objects, so the closure concept will get to complex and memory consuming. The better solution will be to encapsulate all main functions in to one object so we can easy exchange data and pass the object where-ever we need. That let us create an easy to menage structure, e.g.:

    var App = {
        Load: function() {
           this.frame = new Frame();
        },
        // UPDATE
        Update: function() {
           this.frame.updatePosition();
        },
        // RENDER
        Render: function() {
           this.frame.draw();
        }
    };
    
    function Main() {
        var app = App;
        app.Load();
        setInterval(MainLoop(app), 1000/60);
    }
    
    function MainLoop(app) {
        // main application render
        app.Render();
        // main application update
        app.Update();
    }
    

    Someone just remind me about this question. I'm not a JS expert yet but for that application I find my solution. I know that could be solved better but this solution is good enough for the little game I been writing. But if someone have a better one, I will be glad to hear your opinion.