Game Development Reference
In-Depth Information
var getIndex = function(x, y) {
return width * y + x;
};
var getPosition = function(index) {
return {
x: index % width,
y: parseInt(index / width)
};
};
this.clear = function() {
ctx.clearRect(0, 0, canvas.width,
canvas.height);
};
this.draw = function(points, img) {
for (var i = 0, len = points.length; i <
len; i += 2) {
ctx.drawImage(img, points[i] *
img.width, points[i + 1] * img.height,
img.width, img.height);
}
};
};
Next, we create a Snake class that encapsulates all of the data and behavior asso-
ciated with the snake. The data that this class stores is the current position of the
snake's head, the current length of the snake's body, the image that is to be drawn
representing the snake, and whether the snake is alive or not. The behavior that it
handles includes the moving of the snake and the handling of user input (which is
included in this class for simplicity and brevity). There are a few helper functions that
allow us to delegate other behaviors to the client. For example, through the API ex-
posed, the client can check at each frame whether the snake has gone outside the
world grid, if it has eaten a fruit, or if the snake ran into its own body. The client can
also use the API provided, to take action on the snake, such as setting its life attrib-
Search WWH ::




Custom Search