Handling the Keyboard

Keyboard Related Structures

It should make it a lot easier to understand this tutorial is you are familiar with the data types involved in keyboard access, so I'll explain them first.

SDLKey

SDLKey is an enumerated type defined in SDL/include/SDL_keysym.h and detailed here. Each SDLKey symbol represents a key, SDLK_a corresponds to the 'a' key on a keyboard, SDLK_SPACE corresponds to the space bar, and so on.

SDLMod

SDLMod is an enumerated type, similar to SDLKey , however it enumerates keyboard modifiers (Control, Alt, Shift). The full list of modifier symbols is here. SDLMod values can be AND'd together to represent several modifiers.

SDL_keysym

  TSDL_KeySym = record
scancode: Uint8; // hardware specific scancode
sym: TSDLKey; // SDL virtual keysym
modifier: TSDLMod; // current key modifiers
unicode: Uint16; // translated character
end;

The SDL_keysym structure describes a key press or a key release. The scancode field is hardware specific and should be ignored unless you know what your doing. The sym field is the SDLKey value of the key being pressed or released. The mod field describes the state of the keyboard modifiers at the time the key press or release occurred. So a value of KMOD_NUM | KMOD_CAPS | KMOD_LSHIFT would mean that Numlock, Capslock and the left shift key were all press (or enabled in the case of the lock keys). Finally, the unicode field stores the 16-bit unicode value of the key.

Note: It should be noted and understood that this field is only valid when the SDL_keysym is describing a key press, not a key release. Unicode values only make sense on a key press because the unicode value describes an international character and only key presses produce characters. More information on Unicode can be found at www.unicode.org

Note: Unicode translation must be enabled using the SDL_EnableUNICODE function.

SDL_KeyboardEvent

TSDL_KeyboardEvent = record
type_: Uint8; // SDL_KEYDOWN or SDL_KEYUP
which: Uint8; // The keyboard device index
state: Uint8; // SDL_PRESSED or SDL_RELEASED
keysym: TSDL_KeySym;
end;

The SDL_KeyboardEvent describes a keyboard event (obviously). The key member of the SDL_Event union is a SDL_KeyboardEvent structure. The type field specifies whether the event is a key release (SDL_KEYUP) or a key press ( SDL_KEYDOWN) event. The state is largely redundant, it reports the same information as the type field but uses different values (SDL_RELEASED and SDL_PRESSED ). The keysym contains information of the key press or release that this event represents (see above).

Reading Keyboard Events

Reading keybaord events from the event queue is quite simple (the event queue and using it is described here). We read events using SDL_PollEvent in a while() loop and check for SDL_KEYUP and SDL_KEYDOWN events using a switch statement, like so:

Example 3-10. Reading Keyboard Events

  event : TSDL_Event;
.
.
// Poll for events. SDL_PollEvent() returns 0 when there are no
// more events on the event queue, our while loop will exit when
// that occurs.
while ( SDL_PollEvent( &event ) > 0 ) do
begin
// We are only worried about SDL_KEYDOWN and SDL_KEYUP events
case event.type_ of
SDL_KEYDOWN:
begin
MessageBox(0, 'Key press detected', 'Error', MB_OK or MB_ICONHAND);
end;

SDL_KEYUP:
begin
MessageBox(0, 'Key release detected', 'Error', MB_OK or MB_ICONHAND);
end;
end;
end;
.
.

This is a very basic example. No information about the key press or release is interpreted. We will explore the other extreme out our first full example below - reporting all available information about a keyboard event.

A More Detailed Look

Before we can read events SDL must be initialised with SDL_Init and a video mode must be set using SDL_SetVideoMode. There are, however, two other functions we must use to obtain all the information required. We must enable unicode translation by calling SDL_EnableUNICODE(1) and we must convert SDLKey values into something printable, using SDL_GetKeyName

Note: It is useful to note that unicode values < 0x80 translate directly a characters ASCII value. THis is used in the example below

Example 3-11. Interpreting Key Event Information


