Game event loop and input

I’m starting to map out the various stages of my game, intro, tutorial, game play, cut scenes, etc. and it is getting a little ugly when it comes to what I envision as user input and the basic event loop. I’m thinking I need to create a global that stores the current game state and use a series of case statements within the PollEvent loop. This seems a bit bulky though and could run pages long.

Has anyone had experience in developing a custom class that you can use to wrap around the event to simplify the event structure with respect to your game states? Or perhaps other ways that you have found especially effective in keeping code clean and simple?

  • Joby
    http://jobybednar.com
    Give someone a program - frustrate them for a day.
    Teach them how to program - frustrate them for a lifetime.

I’m starting to map out the various stages of my game, intro, tutorial,
game play, cut scenes, etc. and it is getting a little ugly when it
comes to what I envision as user input and the basic event loop. I’m
thinking I need to create a global that stores the current game state
and use a series of case statements within the PollEvent loop. This
seems a bit bulky though and could run pages long.

Yes, I’m very interested in any info in this area as well. In my program,
I call a handleEvents every frame. I’d like to add a menu to the program
that will take key events as well.

My solution was to use a handleGameEvents normally, but if in menu mode
(indicated by some global variable), then to do a handleMenuEvents
instead.

Something makes me think there should be a cleaner way though. What if I
want to add a different menu? Create another function to handle those
events??

I guess what I’d like to know is how to simulate a multi-event paradigm in
SDL, like one does in a GUI toolkit.

SteveOn January 30, 2003 09:12 pm, Joby Bednar wrote:

I think this is more a general game programming question.

Try www.gamedev.net or www.flipcode.com.

Most importantly, try www.google.com.

Check out the developer diaries on www.pyrogon.com.

Check out the source to one/many of the many games listed on the libsdl
webpage.

Owen Butler> -----Original Message-----

From: sdl-admin at libsdl.org [mailto:sdl-admin at libsdl.org]On Behalf Of
Joby Bednar
Sent: Friday, 31 January 2003 11:43 AM
To: sdl at libsdl.org
Subject: [SDL] Game event loop and input

This message was transferred with a trial version of CommuniGate™ Pro
I’m starting to map out the various stages of my game, intro,
tutorial, game play, cut scenes, etc. and it is getting a little
ugly when it comes to what I envision as user input and the basic
event loop. I’m thinking I need to create a global that stores
the current game state and use a series of case statements within
the PollEvent loop. This seems a bit bulky though and could run
pages long.

Has anyone had experience in developing a custom class that you
can use to wrap around the event to simplify the event structure
with respect to your game states? Or perhaps other ways that you
have found especially effective in keeping code clean and simple?

  • Joby
    http://jobybednar.com
    Give someone a program - frustrate them for a day.
    Teach them how to program - frustrate them for a lifetime.

SDL mailing list
SDL at libsdl.org
http://www.libsdl.org/mailman/listinfo/sdl

I think this is more a general game programming question.

Try www.gamedev.net or www.flipcode.com.

Most importantly, try www.google.com.

Check out the developer diaries on www.pyrogon.com.

Check out the source to one/many of the many games listed on the libsdl
webpage.

Owen Butler

I was actaully hoping for any experience specifically with SDL events, since they are a little different than the Win32 message structure I’m used to coding in. I was hoping someone might have some snazzy experience in taking the SDL ideas to heart and simplifying the ugliness that could be created among the stages in a game by some additional class interactions. But thanks anyway, I’ll take a look around at those sites.

  • Joby
    http://jobybednar.com
    Give someone a program - frustrate them for a day.
    Teach them how to program - frustrate them for a lifetime.

You don’t necessarily need classes for that, take a look at the C code I use
in my minimal engine demo:

http://people.nl.linux.org/~phillips/world/world.zip

Raw events from a variety of sources are classified and translated into
generic engine actions using a simple but powerful binding technique. This
uses two-column tables to define the bindings, where each row means “if this
event comes in, do that action”. This is like a relational table in that
it’s capable of expressing one-to-one, many-to-one, one-to-many and
many-to-many relationships. In other words, you can bind each key to more
than one action, or as many keys as you like to the same action or group of
actions.

Each different input device has its own two-column table, which I did because
it was slightly simpler than having three-column tables.

There’s also a filter hook that game code, as opposed to engine code, can use
to override any default binding. Anyway, the binding tables should not be
static declarations as I’ve written, they should be dynamically allocated so
you can load them from a file and the player can change them. It’s just a
demo, so I didn’t go that far.

Regards,

DanielOn Friday 31 January 2003 01:42, Joby Bednar wrote:

