[SDL] What's the best way to implement rebindable keys?
bob at pendleton.com
Mon Sep 9 08:32:01 PDT 2002
Tim Allen wrote:
> 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?
> You only need eight digital inputs to play Tetris (up, down, left,
> right, spin-left, spin-right, start, and select) which I have in an
> enum. My first attempt at keybinding was to have an array of keysyms
> (int keysyms), but that meant scanning the array every time I got a
> keypress, which meant repeated code in every key-related or
> joystick-related event.
> My next attempt was just for the joystick-button binding - I made an
> array as big as the number of buttons on the first joystick, and put one
> of the Tetris keycodes into the entry for each button that was bound.
> That worked, made a lot of code shorter and easier to read, but there's
> something like 350+ different keysyms that you can get events for, which
> seems a little large just for keybinding.
> 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 isn't all that complex. I've written several applications that had
rebindable keys. I used a simple vector of function pointers indexed by
keysym. Most of the entries vector in the vector point to a do nothing
routine so that invalid keys are dropped quickly and without any special
case code. The entries for bound keys point to the function that does
the operation you want. This approach also lets you have multiple
bindings for actions, i.e. more than one key can perform the same action.
When you are handling multiple key sequences just have multiple tables.
The first key selects the second table, and so on until you hit an
action routine that resets the table index and performs your action or
an ignore function that just resets to the first table.
You will want to use separate tables for keysyms and events just so you
can be absolutely sure not to confuse a keysym for an event and vice versa.
+ Bob Pendleton, consultant for hire +
+ Resume: http://www.jump.net/~bobp +
+ Email: bob at pendleton.com +
More information about the SDL