Game Development Reference
In-Depth Information
Ending a level or the game
So now we have put blocks on the screen, removed them, and added blocks back to take their
place. The only thing left to do is to test to see if the level or the game has ended. We do this in
the
GameStates.STATE_WAITING_FOR_INPUT
game state by calling
checkForEndLevel
.
This function does two things. First, it checks to see if the
levelScore
is equal to or greater than
currentLevel.scoreThreshold
. If so, the level has been completed. We play a sound, set the
nextGameState
to
GameStates.STATE_END_LEVEL
, call
fadeBlocks
, and set the
gameState
to
GameStates.STATE_FADE_BLOCKS_WAIT
. Recall that
GameStates.STATE_FADE_BLOCKS_WAIT
continually checks to see if all the
Block
s have faded from the screen before continuing to the
gameState
set in
nextGameState
.
If the level has not been finished, we check to see if
plays
has been exhausted. If so, the game is
over. We perform similar operations to the ones to end a level but, this time, to end the game. We
play a different sound; we set the
nextGameState
to
GameStates.STATE_END_GAME
, call
makeBlocksFall
, and set the
gameState
to
GameStates.STATE_FALL_BLOCKS_WAIT
.
public function checkforEndLevel():void {
if (levelScore >= currentLevel.scoreThreshold) {
dispatchEvent( new CustomEventSound(CustomEventSound.PLAY_SOUND,
Main.SOUND_WIN,false,1,0,1));
nextGameState = GameStates.STATE_END_LEVEL;
fadeBlocks();
gameState = GameStates.STATE_FADE_BLOCKS_WAIT;
} else if (plays <= 0) {
nextGameState = GameStates.STATE_END_GAME;
dispatchEvent( new
CustomEventSound(CustomEventSound.PLAY_SOUND,Main.SOUND_LOSE,false,1,0,1));
makeBlocksFall()
gameState = GameStates.STATE_FALL_BLOCKS_WAIT;
}
}
The
fadeBlocks
function iterates through all the blocks in the
board
2D array and sets every
Block
to fade by calling the
startFade
function of each
Block
; see Figure 8-7. The
Block.startFade
function accepts a
fadeValue
(between 0 and 1) that will decrement the
alpha
value for the
Block
over a series of frames. We send this as a random value so that the fadeout
does not appear completely uniform.
public function fadeBlocks():void {
for (var r:int = 0; r < board.length; r++) {
for (var c:int = 0; c < board[r].length; c++) {
tempBlock = board[r][c];
tempBlock.startFade((Math.random()*.9)+.1);
}
}
}