Java Game State Management

11.9k views Asked by At

Does anyone have a good State Manager tutorial in Java? I have been looking into this for the past couple of days and anything that I come across doesn't seem to work in the correct fashion for what I need it to do. I need it to be able to take user input and then switch from a title state to a game state. Thanks in advance.

2

There are 2 answers

0
Jon G. On BEST ANSWER

I'll point you in the right direction by giving you bit of jargon to look for: "Finite State Machine". For game menus, a FSM should suffice. Now that you know the buzz word, you shuld be able to figure out a ton of examples just by googling. Although the basic idea is very simple, there are tons of different implementations. Just remember that this sort of system for game state transitions doesn't need to be that extreme.

I've personally seen all sorts of stuff from way over-engineered multi-dimensional state transitions to a gigantic thousand-line switch statement.

For a basic game without streaming or crazy gaming interrupts, you should probably look for an object oriented approach no more complex than this:

public enum GameState {
    TITLE_STATE = 0,
    MAINGAME_STATE,
    PAUSE_STATE,
}

void GameStateUpdate() {
     // handle update
    switch(m_curState) {
       case TITLE_STATE:
          UpdateTitleScreen();
          if(UserPressesEnter()) {
              m_curState = MAINGAME_STATE;
          }
          break;
       case MAINGAME_STATE:
          UpdateMainGame();
          if(UserPressesPause()) {
              m_curState = PAUSE_STATE;
          }
          break;
       case PAUSE_STATE:
          UpdatePause();
          if(UserDoneWithPause()) {
              m_curState = MAINGAME_STATE;
          }
          break;
    }
}

Work from something like this and see if you can add transitional states for things like a pause menu popping in and out, or an introduction movie prior to the "MAINGAME_STATE" starting.

1
Jimmt On

Enums are the way to go with states. Check this out: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html