I'm making a javascript/canvas game and I saw this example on CSS Tricks. Here's the link http://css-tricks.com/9876-learn-canvas-snake-game/#comment-100804
Anyways, I'm wondering because I'm refactoring my game code, and creating my own objects and so far this looks like a good pattern to be using.
To me, this looks like the Revealing Module Pattern I read about on http://addyosmani.com/resources/essentialjsdesignpatterns/book/
So am I right?
/* NOTE: this is just a snippet from the example, go to the link to see the
finished example */
var JS_SNAKE = {};
JS_SNAKE.game = (function () {
var ctx;
JS_SNAKE.width = 200;
JS_SNAKE.height = 200;
JS_SNAKE.blockSize = 10;
var frameLength = 500; //new frame every 0.5 seconds
var snake;
function init() {
$('body').append('<canvas id="jsSnake">');
var $canvas = $('#jsSnake');
$canvas.attr('width', JS_SNAKE.width);
$canvas.attr('height', JS_SNAKE.height);
var canvas = $canvas[0];
ctx = canvas.getContext('2d');
snake = JS_SNAKE.snake();
bindEvents();
gameLoop();
}
function gameLoop() {
ctx.clearRect(0, 0, JS_SNAKE.width, JS_SNAKE.height);
snake.advance();
snake.draw(ctx);
setTimeout(gameLoop, frameLength); //do it all again
}
function bindEvents() {
var keysToDirections = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
$(document).keydown(function (event) {
var key = event.which;
var direction = keysToDirections[key];
if (direction) {
snake.setDirection(direction);
event.preventDefault();
}
});
}
return {
init: init
};
})();
Also, is there a better pattern that I should be using when creating objects in a javascript/canvas game?
If you would like to check out my game, go to my website. http://magnut.comze.com
The game I created is called Fruit Blitz and the next update which I'm working on right now is going to a big one, with enemies, power ups and such.