Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Created April 11, 2012 07:17
Show Gist options
  • Save hongymagic/2357521 to your computer and use it in GitHub Desktop.
Save hongymagic/2357521 to your computer and use it in GitHub Desktop.
Sample game state management
var GameState = function (ctx) {
this.ctx = ctx;
};
GameState.prototype = {
init: function (timestamp) {
this.start = timestamp;
},
draw: function (timestamp) {
// Ready for repaint
this.ctx.clearRect (0, 0, 100, 100);
// Time elapsed
var elapsed = Math.round((timestamp - this.start) / 1000);
// Draw gems
var key = elapsed % 2 ? 'blue' : 'green';
this.ctx.drawImage(assets[key], 10, 10);
// Render current time
var measured = this.ctx.measureText(elapsed);
this.ctx.font = "20px Arial";
this.ctx.fillStyle = "black";
this.ctx.fillText(elapsed, 50 - (measured.width / 2), 60);
},
pause: function () {},
resume: function () {},
handleEvent: function (event) {},
clear: function () {}
};
var GameStateManager = function () {
this.states = [];
};
GameStateManager.prototype = {
empty: function () {
return this.states.length === 0;
},
current: function () {
var last = this.states.length - 1;
return this.states[last];
},
push: function (state) {
if (!this.empty()) {
this.current().pause();
}
this.states.push(state);
state.init(+new Date());
},
pop: function () {
if (!this.empty()) {
this.states.pop().clear();
}
if (!this.empty()) {
this.current().resume();
}
},
draw: function (time) {
this.current().draw(time);
},
handleEvent: function (event) {
this.current().handleEvent(event);
}
};
function start() {
console.log('#start');
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d'),
manager = new GameStateManager(),
playstate = new GameState(context);
// Start drawing the game!
manager.push(playstate);
draw();
function draw (timestamp) {
webkitRequestAnimationFrame(draw);
manager.draw(timestamp);
}
}
//
// PxLoader – load image assets
var assets = {};
function preload (px) {
console.log('#preload', px);
var images = {
blue: 'http://images.wikia.com/ztreasureisle/images/5/51/Blue_Gem-icon.png',
green: 'http://images.wikia.com/ztreasureisle/images/7/75/Green_Gem-icon.png',
orange: 'http://images3.wikia.nocookie.net/__cb20100522145507/ztreasureisle/images/a/a8/Orange_Gem-icon.png'
};
// When all images are loaded, let the world know
px.addCompletionListener(function () {
start();
});
// Start loading images
for (var key in images) {
assets[key] = px.addImage(images[key], key);
}
px.start();
}
preload(new PxLoader());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment