Classic Snake Game
by Daniel Hall
HTML
<script src="snake.js"></script>
<h3>Click inside box, and you can use arrow keys to control snake.</h3>
CSS
canvas {
display: block;
position: absolute;
border: 2px solid #000;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
JavaScript
var JS_SNAKE = (function () {
//grid size
var COLS = 30,
ROWS = 20;
TILE_SIZE = 15;
//grid content
var EMPTY = 0,
SNAKE = 1,
FRUIT = 2;
//snake direction
var LEFT = 0,
UP = 1,
RIGHT = 2,
DOWN = 3;
//event listener/handlers
var KEY_LEFT = 37,
KEY_UP = 38,
KEY_RIGHT = 39,
KEY_DOWN = 40,
SPACE_BAR = 32;
var FPS = 5;
var canvas,
ctx,
keystate,
frames,
score;
var grid = {
width: null,
height: null,
_grid: null,
init: function (d, c, r) {
this.width = c;
this.height = r;
this._grid = [];
for (var x = 0; x < c; x++) {
this._grid.push([]);
for (var y = 0; y < r; y++) {
this._grid[x].push(d);
}
}
},
set: function (val, x, y) {
this._grid[x][y] = val;
},
get: function (x, y) {
return this._grid[x][y];
}
}
var snake = {
direction: null,
head: null,
_queue: null,
init: function (d, x, y) {
this.direction = d;
this._queue = [];
//create horizontal snake of length 3
this.insert(x, y);
this.insert(x + 1, y);
this.insert(x + 2, y);
},
insert: function (x, y) {
//prepends coordinates to queue
this._queue.unshift({
x: x,
y: y
});
this.head = this._queue[0];
},
remove: function () {
return this._queue.pop();
}
}
function setFood() {
var empty = [];
for (var x = 0; x < grid.width; x++) {
for (var y = 0; y < grid.height; y++) {
if (grid.get(x, y) === EMPTY) {
empty.push({
...