Created
March 21, 2012 14:52
-
-
Save rlemon/2147851 to your computer and use it in GitHub Desktop.
Snake
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* First draft - not working - BAD memory issues */ | |
window.requestAnimFrame = (function() { | |
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || | |
function( /* function */ callback, /* DOMElement */ element) { | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
(function() { | |
var cvs = document.getElementById('cvs'), | |
ctx = cvs.getContext('2d'), | |
frameHeight = 480, | |
frameWidth = 640, | |
fps = 0, | |
fps_now, fps_last = (new Date), | |
fps_el = document.getElementById('fps'); | |
cvs.setAttribute('height', frameHeight); | |
cvs.setAttribute('width', frameWidth); | |
var snake = { | |
'len': 3, | |
'position': { | |
'x': 50, | |
'y': 50 | |
}, | |
'dir': 39, | |
'body': [] | |
}, | |
cellSize = 10; | |
window.onkeydown = function(e) { | |
switch (e.which) { | |
case (37): | |
snake.dir = 37; | |
snake.position.x -= cellSize; | |
break; | |
case (38): | |
snake.dir = 38; | |
snake.position.y -= cellSize; | |
break; | |
case (39): | |
snake.dir = 39; | |
snake.position.x += cellSize; | |
break; | |
case (40): | |
snake.dir = 40; | |
snake.position.y += cellSize; | |
break; | |
} | |
snake.body.push([snake.position.x, snake.position.y]); | |
if (snake.body.length > snake.len) { | |
snake.body.shift(); | |
} | |
}; | |
snake.body.push([snake.position.x, snake.position.y]); | |
var render = function() { /* FPS setup */ | |
fps_now = new Date; | |
fps = 1000 / (fps_now - fps_last); | |
fps_last = fps_now; /* /FPS setup */ | |
/* Frame Animation */ | |
ctx.save(); | |
ctx.clearRect(0, 0, frameHeight, frameWidth); | |
for (var i = 0, l = snake.body.length; i < l; i++) { | |
ctx.fillStyle = 'rgb(255,0,0)'; | |
ctx.fillRect(snake.body[i][0], snake.body[i][1], cellSize, cellSize); | |
} | |
ctx.restore(); /* /Frame Animation */ | |
/* FPS printout */ | |
fps_el.innerHTML = Math.round(fps) + " fps"; /* /FPS printout */ | |
requestAnimFrame(function() { | |
render() | |
}); | |
}; | |
render.call(); | |
var move = function() { | |
window.onkeydown.apply(this,[{ | |
'which': snake.dir | |
}]); | |
setInterval( function() { | |
move(); | |
}, 1000); | |
}; | |
move.call(); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment