JS: Snake
v1: http://jsfiddle.net/ARTsinn/3cQvw/8/ more at: http://trickkr.com/item/40/javascript-basic-html5-snake http://aspektas.com/blog/canvas-snake-game/ http://lab.aspektas.com/canvas_snake.html http://cssdeck.com/labs/classic-snake-game-with-html5-canvas http://www.htmlstack.com/canvassnake/
by jarosciak
CSS
html, body {
margin:0;
padding:0
}
canvas {
display: block;
}
canvas {width: auto; max-width: 100%; height: auto;}
JavaScript
/**
* A lightweight game wrapper
*
* @constructor
*/
function Game(canvas, options) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.score = 0;
this.key = 'right';
this.entities = [];
this.options = {
fps: 5
};
if (options) {
for (var i in options) this.options[i] = options[i];
}
this.scale();
}
/**
* Start the game loop
* and initialize the keybindings
*/
Game.prototype.start = function () {
this.keyBindings();
this.gameLoop();
};
/**
* Stop the game loop
*/
Game.prototype.stop = function() {
this.pause = true;
};
/**
* Scale the canvas element
* in accordance with the correct ratio
*/
Game.prototype.scale = function () {
this.ratio = innerWidth < innerHeight ? innerWidth : innerHeight;
this.tile = (this.ratio / 20) | 0;
this.grid = this.ratio / this.tile;
this.canvas.width = this.canvas.height = this.ratio;
};
/**
* Adds an entity to the game
*
* @param {Function} entity
*/
Game.prototype.addEntity = function (entity) {
this.entities.push(entity);
};
/**
* Determines if an entity collides with another
*
* @param {Object} a
* @param {Object} b
*/
Game.prototype.collide = function(a, b){
return a.x === b.x && a.y === b.y;
};
/**
* Tracks the pressed keys
*/
Game.prototype.keyBindings = function () {
var that = this;
// define some keys
var keys = {
a: 65,
left: 37,
d: 68,
right: 39,
w: 87,
up: 38,
s: 83,
down: 40
};
/**
* Attach keyboard arrows to snake direction
*/
document.onkeydown = function (e) {
switch ((e.which || e.keyCode) | 0) {
case keys.a:
case keys.left:
if (that.key !== 'right') that.key = 'left';
break;
case keys.d:
case keys.right:
if (that.key !== 'left') that.key = 'right';
...