What is a good way of changing states in a game?

For instance, how do I go from the main menu screen to the instructions screen to the play screen??? I currently use bool variables but is there a better way? Thanks
I use function pointers for this.

For each menu and the game I write a:
INIT() - allocate and initialize all data needed for the menu or game
logic() - carry out logic at the frame rate.
draw() - draw objects at the render rate
DLT() - free memory, etc

The logic and draw function pointers are assigned in the INIT() so that the logic and draw functions for that menu are being called in the main().

Example:
App opens to a start menu.
start menu -> game
game -> mid menu
mid menu -> game
game -> end menu

main() would look crudely like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int gameLevel = 1;

int main()
{
    beginMenuINIT();

    while( running )
    {
        running = pLogicFunc();// points to current logic function
        pDrawFunc();// points to current draw function
    }
    cleanup();
    return 0;
}


1
2
3
4
5
6
void beginMenuINIT()
{
    // allocate and init data for the menu
    pLogicFunc = beginMenuLogic;// so these functions will be the ones
    pDrawFunc = beginMenuDraw;// being called in main()
}


1
2
3
4
5
6
7
8
9
10
bool beginMenuLogic()
{
    // process user input
    // handle animation logic, etc...

    // handle exit condition here - go to game
    beginMenuDLT();// free memory and assign our function pointers to NULL
    gameINIT( gameLevel );
    return true;
}


1
2
3
4
5
6
7
void gameINIT()()
{
     // allocate and init data for the game
    pLogicFunc = gameLogic;// so these functions will be the ones
    pDrawFunc = gameDraw;// being called in main()
    return;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
bool gameLogic()
{
    // process user input
    // handle animation logic, etc...

    // handle exit condition (end of play level) - go to midmenu or end menu
    gameDLT();// free memory and assign our function pointers to NULL
    if( ++gameLevel <= 3 )
       midMenuINIT();// another level is left
    else
        endMenuINIT();// game over
    return true;
}


See the pattern?
It is designed so that the menu -> game -> menu ->...
process chains along automatically via the assignments made to the function pointers in the INIT() functions.
Last edited on
Hey sorry for the late reply but yeah I think I see what is going on. It's like you have two central functions to your programs and their value decides the direction the program will go. Am I right? This is definitely less clunky than how I currently structure programs...thanks.
Topic archived. No new replies allowed.