Monday, December 2, 2019

screen management - Restarting a game


I'm having trouble restarting a 2D game when the user presses the "New Game" button.



Structure of my game:


The game has several 'screens': Opening screen, instructions screen, main game screen, and a game-over screen.


Each screen is an instance of a class: OpeningScreen class, GameScreen class, etc.


There is a class named Main. This class has three roles.



  • It's the JFrame (the window) of the program.

  • It has the main method - first class to run.

  • It has a method that change's screens.


When the program starts, this class runs. When it first runs:




  1. Creates a new instance of itself (it's a JFrame-type class).

  2. Creates an instance of every 'screen-class'. The constructor of each 'screen-class' takes the instance of Main as an argument: (aka: GameOverScreen gameOverScreen = new GameOver(this)).

  3. Creates a new JPanel named mainPanel, and adds it to the JFrame. Any screen to be displayed will be contained in this JPanel (The screens are also JPanel-type classes).


How the changeScreen() method works:


The signature of changeScreen() is this: changeScreen(JPanel from, JPanel to).


Whenever a screen needs to be changed, the current screen that is displayed calls this method, like so: main.changeScreen(this, main.InstructionsScreen). It removes the previous screen from mainPanel and adds the new screen to mainPanel. As said, these screens are created when the program launches.


This is the method that changes screens:


public void changeScreen(JPanel from, JPanel to){


mainPanel.remove(from);
mainPanel.add(to);

mainPanel.revalidate();
mainPanel.repaint();

}

My problem:



After a game is finished, the Game class calls the changeScreen method: main.changeScreen(this, main.GameOverScreen) .


This replaces the game screen with a game over screen. Pressing the "New Game" button in the game-over screen, calls main.changeScreen(this, main.GameScreen) .


The problem: Pressing the "New Game" button in the game-over screen, indeed displays once again the instance of the Game class. But this is the old instance, so the game is not restarted. It's already finished.


I tried to do the following changes in changeScreen():


public void changeScreen(JPanel from, JPanel to){

mainPanel.remove(from);

if(to.equals(gameScreen)){
gameScreen = null;

gameScreen = new GameScreen(this);
}
mainPanel.add(gameScreen);

mainPanel.revalidate();
mainPanel.repaint();

}

This should reset the gameScreen object. But this creates a delay of about 10 seconds when pressing the "New Game" button.



What would be a good way of restarting the game?


Thank you




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...