Search code examples
csdl

What's a good way to implement menus/scenes with SDL2 in C?


I'm making a game using SDL2. I was testing menus but a bug had me think I had to change my approach. I used to have a separate while loop for every menu, but now I'm trying to have a single loop for the whole game which handles different menus depending on the value of a variable (nested loops became a mess to handle). I thought about it for a while, but the variety of the needs of the menus gave me a lot of trouble. If anyone can suggest me some good approach, here is what it requires:

  • Differentiated event handling (a menu should handle player movement keys, another some handle other things...);

  • A way to free every variable declared with malloc() once a menu stops running;

  • An initialization that runs only once before each menu loop starts.

I hope someone can give me a good approach with pseudocode or just normal explaination, thanks in advance to those who'll help!


Solution

  • You may want to consider doing the following:

    Every menu defines its own object of struct menu, which contains at least the following three function pointers:

    1. A pointer to a function which is called whenever the menu opens, so memory for the menu's data can be allocated, and the data can be initialized.
    2. A pointer to a function which is called whenever the menu closes, so that all memory allocated by the menu can be freed.
    3. A pointer to the menu's input function which is called whenever the program receives input. This function will return true if the menu handles the input, or false if it does not handle the input, because it is unrelated to the menu (for example if the input is a key for player movement).

    Your program should have a pointer to a struct menu which always specifies the currently active menu, or NULL if no menu is active. Whenever your program's main loop receives input, it calls the function pointer for the input function of the currently active menu. If the menu's input function returns true, then the game's main loop will ignore the input, but if the menu's input function returns false (for example if the input is a key for player movement), then the game's main loop will handle the input itself.