I’m starting to map out the various stages of my game, intro, tutorial,
game play, cut scenes, etc. and it is getting a little ugly when it comes
to what I envision as user input and the basic event loop. I’m thinking I
need to create a global that stores the current game state and use a series
of case statements within the PollEvent loop. This seems a bit bulky
though and could run pages long.

Has anyone had experience in developing a custom class that you can use to
wrap around the event to simplify the event structure with respect to your
game states? Or perhaps other ways that you have found especially
effective in keeping code clean and simple?

Slightly OT…

On Thu, 30 Jan 2003 16:42:46 -0800, “Joby Bednar”
said:

I’m starting to map out the various stages of my game, intro, tutorial,
game play, cut scenes, etc. and it is getting a little ugly when it
comes to what I envision as user input and the basic event loop. I’m
thinking I need to create a global that stores the current game state
and use a series of case statements within the PollEvent loop. This
seems a bit bulky though and could run pages long.

Has anyone had experience in developing a custom class that you can use
to wrap around the event to simplify the event structure with respect
to your game states? Or perhaps other ways that you have found
especially effective in keeping code clean and simple?

The first or second article in `Game Programming Gems 3’ is about a
similar topic to this. He talks about a thing which he calls a Game
Framework. It has a website - www.gameframework.com - which is updated
reasonably regularly.

The basic concept is that you have layers' which can each have control. The layers are, well,layered’ on top of one another. The top one gets
the first shot at the input, and if it doesn’t handle it, the next one
gets a go, and so on. (There can be exclusive layers which don’t give
anyone else a go at the input.) So the input cascades down the chain of
layers. A menu can be an exclusive layer which tacks onto the front of
the stack. You can have different layers for different parts of the
interface. It’s quite flexible, and works pretty well with SDL.

Hope that helps,

Dave.–
David Slutzkin, BCS (Hons)
Melbourne, Australia
@Dave_Slutzkin


http://fastmail.fm - Choose from over 50 domains or use your own

Have a look at state patterns.

There is a good article on this in

http://www.codeproject.com/tips/statepattern3.asp

Its for MFC but each class handles it own events etc.

For example Intro - Has a message loop, when intro has finished it changes
state to menu - which has its own message loop etc, etc, etc…

Have a read !!

I’m starting to map out the various stages of my game, intro,
tutorial, game play, cut scenes, etc. and it is getting a little
ugly when it comes to what I envision as user input and the basic
event loop. I’m thinking I need to create a global that stores the
current game state and use a series of case statements within the
PollEvent loop. This seems a bit bulky though and could run pages
long.

In Kobo Deluxo, I’m using a generic game state class for this. When
you add a state to the game, you derive from a state class, override
handlers for events, video frames, game logic frames etc. The state
manager class has methods for switching and pushing states, so you
can either replace the current state with another state, or "call"
the another state, subroutine style.

This makes it easy to enter the options dialog from within the game
and then return to the current game when leaving it, and that sort of
stuff.

Has anyone had experience in developing a custom class that you can
use to wrap around the event to simplify the event structure with
respect to your game states?

Well, yes and no; the event itself is rather irrelevant here, IMHO.
It’s the state and whatever manages states that are the actual
objects here. It’s a pretty typical state machine, and the events are
just one form of input to it.

Or perhaps other ways that you have
found especially effective in keeping code clean and simple?

The game_state_manager of Kobo Deluxe does the job pretty well, IMHO,
but it’s perhaps not as clean as it could be. It sort of evolved over
time, and I haven’t looked at it in a while; maybe it’s just the game
code around it that’s messy? :slight_smile:

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Friday 31 January 2003 01.42, Joby Bednar wrote:

[…]

My solution was to use a handleGameEvents normally, but if in menu
mode (indicated by some global variable), then to do a
handleMenuEvents instead.

That’s a basic state machine design. I think that’s about the only way
to keep this clean if you have more than one or two menues. As soon
as you have intro mode, game mode, “get ready” mode and a few dialogs
such as “end current game?”, “quit game?”, options etc, anything else
will be a total mess. Sooner or later, you’ll want to use some of the
dialogs from within more than one game state, which is where you
realize a state stack is rather handy…

Something makes me think there should be a cleaner way though.
What if I want to add a different menu? Create another function to
handle those events??

Well, you can’t really get around that… You can translate the
events into something that fits your design better, though, if that
helps.

In Kobo Deluxe, I have rudimentary internal “control events”, that are
IIRC, function call delivered and based on generic control "buttons"
rather than actual keys, mouse buttons, joystick events etc. The idea
is that everything goes through the input mapper first, so you can
control the game, menues and all with whatever controller you decide
to use. (So you can reach the menues at all, even if you don’t have a
keyboard in reach, or don’t have one at all.)

I guess what I’d like to know is how to simulate a multi-event
paradigm in SDL, like one does in a GUI toolkit.

Same way, really - although dialogs in games are generally modal,
which is something that GUI toolkits handle for you in the
background. SDL doesn’t even have the concept of “dialogs” and
"windows", nor the concept of different “objects” as event receivers,
so you have to this yourself.

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Friday 31 January 2003 01.57, Stephen Anthony wrote:

Another possible solution to several of the questions asked in this
thread might be to create an array of function points that handle the
different states.

DoStateFunc(current_state);

void DoStateFunc(int & state) {
State_Function_Arraystate; // takes a state reference
// to change it
}

In what way? (Yes, I’ve done some Win32 programming as well…)

The only important difference is that SDL has only one place to send
events, and no focus system. It couldn’t have, in any useful way, so
you have to implement that yourself in some way that works for you.
If you want windows, controls and focus, just implement that.

The easy way is dispatching events in a main event handler and
delivering them through function calls, but you could implement your
own event queues as well, if you like that better. (Although that’s
only really useful if you get tons of events that you won’t be able
to handle without serious filtering, and you don’t want to do the
filtering in the dispatcher.)

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Friday 31 January 2003 02.42, Joby Bednar wrote:

I think this is more a general game programming question.

Try www.gamedev.net or www.flipcode.com.

Most importantly, try www.google.com.

Check out the developer diaries on www.pyrogon.com.

Check out the source to one/many of the many games listed on the
libsdl webpage.

Owen Butler

I was actaully hoping for any experience specifically with SDL
events, since they are a little different than the Win32 message
structure I’m used to coding in.

David Olofson wrote:

In Kobo Deluxo, I’m using a generic game state class for this. When
you add a state to the game, you derive from a state class, override
handlers for events, video frames, game logic frames etc. The state
manager class has methods for switching and pushing states, so you
can either replace the current state with another state, or "call"
the another state, subroutine style.

This sounds like a very useful system and much like what I was thinking
of doing in my project. Your way seems much better tho. I’m going to
have to take a look at the kobo-deluxe source and see what i can learn.

I was actaully hoping for any experience specifically with SDL
events, since they are a little different than the Win32 message
structure I’m used to coding in.

In what way? (Yes, I’ve done some Win32 programming as well…)

Well, to be honest, I think SDL handles events the way Win32 should have. Although there is an obvious strong simularity, SDL throws the data into a stronger OO environment allowing you to easily, cleanly and logically determine what happened and where. It gets a little old dealing with high and low words. Yes, I know SDL does this in the background, that’s why I like it so much. I was just hoping that this organization would lend itself well to someone sitting down and saying, “perhaps if I tie it into my events and game state like this… and give it a really hot cup of tea…” Bam! Suddenly we have the Infinite Probability Drive. :wink:

I like the previous postings on relation tables and layers. Working these into a game state system would be interesting. Last night I was building a game state system using bit flags for game states. The idea was to use the over all value as a general checking for states, but then being able to combine states when determining event filters, and even grouping states as combinations of the bit flags.

For example, I define game states where:

PAUSED = 0x01 (0000 0001)
INTRO = 0x02 (0000 0010)
LOADING = 0x05 (0000 0101)
OPTIONS_MENU = 0x09 (0000 1001)
LEVEL_BEGIN = 0x10, etc. (0001 0000)

The game state could then be set as (LEVEL_BEGIN | LOADING) for a loading dialog above new level background, or (LEVEL_PLAY | OPTIONS_MENU) for being in game play but having hit the options menu. But, as you see, both LOADING and OPTIONS_MENU inlcude the PAUSED bit, so the system is also in a PAUSED state. The event filters would receive a mouse click and know that the options menu is up so look to see if it’s on the menu otherwise ignore, and the rendering engine could check the state and see it’s during LEVEL_PLAY so render the sprites in their current positions, but it’s also in a PAUSED state, so don’t calculate their new positions and just keep things where they are.

I don’t know… perhaps its just a dream, but I think there’s a way to do it where the very nature of each entity defines the states and relationships to the others… without the huge masses of event and game state trees. SDL seems like it would lend itself nicely to inherited classes from the event object.

I’ll have to sit down and piece together everyone’s suggestions and see what works best for my situation. But thanks for all of the suggestions and links!

  • Joby
    http://jobybednar.com
    Give someone a program - frustrate them for a day.
    Teach them how to program - frustrate them for a lifetime.

Please, go ahead. That code (as most other new files I’ve added) is
LGPL, so you can even use it as is or modified, regardless of what
license you use for your game.

BTW, as you might notice, Kobo Deluxe implements “state on state” by
calling back to the previous state on the stack. That’s how I put
menues and stuff on top of whatever game state is running. So, you
could just have someone fire up the options dialog in the middle of
the game. In fact, it would work even if you have one or more other
menues “active” on the stack, as they’d just pass the “up calls” on.

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Friday 31 January 2003 19.59, Calvin Spealman wrote:

David Olofson wrote:

In Kobo Deluxo, I’m using a generic game state class for this.
When you add a state to the game, you derive from a state class,
override handlers for events, video frames, game logic frames
etc. The state manager class has methods for switching and
pushing states, so you can either replace the current state with
another state, or “call” the another state, subroutine style.

This sounds like a very useful system and much like what I was
thinking of doing in my project. Your way seems much better tho.
I’m going to have to take a look at the kobo-deluxe source and see
what i can learn.

[…]

Please, go ahead. That code (as most other new files I’ve added) is
LGPL, so you can even use it as is or modified, regardless of what
license you use for your game.

Actually, no - for some reason I don’t remember, it’s GPL, not LGPL.

However, I wrote those two files (gamestate.(cpp|h) from scratch, so
I’ll just rerelease them under the LGPL if that’s an issue. (Rather
trivial stuff, though; the idea is the interesting part.)

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Saturday 01 February 2003 01.12, David Olofson wrote:

I was actaully hoping for any experience specifically with SDL
events, since they are a little different than the Win32 message
structure I’m used to coding in.

In what way? (Yes, I’ve done some Win32 programming as well…)

Well, to be honest, I think SDL handles events the way Win32 should
have. Although there is an obvious strong simularity, SDL throws
the data into a stronger OO environment allowing you to easily,
cleanly and logically determine what happened and where. It gets a
little old dealing with high and low words.

Especially when words are actually longs… :wink: (That’s hungarian
notation in APIs for ya’.)

Yes, I know SDL does
this in the background, that’s why I like it so much.

In fact, SDL does a lot of stuff like this in the background; messing
with the little details we don’t want to see - and that’s why we all
like it so much. :slight_smile:

I was just
hoping that this organization would lend itself well to someone
sitting down and saying, "perhaps if I tie it into my events and
game state like this… and give it a really hot cup of tea…"
Bam! Suddenly we have the Infinite Probability Drive. :wink:

Of course. Well, SDL doesn’t remove any information (except possibly
for timestamps, in the few cases there are any), so what you have is
a single window getting events. Pretty much like looking at a raw
hardware display and some input devices. There’s basically nothing
you can’t do within that context.

I like the previous postings on relation tables and layers.

Yes, that’s interesting stuff. I have unlimited layers (through “up
calls”), but I don’t even have basic input mapping yet. I have an
object that maps various kinds of input to some kind of “uniform
buttons”, but that’s a quick hack and is entirely hardcoded. (Well,
you can chose keyboard/mouse/joystick, but that’s about it.)

Working these into a game state system would be interesting. Last
night I was building a game state system using bit flags for game
states. The idea was to use the over all value as a general
checking for states, but then being able to combine states when
determining event filters, and even grouping states as combinations
of the bit flags.
[…]

Problem with this is that the “state manager” is now useless when it
comes to defining how states are related. Also note that the
relations may be dynamic (ie states aren’t always layered in the same
order), and that state relations are generally a bit more complicated
than order of handler execution.

In Kobo Deluxe, I generally call game rendering objects directly from
within states, but that’s not really the right way to do it. (That
part is quite messy, and could use some cleaning up.)

Anyway, when rendering a game screen with visible objects that belong
to various layers (ie stacked states, where some run “in the
background”), it’s not obvious in what order the different callbacks
of each state should be called. You may want to do some things in
stack order, and other things in reverse stack order, and some states
might even want to call up the stack in the middle of their handlers,
so they can do stuff both before and after the background states have
done their work.

Anyway, I found the gsm.previous()->whatever() approach rather handy.
I does mean each state has to decide whether it cares to run certain
parts of the background state(s), but that’s also a feature.

For example, you could implement pause by just not calling frame() of
the previous state from your frame(), but still call render() to have
the playfield graphics drawn. Obviously, menu states generally don’t
forward input events to the previous state, and you might want to do
that for the pause state as well, depending on how your game logic
handles input.

I suspect there are better ways, but it easilly gets intrusive and
starts assuming things about the game code… The basic rule that
only the current state is driven by the state manager, and states may
"call up" to the previous state if they want, makes things very
simple for simple games, but supports the most hairy inter-state
relations.

I don’t know… perhaps its just a dream, but I think there’s a way
to do it where the very nature of each entity defines the states
and relationships to the others… without the huge masses of event
and game state trees.

Yes… It’s just that the relations can be quite complex, so it might
be hard to express them in any simple way without imposing
significant restrictions upon the design. (See above.)

SDL seems like it would lend itself nicely
to inherited classes from the event object.

Well, I prefer to think of the events as just data. I don’t see why
you would want to inherit from the event struct. What am I missing?

I’ll have to sit down and piece together everyone’s suggestions and
see what works best for my situation. But thanks for all of the
suggestions and links!

NP. Of course, we’d like to hear about your conclusions. :slight_smile:

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Friday 31 January 2003 20.13, Joby Bednar wrote:

David Olofson wrote:

Please, go ahead. That code (as most other new files I’ve added) is
LGPL, so you can even use it as is or modified, regardless of what
license you use for your game.

Actually, no - for some reason I don’t remember, it’s GPL, not LGPL.

Thankfully, I decided to press my luck and write my own State handling
class. It works just fine, after a little tweaking. I can even move to
previous states on the stack while keeping the newer states “on hold”,
even tho i might never use that feature.

The only thing that tripped me up is having the code of one state cause
its own destruction. I wanted to avoid things like “bool isAlive;”, and
have a cleaner implementation. So, I use try/catch sections to handle
events like that.

try {
State::Tick();
} catch(CloseState e) {
State::EndState();
}

Works fine, too.

David Olofson wrote:

Please, go ahead. That code (as most other new files I’ve added)
is LGPL, so you can even use it as is or modified, regardless of
what license you use for your game.

Actually, no - for some reason I don’t remember, it’s GPL, not
LGPL.

Thankfully, I decided to press my luck and write my own State
handling class. It works just fine, after a little tweaking. I can
even move to previous states on the stack while keeping the newer
states “on hold”, even tho i might never use that feature.

Might be a way to drop back to the map view for an "alternative mode"
in a map editor or something… Say you bring up the tile selector,
and in it, you have a button “pick from map” - which hides the tile
selector layer, while still actually remaining in the tile selector
state.

Or something like that… :wink:

The only thing that tripped me up is having the code of one state
cause its own destruction. I wanted to avoid things like “bool
isAlive;”, and have a cleaner implementation. So, I use try/catch
sections to handle events like that.

try {
State::Tick();
} catch(CloseState e) {
State::EndState();
}

Works fine, too.

Yeah, that’s one way…

I just say that state changes are “delayed”; ie they don’t actually
happen until the function that causes the state change returns. Now,
I don’t destroy states on the fly, since I want to keep the amount of
dynamic memory allocation down - but it wouldn’t be a problem with
that design, since you’re always in the “state manager” when it would
happen.

//David Olofson - Programmer, Composer, Open Source Advocate

.- The Return of Audiality! --------------------------------.
| Free/Open Source Audio Engine for use in Games or Studio. |
| RT and off-line synth. Scripting. Sample accurate timing. |
`---------------------------> http://olofson.net/audiality -’
http://olofson.nethttp://www.reologica.se —On Monday 03 February 2003 21.11, Calvin Spealman wrote:

