Game Development Reference
In-Depth Information
First let's look at a simplified case where you want to draw a background sprite and, on top of that,
a grid of ten rows times five columns, where each location in the grid is filled with a sprite. The
program that does this is called JewelJam2 , and you can find it in the example code folder belonging
to this chapter.
Creating a Grid of Sprites
The previous chapter showed how to create arrays. Let's put this feature to use in the next example
to create a two-dimensional playing field. The program JewelJam2 contains the instructions
to create a game world consisting of a grid of sprites that can be manipulated. In this particular
example, you don't store the actual sprites in the grid, but rather an integer number that represents
them . That way, you can choose which sprite to draw depending on that number, and perhaps
even do calculations using the numbers in the grid. You load three jewel sprites together with the
background sprite when you start the game:
Game.loadAssets = function () {
var loadSprite = function (sprite) {
return Game.loadSprite("../assets/sprites/" + sprite);
};
sprites.background = loadSprite("spr_background.jpg");
sprites.single_jewel1 = loadSprite("spr_single_jewel1.png");
sprites.single_jewel2 = loadSprite("spr_single_jewel2.png");
sprites.single_jewel3 = loadSprite("spr_single_jewel3.png");
};
In the JewelJamGameWorld class, you create an array that represents the two-dimensional playing
field. In the previous chapter, you saw how to use a one-dimensional array to represent a two-
dimensional grid:
var myGrid = new Array(rows * cols);
var someElement = myGrid[i * cols + j];
So, let's create such a grid in the JewelJamGameWorld class:
this.rows = 10;
this.columns = 5;
this.grid = new Array(this.rows * this.columns);
To make things a bit easier when accessing this grid, define the following two methods for getting
and setting values in the grid:
JewelJamGameWorld.prototype.setGridValue = function (x, y, value) {
var index = y * this.columns + x;
this.grid[index] = value;
};
JewelJamGameWorld.prototype.getGridValue = function (x, y) {
var index = y * this.columns + x;
return this.grid[index];
};
 
Search WWH ::




Custom Search