Game Loops

01 Aug 2012. comments

All computer games when you boil them down to their simplest form consist of a notion called the ‘game loop’. A game is really just a looping construct thats continuously receiving inputs, thinking, drawing the outputs, and repeating. 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. 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. 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:

public class Game {

  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 now = System.currentTimeMillis();
      long elapsed = now - this.lastLoopTimestamp;
      this.lastLoopTimestamp = now;

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

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

  }

}

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. The only thing the Engine cares about is knowing how to run, and how much time elapses each time through (to use in determining how far to move things in the think()).

comments

Tagged: java game development

2017 Ben Lakey

The words here do not reflect those of my employer.