Enchant.js Guide

by Patrick Casao, Cal Poly


08 Game Logic

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


08.01 - A Word on Scene's 'enterframe'

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
});
	
to the scene’s code. Code added to this function that will execute as long as the scene is the current scene. We can use this function to do stuff like spawn enemies, projectiles, items, and so on. For our example, we’re going to implement a projectile spawner that uses a scene’s enterframe function.

Let’s implement a spawner in our example code. (Once again, you can access it from here.)

CODE EXAMPLE: Using the 'enterframe' Function

Under 08.1 Enterframe Function, add this:

game.rootScene.addEventListener('enterframe', function() {
	if (bg.age % 15 === 0) {
		var p = new Projectile();
		game.rootScene.addChild(p);
  	}
            
	//08.2 End Conditions
});
	
This adds an 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.

Confirm that the spawner works by clicking RUN. You should see projectiles spawning from the right and moving to the left across the screen.


08.02 - Ending a Game

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.)

CODE EXAMPLE: Ending a Game

For now, the game runs without ending. In this example, let's say the player character must reach the other side without hitting too many projectiles or before time runs out. So now let's add a few conditions that end the game. In the 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();
}
	
The game should now end if: the player runs out of health, the player successfully reaches the other side, or time runs out. Confirm that your game over conditions work by clicking RUN and testing them all out.

In the next section we will discuss Sound.