2.7 Game States

In notebook:
edX Advanced HTML5
Created at:
2016-01-18
Updated:
2016-01-18
Tags:
Managing the lifecycle of several balls in the game.
Take note of if(ball.dead) continue;​ trick inside the ​for​ loop to discard the code below
  function updateBalls(delta) {
   // for each ball in the array
   var allBallDead = true;
   for(var i=0; i < ballArray.length; i++) {
     var ball = ballArray[i];
     if(ball.dead) continue; // do nothing if the ball is dead
     // if we are here: the ball is not dead
     allBallDead = false;
     // 1) move the ball
     ball.move();
     // 2) test if the ball collides with a wall
     testCollisionWithWalls(ball);
 
     // Test if the monster collides
     if(circRectsOverlap(monster.x, monster.y,
                         monster.width, monster.height,
                         ball.x, ball.y, ball.radius)) {
        //change the color of the ball
        ball.color = 'red';
        ball.dead = true;
        // Here, a sound effect would greatly improve
        // the experience!
        currentScore+= 1;
     }
     // 3) draw the ball
     ball.draw();
  }
  if(allBallDead) {
     // reset all balls, create more balls each time
     // as a way of increasing the difficulty
     // in a real game: change the level, play nice music!
     nbBalls++;
     createBalls(nbBalls);
   }
}

Splitting the game into several JavaScript files

Isolating functions

All those functions that have no dependence on the framework, e.g. sprite utility functions, collision detection functions, ball constructor functions can all be put outside the game framework

Limit dependencies on shared (global) variables

Instead of using global variables, add parameters to functions

File structure

In the game.js only put the core of the game framework (​init​ and ​mainloop​, game states, scores, levels), and put the rest in separate files: utils.js, sprites.js, collision.js, listeners.js, etc.