HTML and CSS Reference
In-Depth Information
• It is responsible for keeping a list of objects and handling adding sprites to and removing sprites from
that list.
• It also needs to handle looping over that list of objects.
• It needs to respond the same way as previous boards. It needs to have a step and a draw function that
calls the appropriate functions on each of the objects in the object list.
• It needs to handle checking of collisions between objects.
The next few sections walk through each of the parts of the GameBoard object, which will behave like
a simple scene graph. Scene graphs are discussed in detail in Chapter 12, “Building Games with CSS3.” The
GameBoard class will be added to the bottom of the engine.js file.
Adding and Removing Objects
The first and most important responsibility of the GameBoard class is to keep track of the objects in play. The
easiest way to keep track of a list of objects is simply to use an array, in this case an array called objects .
The GameBoard class will be described piecemeal, but the whole thing goes at the bottom of the en-
gine.js file:
var GameBoard = function() {
var board = this;
// The current list of objects
this.objects = [];
this.cnt = [];
This array is where objects that show up in the game are added to and removed from.
Next, the class needs the capability to add objects. This is simple enough. Pushing objects onto the end of
the objects' list gets most of the job done:
// Add a new object to the object list
this.add = function(obj) {
obj.board=this;
this.objects.push(obj);
this.cnt[obj.type] = (this.cnt[obj.type] || 0) + 1;
return obj;
};
For an object to interact with other objects, however, it needs access to the board it's a part of. For this reason
when GameBoard.add is called, the board sets a property called board on the object. The object can now
access the board to add additional objects, such as projectiles or explosions, or remove itself when it dies.
The board also must keep a count of the number of objects of different types that are active at a given time,
so the second-to-last line of the function initializes the count to zero if necessary using a boolean OR and then
increments that count by 1 . Objects won't be assigned types until later in this chapter, so this is a little bit of
forward-looking code.
Next is removal. This process is slightly more complicated than it first might seem because objects may
want to remove themselves or other objects in the middle of a step while the GameBoard loops over the list
of objects. A naive implementation would try to update GameBoard.objects but because the GameBoard
would be in the middle of looping over all the objects, changing them mid-loop would cause problems with the
looping code.
Search WWH ::




Custom Search