Game Development Reference
In-Depth Information
As you can see, you simply apply the trick explained in the previous chapter. Initially, you fill the grid
randomly with one of the three jewel sprites you loaded. You could do this as follows:
for (var i = 0; i < this.rows * this.columns; i++) {
var randomval = Math.floor(Math.random() * 3) + 1;
if (randomval === 1)
this.grid[i] = sprites.single_jewel1;
else if (randomval === 2)
this.grid[i] = sprites.single_jewel2;
else
this.grid[i] = sprites.single_jewel3;
}
The first instruction in the body of the for loop generates a random number from the set {1, 2, 3}. In
that instruction, you use Math.random to get a value between 0 and 1, you multiply that value by 3 (to
get a value between 0 and 3), and then you round it down and add 1 to get a value between 1 and 3.
Depending on the value of the random number, you select a different sprite in an if instruction. You
store a reference to the sprite in the grid array.
There is a nice way in JavaScript to shorten this code, because JavaScript allows you to access the
member variables of an object by using an array-like syntax. For example, suppose you've defined
the following object:
var person = {
name : "Arjan",
gender : "male",
married : true
};
You can access the member variables in the regular way, as follows:
person.name = "John";
There is an instruction that is equivalent. It looks like this:
person["name"] = "John";
So, when accessing member variables of objects, you can use the regular syntax, or you can access
the members as an array that is indexed with strings. Why is this useful, you ask? Well, strings can
be concatenated, so you can write some clever code that selects different sprites based on the
randomly generated number. Here is the same for loop as before, but now you use this feature to
write shorter code—which easily accommodates a four or more jewel types!
for (var i = 0; i < this.rows * this.columns; i++) {
var randomval = Math.floor(Math.random() * 3) + 1;
this.grid[i] = sprites["single_jewel" + randomval];
}
 
Search WWH ::




Custom Search