I am trying to add pause functionality to a game. Unfortunately the method I’m currently using causes the program to take no more inputs so I am unable to resume the game.
Here is what I’m currently doing:
a pause button calls:
public void pause(){
if(data.paused == true){
data.paused = false;
}
else{
data.paused=true;
while(true){
if(data.paused == true){
try{
Thread.currentThread().sleep(100);
}
catch(InterruptedException ie){
System.out.println(ie);
}
}
else
break;
}
data.paused=false;
}
return;
I then have a TimerTask that I have to deal with:
class aTask extends java.util.TimerTask {
protected Data data;
public aTask( Data d ) { data = d; }
public void run() {
try{
if(data.paused){
try{
Thread.currentThread().sleep(100);
}
catch(InterruptedException ie){
System.out.println(ie);
}
}
else
data.tick();
}
catch( ATCGameOverException e ){
data.gameOver( e.getMessage() );
}
}
};
where tick causes an action in the game every second.
I would think this would allow the game to pause when the button is pressed and then unpause when the button is pressed again, but I would be wrong. What am I doing wrong?
Simply try this :
It looks like a threading problem. If you use Swing and your pause method is tied to an action listener, than the behaviour is normal: the pause function never returns, Swing main thread never has control again, and cannot manage further actions, including unpausing… Look at this link
My solution simply inverse the state of the pause variable, and gives control back to Swing. It’s the game main loop that will tick the data or not according to the state of this variable. No thread is blocked, main loop continues to loop.