[SDL] What's the best way to implement rebindable keys?

Neil Bradley nb at synthcom.com
Mon Sep 9 01:48:01 PDT 2002


> Hi! I'm writing a little tetris clone to teach myself SDL, and I've run
> across an interesting problem: what's the best way to implement
> rebindable keys?

"Best" is of course subjective, but I have a suggestion.

I created a concept of a binary, analog, and ballistics controller to
handle on/off style transitions, analog for continuous transitions, and
ballistics for difference of position reports. It can either be
on/asserted off/deasserted. I kept a key assignment table for every
controller in the game - a 1 to N mapping (a linked list). So in your
case, I'd create:

CTRL_UP
CTRL_DOWN
CTRL_LEFT
CTRL_RIGHT
CTRL_SPINLEFT
CTRL_SPINRIGHT
CTRL_START
CTRL_SELECT

as an enumeration of 0-7. Then create a structure containing the assigned
keys/buttons/whatever to them:

struct SControllerAssignment
{
	EControllerType eType;
	SDL_Key sKeyAssign;
	struct SControllerAssignment *psNextController;
}

So in memory, it'd look something like (forgive the names and whatnot -
I know they probably aren't right):

CTRL_UP -> SDL_KEYUP -> SDL_PAD8
CTRL_DOWN -> SDL_KEYDOWN -> SDL_PAD2

That way you can add/take away assignments from anywhere. Of course you
can extend the SControllerAssignment structure to include make/break from
any other sources - including joysticks.

> (int keysyms[8]), but that meant scanning the array every time I got a
> keypress, which meant repeated code in every key-related or
> joystick-related event.

That's not a bad thing. Scanning each key for all assignments when an
event comes in (you are scanning only when those types of events are
deposited in the queue, right?) does not take much CPU power.

> Ideally, I'd like to use a hash of the event type and keysym or
> button-number as an index into an array, but that seems a little complex.

It is. You can't get around looking to match up logical controllers within
a game to physical controllers. Basically I created a logical<->physical
converter that can accept anything. I do have to scan the active
controller list looking for its assignment.

This has the distinct advantage of being very flexible - as well as not
having to keep a keymap on all held keys. Plus, that means that you can
assign one function to multiple controllers without having one override
another continuously due to polling.

-->Neil

-------------------------------------------------------------------------------
Neil Bradley            What are burger lovers saying
Synthcom Systems, Inc.  about the new BK Back Porch Griller?
ICQ #29402898	        "It tastes like it came off the back porch." - Me






More information about the SDL mailing list