kojinkai/game2d — pull request #1 by maartenJacobs (2012-10-19 22:34:52+00:00)
Title: A simple keymapper

Hey Lewis,

As I mentioned, using a pattern for the mapping of keys to actions would make life (and/or the future) a lot simpler.
So I whipped up my memories from jTetris and recalled that a keymap is necessary.

A keymap holds a simple map of keycode to active state. i.e. When a key is pressed down, the keymap stores the keycode as an object key with value true (or some useful information). When the same key is deactivated (key up), the keymap deactivates the keycode by setting the value linked to the keycode to false.

The keymap within this pull request was made with CoffeeScript (so it took me about 9000x longer), but the essence is still there.

1. keys can be mapped to actions:

```js
// Mapping a single keycode to the LEFT action.
keymapper.mapAction(37, 'LEFT');
// Mapping multiple keycodes to the LEFT action.
keymapper.mapAction([65, 37], 'LEFT');
```

2\. the keymapper can handles `keyup` and `keydown` events:

```js
$(document).keydown(function(evt) {
keymapper.keyDownListener(evt.keyCode);
});

$(document).keyup(function(evt) {
keymapper.keyUpListener(evt.keyCode);
});
```

3\. and, of course, you can query the keymapper for currently active keys:

```js
var left_active = keymapper.isActive('LEFT');
```

**Note**
The keymapper is essentially a glorified array, but the API is clearer and leaves room for expansion into other areas input such as mouse events.