Game Development Reference
In-Depth Information
if (win) {
setTimeout(function () {
alert('YOU DID IT!');
}, 200);
}
else {
selectedPieces = [];
}
}
Before looping through and evaluating each puzzle piece's location, the bitmaps are uncached, which will
remove the effect filter applied to them. In the loop, you simply check each piece to see if either their
x
or
y
position
does
not
match their “home” location. If this is the case at any time during the loop, you know that the puzzle cannot
be complete. The local
win
variable will then be set to
false
, and the loop is broken.
The
win
value is checked, and if true, a simple alert is called to award the user with a message. If not,
the
selectedPieces
array is emptied, allowing the player to continue swapping puzzle pieces.
Lastly, the typical
startGame
function (shown in Listing 5-17) is used to run the stage updates.
Listing 5-17.
Ticker and Stage Update Function
function startGame() {
createjs.Ticker.addEventListener("tick", function(){
stage.update();
});
createjs.Ticker.setFPS(60);
}
The Complete Puzzle Swap Code
The complete code for the puzzle game is shown in Listing 5-18.
Listing 5-18.
The Complete Code for puzzle.js
const PUZZLE_COLUMNS = 5;
const PUZZLE_ROWS = 3;
const PUZZLE_SIZE = 200;
var stage;
var pieces = [];
var selectedPieces = [];
function init() {
stage = new createjs.Stage('canvas');
buildPuzzle();
startGame();
setTimeout(shufflePuzzle, 2000);
}
function buildPuzzle() {
var i, piece;
var l = PUZZLE_COLUMNS * PUZZLE_ROWS;
var col = 0;
var row = 0;