Game Development Reference
In-Depth Information
Drawing the Grid
Now that you have a grid of randomly chosen jewel sprites, you're ready to draw the grid on the
screen. The challenge here is that you need to calculate the position at which each jewel should be
drawn. This position depends on the row and column index of the jewel you want to draw. So, you
use a nested
for
loop to go through all the rows and columns and then draw the jewel at each row
and column index. To retrieve the jewel, you use the
getGridValue
method that you defined earlier.
Here is the complete
draw
method:
JewelJamGameWorld.prototype.draw = function (delta) {
Canvas2D.drawImage(sprites.background);
for (var row = 0; row < this.rows; row++) {
for (var col = 0; col < this.columns; col++) {
var position = new Vector2(85 + col * 85, 150 + row * 85);
Canvas2D.drawImage(this.getGridValue(col, row), position);
}
}
};
In this code, you can see the advantage of using a grid. By using the indices, you can calculate the
position of the sprite in a very convenient way. The whole grid should be drawn at an offset of
(85, 150), so you add 85 to the
x
-coordinate and 150 to the
y
-coordinate of the local
position
variable. To calculate the actual position of the sprite, you multiply the indices by 85 (the width and
height of the sprite) to get the final position. The offset value can be stored in a configuration variable
at the start of the script. That way, if different levels use different background sprites, you only need
to update that variable instead of having to go through the drawing code to update the offsets. Later,
you see another way to deal with this. Figure
14-1
shows a screenshot of the
JewelJam2
example.
Search WWH ::
Custom Search