Game Development Reference
In-Depth Information
The rest of the function will consist of one loop that creates the game assets and assigns them their necessary
properties, for both display and logic. Using the loop's iterator value you can both build and position the slots in a
horizontal line at the top of the stage. While the slots are actually drawn to the stage in this loop, the blocks are simply
instantiated and pushed to an array so you can draw them later at random positions.
A key property is assigned to each slot and block using the iterator value, and can be used later in the game to
determine matches when you drop blocks on the slots.
With the slots drawn on the stage and your block objects instantiated, you are ready to draw the blocks in random
positions (see Listing 3-6).
Listing 3-6. colorDrop.js - setBlocks Function
function setBlocks() {
var i, r, shape;
var l = shapes.length;
for (i = 0; i < l; i++) {
r = Math.floor(Math.random() * shapes.length);
shape = shapes[r];
shape.homeY = 320;
shape.homeX = (i * 130) + 100;
shape.y = shape.homeY;
shape.x = shape.homeX;
shape.addEventListener("mousedown", startDrag);
stage.addChild(shape);
shapes.splice(r, 1);
}
}
A similar loop is created to position the blocks, this time along the bottom. Each iteration grabs a random index
out of the shapes array before placing it on the screen. After you add it, you remove it from the array so you don't grab
the same object again. This makes the array length shorter so it's imperative that you first declare that initial array
length and use it to write your loop. Otherwise, you would get undesired results.
As you randomly choose and draw each block, you also set a few properties to them for reference on where it was
initially drawn. This lets you put it back to this position if you incorrectly drop it somewhere else on the stage.
Finally, a mousedown event listener is registered to each shape so you can create its dragging functionality. This
handler has a good amount of code so you'll avoid writing this function anonymously to preserve legibility.
The last function you call from init sets up a simple game loop to continuously update the stage (see Listing 3-7).
At this point, your game objects are drawn on the stage and registered to fire a function for handling their drags.
Figure 3-3 shows the game elements drawn on the stage and ready for interaction.
Listing 3-7. colorDrop.js - startGame Function
function startGame() {
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", function(e){
stage.update();
});
}
 
Search WWH ::




Custom Search