Game Development Reference
In-Depth Information
■
You should always use
currentTarget
as opposed to
target
when accessing a container that triggered the
event. the
target
property will usually refer to the child inside of the container that was clicked, as opposed to the actual
container object itself.
Note
The text object inside the roll button is also stored away so you can update it later in the function. A function
named
enableDice
is then called and passed a value of false. This will disable all dice while they are spinning. This
function will be covered in the next section, “Holding Dice.” The scorecard and the Roll button both need to be
disabled during a roll as well, which is done by disabling mouse events on each of them.
When the Roll button is hit, its disabled state is visually represented by setting its
alpha
to 0.7. The
rollsLeft
game variable is decreased by 1, and the text object inside the Roll button is immediately updated to display this. Next,
a loop is set to roll each die.
The die sprites are created with a custom property called
hold
, which is set to false. When these values get
updated during the holding process, they will be skipped and not set to roll in the loop. If they are not held, each die
is given a random frame rate value and then played. After one second, the
stopDice
function is called, which will stop
each die from playing its frames. The random frame rates result in the random frame each die lands on.
Holding Dice
After the dice are rolled, the next step in the round is to select or deselect the dice you wish to hold during your next
roll. Before you can choose these dice, the spinning needs to stop, and several objects need to become active and
clickable. This is all handled in the
stopDice
function, shown in Listing 7-22.
Listing 7-22.
The stopDice Stops the Dice on Random Frames, Based on Their Frame Rate
function stopDice() {
var i, die;
diceValues = [];
for (i = 0; i < NUM_DICE; i++) {
die = diceTray.getChildByName('die' + i);
die.stop();
diceValues[i] = Math.floor(die.currentAnimationFrame) + 1;
}
if (rollsLeft > 0) {
enableDice(true);
var rollBtn = diceTray.getChildByName('rollBtn');
rollBtn.alpha = 1;
rollBtn.mouseEnabled = true;
}
scoreCard.mouseEnabled = true;
}
The game variable
diceValues
is used to store the current values of all dice after each roll. This array is
emptied before setting up the dice loop. Each die is accessed via its name and stopped by calling
stop()
. The
value of each die is pushed to
diceValues
and is determined by the frame it stopped on. You can access this by the
currentAnimationFrame
on a sprite. This value is not a whole number, so you need to floor it. These animation frame
numbers start at 0, so adding a 1 will give you the values that match the dice graphics. Figure
7-12
shows the dice
stopped after the first roll.