Game Development Reference
In-Depth Information
Similar to the snake class, we also create a class to encapsulate the fruit that the
snake will eat. The only difference between the snake class and the fruit class is
that the fruit class will not do anything other than show up in the map. For all prac-
tical purposes, the fruit class shares a common entity interface with the snake
class, which allows them to be reset to a default state, set their position, and check
for collision.
var fruit = {
position: new Int8Array(2),
reset: function() {
this.position[0] = -1;
this.position[1] = -1;
},
isAt: function(x, y) {
return this.position[0] == x &&
this.position[1] == y;
},
img: null
};
Finally, in the main code, we perform the following setup task:
• Create a canvas element and attach it to the DOM.
• Instantiate the renderer , snake , and fruit objects.
• Create a game loop that places a fruit on the grid when one is not present,
update the snake's position, check where the snake is, and render the
game state to the canvas.
We also use the game loop to hook into the score board widgets, to add to the user
experience. The complete source code for the game available at the topic's page on
the website of Packt Publishing also includes extra menus, but these have been left
out of the code snippets shown here for brevity.
The other thing we take advantage of in this game loop is the requestAnima-
tionFrame API. In order to assure that different CPUs and GPUs, all render the
game at the same pace, we added a simple frame rate controller inside the game
loop. The frame rate is controlled by a variable that specified how many fps the game
should attempt to run.
Search WWH ::




Custom Search