The only thing that tripped me up is having the code of one state cause
its own destruction. I wanted to avoid things like “bool isAlive;”, and
have a cleaner implementation. So, I use try/catch sections to handle
events like that.

try {
State::Tick();
} catch(CloseState e) {
State::EndState();
}

Works fine, too.

You might not want to use C++ exception handling mechanism to handle a
relatively common condition as a state change unless you don’t care
about performance. I don’t know how often you change states in your
scheme so I’m not saying this will cause trouble for you but you might
want to consider that every try block entry costs you and leaving a
function due to throw might be considerably (Meyers says several orders
of magnitude) slower than simple return. I’m all for exceptions but
they are designed to handle exceptional conditions so think twice before
using them.

latimeriusOn Mon, Feb 03, 2003 at 03:11:10PM -0500, Calvin Spealman wrote:

Latimerius wrote:

You might not want to use C++ exception handling mechanism to handle a
relatively common condition as a state change unless you don’t care
about performance. I don’t know how often you change states in your
scheme so I’m not saying this will cause trouble for you but you might
want to consider that every try block entry costs you and leaving a
function due to throw might be considerably (Meyers says several orders
of magnitude) slower than simple return. I’m all for exceptions but
they are designed to handle exceptional conditions so think twice before
using them.

I didnt think they took much resources. It doesnt seem like that would
have to. Why would the throw statement have to be any different than
calling a function? Or, given that most exceptions are possibly 0 size,
the throw could be as simple as a jmp.