Game Development Reference
In-Depth Information
Building the Puzzle Pieces
The puzzle pieces are created by slicing out chunks of graphics from a complete bitmap file. This process is shown in
Listing 5-12.
Listing 5-12. Building the Puzzle Pieces from a Loaded Bitmap Graphic
function buildPuzzle() {
var i, piece;
var l = PUZZLE_COLUMNS * PUZZLE_ROWS;
var col = 0;
var row = 0;
for (i = 0; i < l; i++) {
piece = new createjs.Bitmap('img/mam.png');
piece.sourceRect = new createjs.Rectangle(col * PUZZLE_SIZE, row * PUZZLE_SIZE,
PUZZLE_SIZE, PUZZLE_SIZE);
piece.homePoint = {x: col * PUZZLE_SIZE, y: row * PUZZLE_SIZE};
piece.x = piece.homePoint.x;
piece.y = piece.homePoint.y;
stage.addChild(piece);
pieces[i] = piece;
col ++;
if (col === PUZZLE_COLUMNS) {
col = 0;
row ++;
}
}
}
The pieces in the puzzle are all created in a loop that has the length of the total pieces. Multiplying the number of
columns by the number of rows, declared in the game constants, determines this total number. Starting with column 0
and row 0, the col and row variables are set to represent these values.
The first thing you do in the loop is create a bitmap object using the png file used for the puzzle. Since only a
specific portion of the graphic is wanted for each piece, a Rectangle object is created by using the current column and
row, and the size of the puzzle pieces. Using these values, the areas of the bitmap can be calculated for each piece.
piece.sourceRect = new createjs.Rectangle(col * PUZZLE_SIZE, row * PUZZLE_SIZE, PUZZLE_SIZE,
PUZZLE_SIZE);
Next, each piece is assigned a point object, which holds the location of each piece's home coordinates. The x and
y values are immediately assigned to each bitmap so the puzzle starts out intact. This gives the player a view of the
puzzle at its complete state. They are each then added to the stage and pushed to the pieces array.
Lastly, the current column is increased by one so the start location of the bitmap is adjusted in the next iteration.
If you've reached the end of the total columns, it's reset back to 0, and the current row is increased by one.
The result is shown in Figure 5-9 . Although it looks as though you have a single bitmap, there are actually a total
of 15 bitmap objects, perfectly placed on the stage.
 
Search WWH ::




Custom Search