Game Development Reference
In-Depth Information
var lives = 5;
var score = 0;
var level = 0;
var gameRunning = true;
The first set of variables is created for the stage and most of the visuals in the game, including messaging. Some
variables are also set up that will be used to reference the bounds of the screen. The next two,
leftKeyDown
and
rightKeyDown
, are used to help with the game controls.
Next is a series of variables that are declared with initial values. These are grouped for easy reference for all values
that should be reset when restarting the game.
The
bricks
array will start empty and eventually be used to reference all bricks created in the game. You'll add
and remove bricks to this array during gameplay. The
paddleHits
variable will increase in value on each hit of the
paddle, and is used to determine when a new level should be added to the board. The
combo
value similarly gets
increased during play and represents the number of bricks busted in a row before hitting the paddle. This gives the
player combo bonuses. The number of remaining lives, the score, and current level are also declared with initial
values.
The
gameRunning
variable is used for some very simple state logic. This game has a pause feature that can be
triggered via the spacebar. This key is also used to replay the game after losing, so this simple Boolean value can be
used to determine what state the game is in when the user hits the spacebar. When
gameRunning
is
true
, it should
toggle the pause feature. When it's
false
, it will simply call a function to restart the game.
Finally, the data is created to be used when creating the levels (see Listing 4-3). Each index in the
levels
array
holds an object that determines the color of bricks and the points each one is worth when busted.
Listing 4-3.
Creating the Level Data
var levels = [
{color:'#705000', points:1},
{color:'#743fab', points:2},
{color:'#4f5e04', points:3},
{color:'#1b5b97', points:4},
{color:'#c6c43b', points:5},
{color:'#1a6d68', points:6},
{color:'#aa7223', points:7},
{color:'#743fab', points:8},
{color:'#4f5e04', points:9},
{color:'#1b5b97', points:10},
{color:'#c6c43b', points:11},
{color:'#1a6d68', points:12}
];
With the game variables declared, it's time to move on to initializing the game.
Initializing the Game
Initializing the game is usually called within some sort of
init
function and is often called when the document and/or
game assets are completely finished loading. You've seen this done already in previous examples. All graphics will be
created with code in this game project so you don't need to load in any graphics or sounds. Because of this, the
onload
event will be used within the
body
of the document to call the
init
function. Listing 4-4 shows this function.