# Input map

> Named actions bound to keys, pad buttons and stick directions at once, declared in project.json, with a controls screen to rebind them.

Example `input-map`, running at https://nacatamalon.com/en/examples/input-map. The whole catalogue: https://nacatamalon.com/llms/examples.md.

Named actions, so the game asks about `'move_left'` and never about a key or a button. The same four names cover WASD, the d-pad and the stick with no branching, and `useDirection` turns them into a direction with a round dead zone, which is what keeps a gentle diagonal from snapping to a straight line.

The map lives in `project.json`, beside the window size, and `gameOptionsFromProject` is the one place it becomes a running game. **Click a row and press a key or a pad button** to rebind it; the change is kept, so it is still there after a reload. Open the other tab to see the file.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { parseProject, gameOptionsFromProject } from 'nacatamalon/files';
import { project } from './settings';
import { Level } from './scenes/demo';

// One translation from project data to game options, as in an editor's play button.
const settings = parseProject(project);

const game = createGame('#app', gameOptionsFromProject(settings));

// Declare Scenes
game({
    Level
}, settings.mainScene || undefined);
```

`components/binding_row.ts`:

```ts
import { createText, createSprite, getColor, listen, useInputMap, useUpdate, type TBitmapFont } from 'nacatamalon';
import { labelOf } from '../helpers/label_of';

export const BindingRow = ({ action, index, font }: { action: string; index: number; font: TBitmapFont }) => {
    const map = useInputMap();
    const y = 170 + index * 22;

    createText({
        text: action.toUpperCase().replace('_', ' '),
        font,
        style: {
            fontSize: 8
        },
        tint: '#e8eef5',
        transform: {
            x: 40,
            y: y
        }
    });

    const bound = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: '#f5c518',
        transform: {
            x: 150,
            y: y
        }
    });

    const row = createSprite({
        anchor: {
            x: 0,
            y: 0
        },
        width: 420,
        height: 18,
        tint: 'rgba(255,255,255,0.05)',
        transform: {
            x: 30,
            y: y - 5
        }
    });

    let waiting = false;

    listen(row, {
        onPointerOver: () => {
            row.tint = getColor('rgba(255,255,255,0.14)');
        },
        onPointerOut: () => {
            row.tint = getColor('rgba(255,255,255,0.05)');
        },
        onClick: () => {
            if (waiting) {
                return;
            }

            waiting = true;
            bound.text = 'PRESS SOMETHING...';
            // capture waits for the first thing the player does. The button that opened this
            // was still held when it started, so a button only counts once it goes down having
            // been up since the wait began, and a stick has to come back to the middle first.
            map.capture((binding) => {
                waiting = false;

                if (binding === null) {
                    return;
                }                       // they pressed Escape

                if (map.conflicts(binding, action).length > 0) {
                    bound.text = 'ALREADY USED';

                    return;
                }

                map.bind(action, binding, 0);                       // saved by itself
            });
        },
    });

    let elapsed = 0;

    useUpdate((delta) => {
        elapsed += delta;

        if (elapsed <= 0.2) {
            return;
        }

        elapsed = 0;

        if (waiting) {
            return;
        }

        bound.text = map.bindings(action).map(labelOf).join('   ');
    });
};
```

`components/controls.ts`:

```ts
import { createText, createSprite, listen, useInputMap, useLoadBitmapFont, useSpawn } from 'nacatamalon';
import { ARCADE, project } from '../settings';
import { BindingRow } from './binding_row';

export const Controls = () => {
    const font = useLoadBitmapFont(ARCADE);
    const map = useInputMap();

    createText({
        text: 'MOVE WITH WASD, THE D-PAD OR THE STICK',
        font,
        style: {
            fontSize: 8
        },
        tint: '#5b7290',
        anchor: {
            x: 0.5,
            y: 0
        },
        transform: {
            x: project.width / 2,
            y: 16
        }
    });

    const row = useSpawn(BindingRow);

    map.list().forEach((action, index) => {
        row({
            action,
            index,
            font
        });
    });
    createText({
        text: 'CLICK A ROW AND PRESS A KEY OR A BUTTON   ESC CANCELS',
        font,
        style: {
            fontSize: 8
        },
        tint: '#5b7290',
        anchor: {
            x: 0.5,
            y: 0
        },
        transform: {
            x: project.width / 2,
            y: 282
        }
    });
    createText({
        text: 'RESET',
        font,
        style: {
            fontSize: 8
        },
        tint: '#5b7290',
        transform: {
            x: 400,
            y: 148
        }
    });

    const resetBox = createSprite({
        anchor: {
            x: 0,
            y: 0
        },
        width: 60,
        height: 16,
        tint: 'rgba(255,255,255,0.05)',
        transform: {
            x: 394,
            y: 144
        }
    });

    listen(resetBox, {
        onClick: () => map.reset()
    });
};
```

`components/hero.ts`:

```ts
import { createSprite, useActions, useDirection, useUpdate } from 'nacatamalon';
import { clamp } from 'nacatamalon/math';
import { HERO, project, GREEN, YELLOW } from '../settings';

