Game Development Reference
In-Depth Information
ute (dead or alive), as well as reset the image used to draw the snake, or any other
attribute of it.
var Snake = function(x, y, width, height,
maxSize) {
var isAlive = true;
var size = 0;
var body = new Int8Array(maxSize * 2);
for (var i = 0, len = body.length; i < len;
i++)
body[i] = -1;
body[0] = x, body[1] = y;
var worldWidth = width;
var worldHeight = height;
var skin;
var dir = { 38: false, 40: false, 37: false,
39: false };
var keys = { UP: 38, DOWN: 40, LEFT: 37,
RIGHT: 39 };
// To move the snake, we first move each
body part to where the
// part before it used to be, starting at
the tail and moving
// towards the head. Lastly, we update the
head's position
var move = function() {
// Traverse the snake backwards and shift
each piece one spot
for (var i = size * 2 + 1; i > 1; i -= 2)
{
body[i] = body[i - 2];
body[i - 1] = body[i - 3];
}
if (dir[keys.UP]) {
body[1]--;
} else if (dir[keys.DOWN]) {
body[1]++;
} else if (dir[keys.LEFT]) {
Search WWH ::




Custom Search