uses SDL;

// Function Prototypes
procedure PrintKeyInfo( key : PSDL_KeyboardEvent );
procedure PrintModifiers( mod : TSDLMod );

var
event : TSDL_Event;
quit : boolean;
// main
begin
quit := false;

// Initialise SDL
if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) then
begin
MessageBox(0, PChar(Format('Couldn''t initialize SDL : %s', [SDL_GetError])), 'Error', MB_OK or MB_ICONHAND);
halt( -1 );
end;

// Set a video mode
if ( SDL_SetVideoMode( 320, 200, 0, 0 ) < 0 ) then
begin
MessageBox(0, PChar(Format('Couldn''t set video mode : %s', [SDL_GetError])), 'Error', MB_OK or MB_ICONHAND);
SDL_Quit;
halt( -1 );
end;

// Enable Unicode translation
SDL_EnableUNICODE( 1 );

// Loop until an SDL_QUIT event is found
while ( !quit ) do
begin

// Poll for events
while ( SDL_PollEvent( &event ) > 0 ) do
begin
case event.type_ of
// Keyboard event
// Pass the event data onto PrintKeyInfo()
SDL_KEYDOWN:
SDL_KEYUP:
begin
PrintKeyInfo( @event.key );
end;

// SDL_QUITEV event (window close)
SDL_QUITEV:
begin
quit := true;
end;
end;
end;
end;

// Clean up
SDL_Quit;
halt( 0 );
end;

// Print all information about a key event
procedure PrintKeyInfo( key : PSDL_KeyboardEvent );
var
KeyInfo : string;
begin
// Is it a release or a press?
if ( key.type_ = SDL_KEYUP ) then
KeyInfo := 'Release:-'
else
KeyInfo := 'Press:-';

// Print the hardware scancode first
KeyInfo := KeyInfo + Format( 'Scancode: $%02X', [key.keysym.scancode] ) + #13#10;
// Print the name of the key
KeyInfo := KeyInfo + Format( 'Name: %s', [SDL_GetKeyName( key->keysym.sym )] ) + #13#10;
// We want to print the unicode info, but we need to make
// sure its a press event first (remember, release events
// don't have unicode info
if ( key.type_ = SDL_KEYDOWN ) then
begin
// If the Unicode value is less than 0x80 then the
// unicode value can be used to get a printable
// representation of the key, using (char)unicode.
KeyInfo := KeyInfo + 'Unicode: ';
if( key.keysym.unicode < $80 ) and ( key->keysym.unicode > 0 ) then
begin
KeyInfo := KeyInfo + Format( '%c ($%04X)', [(char)key.keysym.unicode, key.keysym.unicode] ) + #13#10;
end
else
begin
KeyInfo := KeyInfo + Format( '? ($%04X)', [key.keysym.unicode] );
end;
end;

// Print modifier info
PrintModifiers( key.keysym.mod );
end;

// Print modifier info
procedure PrintModifiers( smod : TSDLMod );
var
Mods : string;
begin
Mods := 'Modifers: ' + #13#10;

// If there are none then say so and return
if ( smod = KMOD_NONE ) then
begin
Mods := Mods + 'None';
end
else
begin

// Check for the presence of each SDLMod value
// This looks messy, but there really isn't
// a clearer way.
if ( smod and KMOD_NUM ) then
Mods := Mods + 'NUMLOCK ' + #13#10;
if ( smod and KMOD_CAPS ) then
Mods := Mods + 'CAPSLOCK ' + #13#10;
if ( smod and KMOD_LCTRL ) then
Mods := Mods + 'LCTRL ' + #13#10;
if ( smod and KMOD_RCTRL ) then
Mods := Mods + 'RCTRL ' + #13#10;
if ( smod and KMOD_RSHIFT ) then
Mods := Mods + 'RSHIFT ' + #13#10;
if ( smod and KMOD_LSHIFT ) then
Mods := Mods + 'LSHIFT ' + #13#10;
if ( smod and KMOD_RALT ) then
Mods := Mods + 'RALT ' + #13#10;
if ( smod and KMOD_LALT ) then
Mods := Mods + 'LALT ' + #13#10;
if ( smod and KMOD_CTRL ) then
Mods := Mods + 'CTRL ' + #13#10;
if ( smod and KMOD_SHIFT ) then
Mods := Mods + 'SHIFT ' + #13#10;
if ( smod and KMOD_ALT ) then
Mods := Mods + 'ALT ' + #13#10;
end;
MessageBox(0, PChar( Mods ), 'Error', MB_OK or MB_ICONHAND);
end;

