Pausing and Resuming
Even with the most exciting game, there comes a time when the user wants to pause it (and resume later).
One largely discredited coding approach is to use Thread.suspend() and resume(). These methods are deprecated for a similar reason to Thread.stop();suspend() can cause an applet/application to suspend at any point in its execution. This can easily lead to deadlock if the thread is holding a resource since it will not be released until the thread resumes.
Instead, the Java documentation for the Thread class recommends using wait() and notify() to implement pause and resume functionality. The idea is to suspend the animation thread, but the event dispatcher thread will still respond to GUI activity. To implement this approach, I introduce an isPaused Boolean, which is set to true via pauseGame():
// global variable
private volatile boolean isPaused = false;
public void pauseGame()
{ isPaused = true; }
public void run()
// Repeatedly (possibly pause) update, render, sleep
// This is not a good approach, and is shown for illustration only.
{ ...
running = true;
while(running) {
try {
if (isPaused) {
synchronized(this) {
while (isPaused && running)
wait();
}
}
} // of try block
catch (InterruptedException e){}
gameUpdate(); // game state is updated
gameRender(); // render to a buffer
paintScreen(); // paint with the buffer
// sleep a bit
}
System.exit(0);
} // end of run()The isPaused flag is detected in run() and triggers a wait() call to suspend the animation ...