In my pong game every object(ball and two paddles) is running in the independent thread.
static Ball b = new Ball(195, 145);
Thread ball = new Thread(b);
Thread paddle1 = new Thread(b.paddle1);
Thread paddle2 = new Thread(b.paddle2);
public void startGame(){
gameStarted = true;
ball.start();
paddle1.start();
paddle2.start();
}
I want to set game on pause when I press ESC and when I press ESC again - continue game. So in keyPressed event I've done like this
if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
if (gameStarted) {
gameStarted = false;
ballCurrentX = b.x; //save all states
ballCurrentY = b.y;
ballXDirection = b.xDirection;
ballYDirection = b.yDirection;
p1Score = b.p1Score;
p2Score = b.p2Score;
p1CurrentY = b.paddle1.y;
p2CurrentY = b.paddle2.y;
try {
ball.interrupt();
ball.join();
paddle1.interrupt();
paddle1.join();
paddle2.interrupt();
paddle2.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else {
gameStarted = true;
continueGame();
}
}
To continue game - I restart all threads but set parameters for the objects from previous game state
public void continueGame(){
gameStarted = true;
b = new Ball(ballCurrentX, ballCurrentY);
b.xDirection = ballXDirection;
b.yDirection = ballYDirection;
b.p1Score = p1Score;
b.p2Score = p2Score;
b.paddle1.y = p1CurrentY;
b.paddle2.y = p2CurrentY;
ball.start();
paddle1.start();
paddle2.start();
}
But program throws IllegalThreadStateException
and the game doesn't continue.
What's the problem? It doesn't stop threads?