HTML5 Snake Game
found here: http://jdstraughan.com/2013/03/05/html5-snake-with-source-code-walkthrough/
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5 snake - Canvas Snake Game</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>html5-snake</h1>
<p><a href="http://en.wikipedia.org/wiki/HTML5">HTML5</a> variation of the classic <a href="http://en.wikipedia.org/wiki/Snake_(video_game)">snake game</a>.</p>
<div>
<canvas id="the-game" width="640" height="480">
</div>
<p>Control snake with arrow keys, WASD, or HJKL (vim keys).</p>
<p>New food may appear under snake, uncoil to reveal.</p>
<p>Collect the food to grow and increase speed.</p>
<p>© 2013 - <a href="http://JDStraughan.com">JDStraughan.com</a> - <a href="https://github.com/JDStraughan/html5-snake">Source on GitHub</a></p>
</body>
</html>
CSS
article, aside, details, figcaption, figure, footer, header,
hgroup, menu, nav, section {
display: block;
}
body {
background-color: #CCC;
}
h1 {
text-align: center;
}
p {
text-align: center;
}
canvas {
display: block;
margin: 0 auto;
background-color: #666;
}
JavaScript
var canvas = document.getElementById("the-game");
var context = canvas.getContext("2d");
game = {
score: 0,
fps: 8,
over: false,
message: null,
start: function() {
game.over = false;
game.message = null;
game.score = 0;
game.fps = 8;
snake.init();
food.set();
},
stop: function() {
game.over = true;
game.message = 'GAME OVER - PRESS SPACEBAR';
},
drawBox: function(x, y, size, color) {
context.fillStyle = color;
context.beginPath();
context.moveTo(x - (size / 2), y - (size / 2));
context.lineTo(x + (size / 2), y - (size / 2));
context.lineTo(x + (size / 2), y + (size / 2));
context.lineTo(x - (size / 2), y + (size / 2));
context.closePath();
context.fill();
},
drawScore: function() {
context.fillStyle = '#999';
context.font = (canvas.height) + 'px Impact, sans-serif';
context.textAlign = 'center';
context.fillText(game.score, canvas.width/2, canvas.height * .9);
},
drawMessage: function() {
if (game.message !== null) {
context.fillStyle = '#00F';
context.strokeStyle = '#FFF';
context.font = (canvas.height / 10) + 'px Impact';
context.textAlign = 'center';
context.fillText(game.message, canvas.width/2, canvas.height/2);
context.strokeText(game.message, canvas.width/2, canvas.height/2);
}
},
resetCanvas: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
};
snake = {
size: canvas.width / 40,
x: null,
y: null,
color: '#0F0',
direction: 'left',
sections: [],
init: function() {
snake.sections = [];
snake.direction = 'left';
snake.x = canvas.width / 2 + snake.size / 2;
snake.y = canvas.height /2 + snake.size / 2;
for (i = snake.x + (5 * snake.size); i >= snake.x; i-=snake.size) {
snake.sections.push(i + ',' + snake.y);
}
},
move: function() {
switch(snake.direction) {
case 'up':
...