Game-type Input

I have found that people using keyboard events for games and other interactive applications don't always understand one fundemental point.

Keyboard events only take place when a keys state changes from being unpressed to pressed, and vice versa.

Imagine you have an image of an alien that you wish to move around using the cursor keys - when you pressed the left arrow key you want him to slide over to the left, when you press the down key you want him to slide down the screen. Examine the following code, it highlights and error that many people have made.

var    
// Alien screen coordinates
alien_x : integer = 0;
alien_y : integer = 0;
.
.
// Initialise SDL and video modes and all that
.
// Main game loop
// Check for events
while ( SDL_PollEvent( &event ) ) do
begin
case event.type_ of
// Look for a keypress
SDL_KEYDOWN:
begin
// Check the SDLKey values and move change the coords
case event.key.keysym.sym of
SDLK_LEFT:
begin
dec( alien_x );
end;

SDLK_RIGHT:
begin
inc( alien_x );
end;

SDLK_UP:
begin
dec( alien_y );
end;

SDLK_DOWN:
begin
inc( alien_y );
end;
end;
end;
end;
end;
.
.
At first glance you may think this is a perfectly reasonable piece of code for the task, but it isn't. Like I said keyboard events only occur when a key changes state, so the user would have to press and release the left cursor key 100 times to move the alien 100 pixels to the left.

To get around this problem we must not use the events to change the position of the alien, we use the events to set flags which are then used in a seperate section of code to move the alien. Something like this:

Example 3-12. Proper Game Movement

    
var
// Alien screen coordinates
alien_x : integer = 0;
alien_y : integer = 0;
alien_xvel : integer = 0;
alien_yvel : integer = 0;
.
.
// Initialise SDL and video modes and all that
.
// Main game loop
// Check for events
while ( SDL_PollEvent( @event ) > 0 ) do
begin
case event.type_ of
// Look for a keypress
SDL_KEYDOWN:
begin
// Check the SDLKey values and move change the coords
case event.key.keysym.sym of
SDLK_LEFT:
begin
alien_xvel := -1;
end;

SDLK_RIGHT:
begin
alien_xvel := 1;
end;

SDLK_UP:
begin
alien_yvel := -1;
end;

SDLK_DOWN:
begin
alien_yvel := 1;
end;
end;
end;
/* We must also use the SDL_KEYUP events to zero the x */
/* and y velocity variables. But we must also be */
/* careful not to zero the velocities when we shouldn't*/
SDL_KEYUP:
begin
case event.key.keysym.sym of
SDLK_LEFT:
begin
// We check to make sure the alien is moving
// to the left. If it is then we zero the
// velocity. If the alien is moving to the
// right then the right key is still press
// so we don't tocuh the velocity
if ( alien_xvel < 0 ) then
alien_xvel := 0;
end;

SDLK_RIGHT:
begin
if ( alien_xvel > 0 ) then
alien_xvel := 0;
end;

SDLK_UP:
begin
if ( alien_yvel < 0 ) then
alien_yvel := 0;
end;

SDLK_DOWN:
begin
if ( alien_yvel > 0 ) then
alien_yvel := 0;
end;
end;
end;
end;
end;
.
.
// Update the alien position
inc( alien_x, alien_xvel );
inc( alien_y, alien_yvel );

As can be seen, we use two extra variables, alien_xvel and alien_yvel, which represent the motion of the ship, it is these variables that we update when we detect keypresses and releases.