Game Development Reference
In-Depth Information
Listing 7-30. Game Variables Are Reset and All Display Objects Are Removed from the Stage
function replayGame() {
section1Score = section2Score = bonusScore = numScored = 0;
rollsLeft = NUM_ROLLS;
stage.removeAllChildren();
initGame();
}
To reset the game, a list of game variables is reset to 0 and rollsLeft is set back to 3. Next, all four display objects
on the stage are completely removed, and initGame is called, which will start the whole process over and make a
new game.
The game should be completely playable at this point, minus the actual score calculations. After confirming that
you can get to the end of the game and restart it, the Scoring class will be built next.
Calculating the Scores
The scoring functions will be built in a separate object in a separate JavaScript file. Moving functionality into self-
contained objects is a common practice in JavaScript, and makes larger games much more manageable. Building
more complex JavaScript objects as classes will be discussed further in Chapter 8.
To get started with scoring, open the Scoring.js file that was created and added to the document at the
beginning of the chapter. This file will contain only the Scoring object.
Setting Up the Scoring Class
Objects in JavaScript can be set up in several ways and can very much act as working classes. In the case of scoring,
the class will be called statically. In other words, instances of the object will not be created. An example of this would
be the Math object that is built into JavaScript.
var num = Math.floor(123.45);
The object Math has a method named floor that takes one parameter and returns a result. The Scoring class will
be utilized in the same way. Listing 7-31 shows how the object is set up.
Listing 7-31. Settng Up the Scoring Class
var Scoring = {
dice:[],
btnKey:null
};
Scoring.getScore = function (type, dice, key) {
dice.sort();
this.dice = dice;
this.btnKey = key;
}
The object is set up similar to your typical JavaScript object literal and contains two properties, dice and btnKey .
The methods to this object are added directly on the object after it has been declared.
 
Search WWH ::




Custom Search