Game Development Reference
In-Depth Information
for (var i = 0; i < 3; i += 1) {
if ((Math.floor(curra / divider) + Math.floor(currb / divider)
+ Math.floor(currc / divider)) % 3 !== 0)
return false;
curra = curra % divider;
currb = currb % divider;
currc = currc % divider;
divider = Math.floor(divider / 3);
}
return true;
First you retrieve the value that represents which jewel you're dealing with, using the
variation
member variable of each jewel. Then you define a
divider
number that is equal to 9 (you first divide
by 9). You next define a
for
instruction that runs three times. In the body of the
for
instruction, you
place a condition that the sum of the three variation indices divided by
divider
should be divisible
by 3. If this isn't the case, you return
false
because the combination condition doesn't hold for one
of the properties. You assign the rest of the division by the divider to each of the variables containing
the current variation index. You then divide the divider by 3. If you exit the
for
instruction, it means
in all cases that the condition in the
if
instruction was
true
, meaning you found a valid combination.
Because you found a valid combination, you return the value
true
.
Removing Jewels from the Grid
In the
update
method, you can now use the
isValidCombination
method to determine whether a
valid combination exists. For this, you use a
while
instruction that evaluates all sequences of three
jewels in the middle column:
var middleCol = Math.floor(this._columns / 2);
var i = 0;
while (i < this._rows - 2) {
if (this.isValidCombination(this.at(middleCol, i),
this.at(middleCol, i + 1), this.at(middleCol, i + 2))) {
// do something
}
else
i++;
}
When you find a valid combination, you need to remove these jewels from the grid and insert new
jewels. To do this, you define a method called
removeJewel
, which removes a jewel from the grid
and inserts a new one. To create a nice “falling down” motion, you place these jewels in different
positions above the grid. You pass the desired
y
-location as a parameter to the
removeJewel
method
so it knows where the new jewel should be located. The complete method then becomes
JewelGrid.prototype.removeJewel = function (x, y, newYPosition) {
for (var row = y; row > 0; row -= 1)
this._gameObjects[row * this._columns + x] =
this._gameObjects[(row - 1) * this._columns + x];
Search WWH ::
Custom Search