# Dealing with keyboard input

In game design how should keyboard input be handled and why? Do i A: check the state of keys in the main loop each iteration? B: Read key down and key up events from the event queue.

Im using allegro 5 and using the event queue model atm, but ive seen the other method in some samples..

• What are your game's needs? Either model works just fine. Games with more complex needs might even just abstract all the input behind a much higher level input manager. – Sean Middleditch Aug 4 '12 at 20:34

Either model will work, and it really ends up depending on the overall structure of your game. While I'm not familiar with allegro specifically, the model that I see most often is the queue model, with a system that looks something like this:

//Main game loop
while(running) {
//Read in all the events from the queue
while(eventQueue.hasNext()) { //While there are more events on the queue..
Event e = eventQueue.pop(); //Get the event
if(e.type == mouseClick) { //Check the event
//Whatever logic here
}
}

//Other game logic and rendering here
}


This code is obviously very non-specific, but I have seen similar work with SDL, SFML and allegro samples. The advantage this has is that it is easier to work with, at least in my opinion, when one does that have to deal with saving the state of each key.

If you use state based input, then you only are ever going to be able to process information available at exactly the time you run your logic iteration. This means if something happens between iterations, you will miss input.

With events, you can examine the timestamp and know exactly when something happened. You can know whether or not a key was actually held down during the entire time between iterations. But often that is irrelevant in terms of keyboard input. In many cases, you'll find that people do something like:

case ALLEGRO_EVENT_KEY_DOWN:
if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
input.left = true;
break;

case ALLEGRO_EVENT_KEY_UP:
if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
input.left = false;
break;


This gives you state based input, but you can mix it in with other event code such that you don't have two different ways to process data.

So basically, events are mandatory if you do not want to miss any input or if you need to know the "precise" time something occurred. Otherwise, state based is sufficient.