I've been working on a game so as to fill out something that I can put on a CV and I was writing the main Game
class. This shouldn't be a god class, but it should simply be a class that ties together the "wiring" of the game, i.e, it should start listening for input events and should start the game loop and wire any inputs to the associated handlers.
/**
* The main class for the Game.
* This class should start the game loop as well as display updates.
* @author Dan
*
*/
public class Game implements Disposable {
private final DisplayWindow _display;
private final Disposable _displayUpdates;
private final Scheduler _scheduler;
/**
* Create the Game.
* @param displayService - the service to use for the Display
* @param width - the initial width of the display
* @param height - the initial height of the display
*/
public Game(Scheduler gameScheduler, DisplayWindow displayWindow) {
_display = displayWindow;
_scheduler = gameScheduler;
// Wait for the display to open correctly
try {
if(!_display.isOpen().get(500, TimeUnit.MILLISECONDS)) {
System.err.println("failed to initialize OpenGL display!");
System.exit(2);
}
} catch (Exception e) {
System.err.println("OpenGL took too long to respond!");
e.printStackTrace(System.err);
System.exit(1);
}
// schedule display to update @ 60 fps
int frameInterval = (int) ((1f / displayWindow.getTargetFramesPerSecond()) * 1000f);
_displayUpdates = _scheduler.schedule(() -> displayWindow.update(), frameInterval);
}
public void startGameLoop() throws InterruptedException {
while(true) {
// Check to see if the window is closed
// Bear in mind it's OK to wait here because
// if it takes way too long we can assume that
// openGL has stopped responding
try {
if(_display.isClosing().get(500, TimeUnit.MILLISECONDS)) {
break;
}
} catch (Exception e) {
// Terminate
System.err.println("OpenGL took too long to respond!");
e.printStackTrace(System.err);
System.exit(1);
}
Thread.sleep(1);
}
}
public void dispose() {
_display.dispose();
_displayUpdates.dispose();
}
}
Here are a few signatures you might want to know while reviewing:
Future<bool> _display.isOpen()
Future<bool> _display.isClosing()
Disposable _scheduler.schedule(...)
Obviously the while(true) { Thread.sleep(1); }
needs some changing so it actually has a legitimate timestep.
I just wanted to get this out of the way before writing an entire application based on this class doing the functionality it does.
e.printStackTrace(System.err);
\$\endgroup\$ – bhathiya-perera Aug 24 '14 at 18:17System.exit
. Only the main functions owns the process. Everyone else is a guest. \$\endgroup\$ – usr Aug 24 '14 at 22:08e.printStackTrace
:P \$\endgroup\$ – Dan Aug 24 '14 at 22:24printStackTrace
for development/debugging. It's considered "dirty" in production code. \$\endgroup\$ – toto2 Aug 24 '14 at 23:52