Level and Game End
We need to check for game and level end so we can transition to either a new game or to the next level.
Level end
We will check for level end on each frame tick. The function to do so will look like this:
function
checkForEndOfLevel
(){
if
(
rocks
.
length
==
0
)
{
switchGameState
(
GAME_STATE_NEW_LEVEL
);
}
}
When the rocks
array length
is 0
, we switch the state to
GAME_STATE_NEW_LEVEL
.
Game end
We do not need to check for the end of the game on each frame
tick. We need to check only when the player loses a ship. We do this
inside the gameStatePlayerDie()
function:
function
gameStatePlayerDie
(){
if
(
particles
.
length
>
0
||
playerMissiles
.
length
>
0
)
{
fillBackground
();
renderScoreBoard
();
updateRocks
();
updateSaucers
();
updateParticles
();
updateSaucerMissiles
();
updatePlayerMissiles
();
renderRocks
();
renderSaucers
();
renderParticles
();
renderSaucerMissiles
();
renderPlayerMissiles
();
frameRateCounter
.
countFrames
();
}
else
{
playerShips
--
;
if
(
playerShips
<
1
)
{
switchGameState
(
GAME_STATE_GAME_OVER
);
}
else
{
resetPlayer
();
switchGameState
(
GAME_STATE_PLAYER_START
);
}
}
}
This is the state function that is called on each frame tick
during the GAME_STATE_PLAYER_DIE
state. First, it checks to see that there are no longer any particles
on the screen. This ensures that the game will not end until the
player ship has finished exploding. We also check to make sure that
all the player’s missiles have finished their lives. We do this so
that we can check for collisions between the playerMissiles ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.