I'm struggling with implementing a dialog box in my program. The main program does not use stage. However when the users lives are at 0 I would like to popup a dialog that either restarts the game or exits the game.
I have created a separate class for the Dialog using the following code.
public class GameOver {
//dialog game over
private Dialog dlgGameOver;
private Skin skin;
private Stage stage;
private TextButton btnMain;
private TextButton btnTryAgain;
private GameScreen gameScreen;
public GameOver(final GameScreen gameScreen){
//create the game over dialog
this.gameScreen = gameScreen;
skin = new Skin(Gdx.files.internal("uiskin.json"));
dlgGameOver = new Dialog(" ",skin);
stage = new Stage();
btnMain = new TextButton("Main", skin);
btnTryAgain = new TextButton("Try Again", skin);
dlgGameOver.text("Game over!");
dlgGameOver.button(btnTryAgain);
dlgGameOver.button(btnMain);
dlgGameOver.show(stage);
btnMain.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
System.out.println("Button Pressed");
}
});
btnTryAgain.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
gameScreen.setIntLives(3);
gameScreen.setIntScore(0);
System.out.println("Button Pressed");
}
});
Gdx.input.setInputProcessor(stage);
}
public Stage getStage() {
return stage;
}
}
The main game screen does not use stage. In the update method I create the GameOver class if livers are at 0
if(intLives == 0) {
if(!boolGameOver) {
dlgGameOver = new GameOver(this);
boolGameOver = true;
} else if(intLives !=0) {
boolGameOver = false;
}
}
In the render method I draw the stage
if(intLives == 0) {
dlgGameOver.getStage().draw();
} else {
//<rest of normal update code follows here>
}
This works perfectly the first time the dialog is created. When hitting restart the game will restart (or actually reset the score and lives). However, the second time you run out of lives the dialog is displayed as expected but the buttons will not work. Somehow it seems the clicklistener is not initialized the second time.
Am I doing something fundamentally wrong here? If my approach is totally wrong I'm happy to hear it as well.
See Question&Answers more detail:os