Game Development Reference
In-Depth Information
Listing 5-26. Shuffling the Cards Array and Animating Them on a Grid
function shuffleCards() {
var i, card, randomIndex;
var l = cards.length;
var shuffledCards = [];
for (i = 0; i < l; i++) {
randomIndex = Math.floor(Math.random() * cards.length);
shuffledCards.push(cards[randomIndex]);
cards.splice(randomIndex, 1);
}
cards = cards.concat(shuffledCards);
}
function dealCards() {
var i, card;
var xPos = 100;
var yPos = 100;
var count = 0;
for (i = 0; i < cards.length; i++) {
card = cards[i];
card.x = -200;
card.y = 400;
card.rotation = Math.random() * 600;
card.addEventListener('click', flipCard);
stage.addChild(card);
createjs.Tween.get(card)
.wait(i * 100)
.to({x:xPos, y:yPos, rotation:0}, 300);
xPos += 150;
count++;
if (count === 4) {
count = 0;
xPos = 100;
yPos += 220;
}
}
}
Similar to the puzzle pieces shuffle, the cards array is used to shuffle the deck. It's handled a bit differently here to
show an alternative way to shuffle object arrays. A local array named shuffledCards is first declared and set to empty.
As you loop through the array cards , you select and splice out random card objects and push them to the local array
shuffleCards . After the loop, simply give them back by concatenating the local array with the now-empty cards array.
cards = cards.concat(shuffledCards);
The result is a freshly shuffled deck of cards. Now it's time to deal them out in a grid on the stage. A loop is set up
to add each card to the stage, starting off screen and randomly rotated. Each card is then ultimately animated to the
locations determined in the loop. The result is shown in Figure 5-15 .
Search WWH ::




Custom Search