export const Hero = () => {
    const input = useActions();
    // A single direction covers keys, d-pad and stick, with a round dead zone.
    const move = useDirection('move_left', 'move_right', 'move_up', 'move_down');

    const hero = createSprite({
        tint: '#4cff91',
        width: 26,
        height: 26,
        transform: {
            x: project.width / 2,
            y: 90
        }
    });

    useUpdate((delta) => {
        const { x, y } = move();
        const speed = input.isDown('dash') ? HERO.dashSpeed : HERO.speed;

        hero.transform.x = clamp(hero.transform.x + x * speed * delta, 20, project.width - 20);
        hero.transform.y = clamp(hero.transform.y + y * speed * delta, 40, 120);
        hero.tint = input.isDown('dash') ? YELLOW : GREEN;
    });
};
```

`helpers/label_of.ts`:

```ts
import { gamepadAxisDirectionLabel, INPUT, type TActionBinding } from 'nacatamalon';

export const labelOf = (binding: TActionBinding | undefined) => {
    if (binding === undefined) {
        return '---';
    }

    if (binding.type === 'key') {
        return binding.key === ' ' ? 'SPACE' : binding.key.toUpperCase();
    }

    if (binding.type === 'button') {
        return 'PAD ' + INPUT.GAMEPAD_BUTTON_LABELS[binding.button];
    }

    if (binding.type === 'touch') {
        return 'TOUCH ' + binding.box.toUpperCase();
    }

    if (binding.type === 'mouse') {
        return 'MOUSE ' + binding.button.toUpperCase();
    }

    return gamepadAxisDirectionLabel(binding.axis, binding.dir);
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { Hero } from '../components/hero';
import { Controls } from '../components/controls';

export const Level = () => {
    useSpawn(Hero)();
    useSpawn(Controls)();

    return createScene();
};
```

`settings.ts`:

```ts
import { getColor } from 'nacatamalon';
import type { TProjectSettings } from 'nacatamalon/files';

export const project = {
    format: 'nacatamalon-project',
    version: 1,
    name: 'Input Map Demo',
    width: 480,
    height: 300,
    background: {
        r: 0.05,
        g: 0.06,
        b: 0.09,
        a: 1
    },
    smooth: false,
    msaa: 1,
    mainScene: 'Level',

    // Named actions. Each one listens to a key, a pad button and a stick direction at once, so the
    // game asks about the NAME and never about the device.
    //
    // A stick is four actions and not one two-dimensional binding: if a binding could be 2D, every
    // action would be either a number or a direction, and that split would spread into the saved
    // file, the editor's table and this very screen.
    actions: [
        {
            name: 'move_left',
            bindings: [
                {
                    type: 'key',
                    key: 'a'
                },
                {
                    type: 'button',
                    button: 'left'
                },
                {
                    type: 'axis',
                    axis: 'leftX',
                    dir: -1
                }
            ]
        },
        {
            name: 'move_right',
            bindings: [
                {
                    type: 'key',
                    key: 'd'
                },
                {
                    type: 'button',
                    button: 'right'
                },
                {
                    type: 'axis',
                    axis: 'leftX',
                    dir: 1
                }
            ]
        },
        {
            name: 'move_up',
            bindings: [
                {
                    type: 'key',
                    key: 'w'
                },
                {
                    type: 'button',
                    button: 'up'
                },
                {
                    type: 'axis',
                    axis: 'leftY',
                    dir: -1
                }
            ]
        },
        {
            name: 'move_down',
            bindings: [
                {
                    type: 'key',
                    key: 's'
                },
                {
                    type: 'button',
                    button: 'down'
                },
                {
                    type: 'axis',
                    axis: 'leftY',
                    dir: 1
                }
            ]
        },
        {
            name: 'dash',
            bindings: [
                {
                    type: 'key',
                    key: ' '
                },
                {
                    type: 'button',
                    button: 'a'
                }
            ]
        },
    ],

    // The player's own changes are kept, so they are still there next time. Off by default in the
    // engine: writing to somebody's browser storage unasked is not something a game should start
    // doing because the engine gained a feature.
    actionsPersist: 'localStorage',
} satisfies Partial<TProjectSettings>;
export const ARCADE = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};
export const HERO = {
    speed: 120,
    dashSpeed: 320
};

export const GREEN = getColor('#4cff91');
export const YELLOW = getColor('#f5c518');
```
