Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C Game Logic

Name: Anonymous 2012-03-22 6:28

How should I setup my game logic in C?  I'm not entirely sure how I can set it up without using classes.

For example, in C++ it works like:
MainMenuWorld and LevelWorld both extend WorldBase class.

WorldBase *TargetWorld;

TargetWorld = new MainMenuWorld();
//or
TargetWorld = new LevelWorld();

Then, for the logic:

TargetWorld -> input(event);
...
TargetWorld -> draw();
...
TargetWorld -> update();

Should I use a variable to determine what to render? i.e. 1 = MainMenuWorld, 2 = LevelWorld, etc. That feels like it might be a bit of a performance problem though, so I'm not exactly sure. I'm also using C because the psp homebrew compiler doesn't like C++.

I was thinking having methods that work like "ChangeWorld(Worlds::MainMenu);" but I'm not really sure what I should have the method do.

Name: Anonymous 2012-03-22 7:11

Inheritance and polymorphism is only one way to implement the underlying idea you're trying at.

For instance, design the interaction flow as a simple state machine. Each state represents one screen, i.e. menu, loading screen or the game. This is pretty much what you already do. Every state can have one or more exit states, and have state-transition logic take care of moving from state to state. For instance, the update function could return the next state to run. Either do as >>2 suggested, with a vtable:
struct world {
    void *data, (*input)(void *, struct event *), (*draw)(void *);
    struct world *(*update)(void *);
};

void run_game(...) {
    struct world *w = initial_state(...);
    ...
    while (w != end_state) {
        w->input(w->data, get_event(...));
        w->draw(w->data);
        w = w->update(w->data);
    }
    ...
}

or if there are only a very small number of states, you could even use a switch statement and have enumerated states.

Another solution is to have both the game levels and main menu built up of the same primitives, i.e. rects/images for 2D or a polygon list or so for 3D, that comprise a scene. Then you make a generic renderer that has freedom to draw the primitives in any order and with any platform specific implementation. Make a generic input handler that finds what clickable primitive was clicked and call a function that was associated with the item.

Remember, you don't need taxonomies for separating interfaces and implementations. C++ style classes are one way, but not the only one. Especially for the renderer, making the nodes of the scene abstract takes away a huge amount of optimization possibilities, for instance you can draw front to back instead of back to front (back to front happens when you have a widget class that recursively calls draw() on all of its children).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List