I’m planning on creating a Mortal Kombat-inspired game in JavaScript. I’ve written a basic game engine that manages my game states and creates a game loop.
I just wondered if it could be improved at all? As I’m a web developer by trade and this is my first foray into programming games.
/**
* Game engine.
*/
function GameEngine() {
this.states = new Array();
this.currentState;
this.running = false;
};
GameEngine.prototype.init = function() {
this.running = true;
};
GameEngine.prototype.changeState = function(state) {
this.currentState = state;
};
GameEngine.prototype.isRunning = function() {
return this.running;
};
GameEngine.prototype.handleEvents = function() {
this.currentState.handleEvents(this);
};
GameEngine.prototype.update = function() {
this.currentState.update(this);
};
GameEngine.prototype.draw = function() {
this.currentState.draw(this);
};
/**
* Base game state state.
*/
function GameState() {};
/**
* Intro state.
*/
function IntroState() {};
IntroState.prototype = Object.create(GameState.prototype);
IntroState.prototype.handleEvents = function(game) {
console.log('IntroState::handleEvents');
};
IntroState.prototype.update = function(game) {
console.log('IntroState::update');
};
IntroState.prototype.draw = function(game) {
console.log('IntroState::draw');
};
/**
* Initialises the game.
*/
(function() {
var game = new GameEngine();
var gameLoop;
var frameLength = 500;
game.init();
game.changeState(new IntroState());
gameLoop = setInterval(function() {
game.handleEvents();
game.update();
game.draw();
}, frameLength);
})();
Constructor.prototype
all the time, you should perhaps do something likeConstructor.prototype = { constructor: Constructor, someFn: function () {}, someOtherFn: function () {} }
. Also have a look at ibm.com/developerworks/library/wa-objectorientedjs – plalx Oct 12 '13 at 6:39