Game Development Reference
In-Depth Information
You also add a method
addPair
to the class, which finds the first occurrence of the value 7 in the
array and replaces it with the index that was passed along as a parameter:
PairList.prototype.addPair = function (index) {
var i = 0;
while (i < this._pairs.length && this._pairs[i] !== 7)
i++;
if (i < this._pairs.length)
this._pairs[i] = index;
};
This example uses a
while
instruction to increment the
i
variable until you find an empty spot.
Now you add a useful property to check whether the player has completed the level. The level is
completed if the list of pairs no longer contains any value of 7 (meaning all empty spots have been
replaced by a pair):
Object.defineProperty(PairList.prototype, "completed",
{
get: function () {
for (var i = 0, l = this._pairs.length; i < l; i++)
if (this._pairs[i] === 7)
return false;
return true;
}
});
Finally, you need to draw the pairs on the screen in the
draw
method. Here you use a
for
instruction
to traverse all the indices in the pair list. For each index, you draw the correct sprite at the
appropriate position. Note that you use the same sprite and simply draw it multiple times with
different sheet indices:
PairList.prototype.draw = function () {
SpriteGameObject.prototype.draw.call(this);
if (!this.visible)
return;
for (var i = 0, l = this._pairs.length; i < l; i++) {
this._pairSprite.position = new Vector2(110 + i * this.height, 8);
this._pairSprite.sheetIndex = this._pairs[i];
this._pairSprite.draw();
}
};
The call to the base
draw
method ensures that the background frame is drawn first.
Now that you have the
PairList
class, you can create an instance of it in the
Level
class, add it to
the game world, a.n it near the top left of the screen:
var pairList = new PairList(levelData.nrPairs, ID.layer_overlays, ID.pairList);
pairList.position = new Vector2(20, 15);
this.add(pairList);
Search WWH ::
Custom Search