patternjavascriptMinor
Simple Game Engine in JavaScript
Viewed 0 times
javascriptenginegamesimple
Problem
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.
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);
})();Solution
There's really not much to say about this code, so I'll quote a comment posted on this question:
[...] a basic game engine is a loop and a redraw/update system. So yes you are good. You should explore other game engines in javascript and see what they do. – Steven
Just one thing that's itching: you're declaring
[...] a basic game engine is a loop and a redraw/update system. So yes you are good. You should explore other game engines in javascript and see what they do. – Steven
Just one thing that's itching: you're declaring
var frameLength = 500; - I think this is going to bite you later, when you want to adjust frame rate (FPS).Context
StackExchange Code Review Q#31901, answer score: 2
Revisions (0)
No revisions yet.