Passing events back to Game

Im writing my first java game, and I use a main Game class that use different Screens (ie. mapScreen, combatScreen, menuScreen) to handle different sections on the game. And right now I need my mapScreen to tell my game that it’s done and we should move to the combatScreen.

And so I just wanted to ask about best practices here, should mapScreen implement ActionListener and have the Game subscribe to these notifications, or is there a more common way to do it?
Also, can anyone please link to a good explenation of how I should implement the ActionListener?

thanks in advance.

-Torquai

Well, for Screens, it isn’t a good idea to use Listeners at all actually. The best way to handles Screens is by using simple states. If you have a lot of screens, for instance, and you want to move from one screen to another, you can have an ID that tells your program which Screen to display next. Each Screen can be part of an array, and you can choose which Screen to display based on the ID.

It is a lot more simple than Listeners. I’ve only found Listeners extremely useful when listening for items on other threads, such as input devices, music thread lines, or Swing buttons.

If you don’t have that many screens, you could instantiate each one as public fields in Game. (if you want you can write methods like getMapScreen() and getMenuScreen()). If each screen holds a reference to Game, then you can have a simple method in Game like.


public void setScreen(GameScreen screen) {
   currentScreen = screen;
}

Then within your mapScreen you could just call game.setScreen(game.combatScreen);. You can make it a bit more sophisticated too. For instance if each screen has code that it needs run only when it’s initialized or when it’s closed, you can modify your setScreen code to somehting like:


public void setScreen(GameScreen screen) {
   currentScreen.close();
   currentScreen = screen;
   currentScreen.initialize();
}

I normally will create a ScreenManager for this kinda stuff. Your game would have the ScreenManager, and all your screens would be in an list or map of some kind within ScreenManager. All your screens would have a reference to ScreenManager and when you need to switch it may look something like this:

ScreenManager.switchScreen("ScreenID");

the switch method in the manager might look like this:

public void switchScreen(String id)
{
currentScreen.dispose();
currentScreen = //find screen with id
currentScreen.enter();
}