Game Development Reference
In-Depth Information
The code
The way this game was laid out is actually quite simple. The HTML has only three
widgets: the title of the game, a score board for the player's current score, and a score
board for the overall high score across multiple games. This last score board is not
used in this version of the game, and we'll get more into it in the next game (see
Chapter 5 , Improving the Snake Game ).
<h1>HTML5 Snake</h1>
<section id="scores">
<h3>Score: <span>0</span></h3>
<h3>High Score: <span>0</span></h3>
</section>
<section id="gameMenu" class="hide">
<h3>Ready!</h3>
<button>Play</button>
</section>
In order to separate the various responsibilities from all the different components in
the game, we abstracted out all the rendering for the entire game into a single Ren-
derer class. This class is in charge of drawing data to a canvas reference that is
given to it. The data that it draws, be it a snake or any other objects, is passed in
to it as a typed array, representing the coordinates where the entity is to be drawn,
along with the image resource that is drawn at the location specified by the typed ar-
ray. The Renderer class also includes a few helper functions to help us easily clear
the canvas, and convert an x and y point into an index used to traverse the flat array
representing a 2D one.
var Renderer = function(canvas) {
var canvas = canvas;
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
Search WWH ::




Custom Search