Skip to main content
GameDev.net gamedev.net
🔒 Locked

Writing a game, and the game loop..

Started by win32mfc Dec 2, 2004 at 12:26 PM 5 replies 1.8k views
Original Post
win32mfc
win32mfc
Hiya, I've recently decided to get back into working with DirectX, using the latest Managed DirectX 9. I have a question that's more general in nature, though. Most game books I've seen show the "main" game loop something like this: main() { init() while(!done) { handle_user_input() update_world() render_world() } free_resources() } A while back, I wrote a 2D game of pong that started by going into full-screen and giving you a simple menu, with a rotating arrow graphic next to the selected item (using arrow keys to move up/down and enter to select.) The way I did it was to use lots of switch statements like this: switch(m_state) { case TITLE_SCREEN: handle_title_screen(); break; case SHOW_CREDITS: handle_show_credits(); break; case START_GAME: handle_start_game(); break; case PLAY_GAME: handle_play_game(); break; case END_LEVEL: handle_end_level(); break; case NEW_LEVEL: handle_new_level(); break; case END_GAME: handle_end_game(); break; } My question is how do people normally go about putting in all the extra stuff a game usually has, like title screen, demo mode, etc? Am I going about it in a "sane" manner? Thanks for any input! // CHRIS EDIT: fixed typo
// CHRIS [win32mfc]
Stephen R
Stephen R
Well the way I handle this is by using a state stack. I have an abstract class which all game states, such as the different menus and the game itself, inherrit from. I then have a stack of these states and I simply run whichever one is on top each frame.
corliss
corliss
The "How to Program RPG" book does it the same way. Basically it defines a State object as follows:

struct StateObject {
void (*stateHandler)(void);
};

Then it creates a stack of StateObjects. Every loop through the game, it simply calls the stateHandler method. This method can then print title screens, display menus, run the main game, etc.

Drawbacks: stateHandler is a pointer to a funtion so only functions and not class methods can be used; unless the class method is static. =)
red_sodium
red_sodium
Looks like you're doing it fine.
"Learn as though you would never be able to master it,
hold it as though you would be in fear of losing it" - Confucius
JimPrice
JimPrice
Oops, that was me, and this was the link.

Jim.
win32mfc
win32mfc
Thanks all, that's just the kind of info I was looking for!

// CHRIS
// CHRIS [win32mfc]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.