Game Development: The Engine (Game Loop)

All computer games, when you boil them down to their simplest form, consist of a notion called the ‘game loop’. When you consider what a game really is you realize that it’s just a looping construct thats continuously receiving inputs and drawing outputs. The simplest loop looks like this:

  1. Calculate time elapsed since last loop.
  2. Accept inputs from the user(s).
  3. Decide what to do based upon those inputs, including updating entity positions.
  4. Draw everything to the screen.
  5. Repeat the loop.

I’ve been working on a game in my spare time (ok, so I’m ALWAYS working on a game in my spare time, shutup, let’s get back on topic). I spent a fair amount of time simplifying my game loop so that any developer could come along and immediately understand what it’s doing. As it turns out, this process of simplification is a great way to decouple things into a better design. Here’s what I’ve ended up with so far:

private boolean running;
private long lastLoopTimestamp;
private final Renderer renderer;
private final RateLimiter rateLimiter;

public Engine(Renderer renderer, RateLimiter rateLimiter) {
	this.renderer = renderer;
	this.rateLimiter = rateLimiter;
}

public void run() {
	
	this.running = true;

	while(running) {
		
		long elapsedTimeMillis = 
                  this.calculateLoopElapsedTime();

		this.processInput();
		this.think(elapsedTimeMillis);
		this.drawWorld();

		this.rateLimiter.blockAsNeeded(
                  System.currentTimeMillis());
	}
	
}

private long calculateLoopElapsedTime() {
	
	long now = System.currentTimeMillis();
	long elapsed = now - this.lastLoopTimestamp;
	this.lastLoopTimestamp = now;
	
	return elapsed;

}

The basic idea is that the Engine class here knows nothing about processing input, thinking about the logic, or rendering the world to the screen. It does however orchestrate all of those things (omitted the contents of the orchestration methods for brevity). The only thing the Engine cares about is knowing how to run, and how fast.

I think this is a pretty clean design. I’ll post more later about how I decoupled what’s being rendered to (ultimately a Canvas).