The codeleap for this section may be accessed here. In this section, we will discuss game logic, i.e. beginning and ending a game based on some set conditions. Following this explanation, we will implement some game ending conditions.
Subsections
01 A Word on Scene's 'enterframe'
02 Ending a Game
We’ve discussed onenterframe
before as a function of the Sprite class. Scenes may also have an enterframe
function, implemented by adding this function:
game.rootScene.addEventListener(‘enterframe’, function(){
//CODE HERE
});
enterframe
function.
game.rootScene.addEventListener('enterframe', function() {
if (bg.age % 15 === 0) {
var p = new Projectile();
game.rootScene.addChild(p);
}
//08.2 End Conditions
});
enterframe
event listener to the scene. You'll notice a snippet that says bg.age % 15 === 0
. This statement is true every time the age of bg
is divisible by 15, or every 15 frames. Within this condition, a new Projectile with the name p
is created and added to the scene. So this spawner we've implemented spawns a new projectile every 15 frames.
There are two conditions by which a game may end: player victory or player defeat. How this is defined is ultimately up to you. Once you reach either of these conditions, you may end the game by using the end function: game.end()
. This code halts the game until the user reloads the code.
Let’s implement a Label in our example code. (Once again, you can access it from here.)
enterframe
function we've just added, under 08.2 End Conditions add:
if(player.health <= 0 || player.x > stageWidth - player.width || player.age > 300){
game.end();
}