# Gamepad

> A pad tester: every button, trigger and stick at once, plus rumble. Needs a controller.

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

Every button, trigger and stick at once. **You need a controller**, and the browser will not show it until you press a button on it, so "no controller" is the normal state when the page opens.

`useGamepad()` with no number follows the **first pad connected**, which is what a one player game means: the ports belong to the browser, and a pad unplugged and put back usually turns up in another one. A number is for local multiplayer, where player two has to keep meaning one particular controller. Click the box to try the rumble; on macOS it often does nothing, and `canRumble` says so.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Tester } from './scenes/demo';
import { WIDTH, HEIGHT } from './settings';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#0a0f18'
});

// Declare Scenes
game({
    Tester
});
```

`components/analog_controls.ts`:

```ts
import { createText, createSprite, useLoadBitmapFont, useUpdate, type TGamepad } from 'nacatamalon';
import { ARCADE, DIM, OFF, ON, TOP_LEFT, TRIGGER_WIDTH, STICK } from '../settings';

export const AnalogControls = ({ pad }: { pad: TGamepad }) => {
    const font = useLoadBitmapFont(ARCADE);

    // The triggers are analogue (their value, not their pressed): bars, not lamps.
    createText({
        text: 'LT',
        font,
        style: {
            fontSize: 8
        },
        tint: DIM,
        transform: {
            x: 14,
            y: 154
        }
    });
    createText({
        text: 'RT',
        font,
        style: {
            fontSize: 8
        },
        tint: DIM,
        transform: {
            x: 14,
            y: 172
        }
    });

    const triggers = ['lt', 'rt'].map((_, i) => {
        createSprite({
            anchor: TOP_LEFT,
            width: TRIGGER_WIDTH,
            height: 10,
            tint: OFF,
            transform: {
                x: 40,
                y: 154 + i * 18
            }
        });

        return createSprite({
            anchor: TOP_LEFT,
            width: 0,
            height: 10,
            tint: ON,
            transform: {
                x: 40,
                y: 154 + i * 18
            }
        });
    });

    // The sticks, as a dot inside a box.
    const sticks = [0, 1].map((i) => {
        const cx = STICK.x + i * STICK.gap;
        const cy = STICK.y;

        createSprite({
            width: 76,
            height: 76,
            tint: OFF,
            transform: {
                x: cx,
                y: cy
            }
        });

        return createSprite({
            width: 10,
            height: 10,
            tint: ON,
            transform: {
                x: cx,
                y: cy
            }
        });
    });

    useUpdate(() => {
        triggers[0].width = pad.value('lt') * TRIGGER_WIDTH;
        triggers[1].width = pad.value('rt') * TRIGGER_WIDTH;

        const left = pad.leftStick();

        sticks[0].transform.x = STICK.x + left.x * STICK.travel;
        sticks[0].transform.y = STICK.y + left.y * STICK.travel;

        const right = pad.rightStick();

        sticks[1].transform.x = STICK.x + STICK.gap + right.x * STICK.travel;
        sticks[1].transform.y = STICK.y + right.y * STICK.travel;
    });
};
```

`components/button_lamps.ts`:

```ts
import { createText, createSprite, useLoadBitmapFont, useUpdate, INPUT, type TGamepad } from 'nacatamalon';
import { ARCADE, DIM, OFF, ON, TOP_LEFT } from '../settings';

export const ButtonLamps = ({ pad }: { pad: TGamepad }) => {
    const font = useLoadBitmapFont(ARCADE);

    // The seventeen buttons, as lamps.
    const lamps = INPUT.GAMEPAD_BUTTONS.map((name, i) => {
        const x = 14 + (i % 6) * 78;
        const y = 50 + Math.floor(i / 6) * 30;

        createText({
            text: name.toUpperCase(),
            font,
            style: {
                fontSize: 8
            },
            tint: DIM,
            transform: {
                x: x + 16,
                y: y + 1
            }
        });

        return createSprite({
            anchor: TOP_LEFT,
            width: 10,
            height: 10,
            tint: OFF,
            transform: {
                x: x,
                y: y
            }
        });
    });

    useUpdate(() => {
        INPUT.GAMEPAD_BUTTONS.forEach((name, index) => {
            lamps[index].tint = pad.isDown(name) ? ON : OFF;
        });
    });
};
```

`components/rumble.ts`:

```ts
import { createSprite, createText, listen, useLoadBitmapFont, type TGamepad } from 'nacatamalon';
import { ARCADE, TOP_LEFT, OFF, WHITE } from '../settings';

export const Rumble = ({ pad }: { pad: TGamepad }) => {
    const font = useLoadBitmapFont(ARCADE);

    // Rumble is asked for by clicking, never by a pad button.
    const rumbleBox = createSprite({
        anchor: TOP_LEFT,
        width: 120,
        height: 18,
        tint: OFF,
        transform: {
            x: 14,
            y: 196
        }
    });

    const rumbleLabel = createText({
        text: 'CLICK TO RUMBLE',
        font,
        style: {
            fontSize: 8
        },
        tint: WHITE,
        transform: {
            x: 20,
            y: 201
        }
    });

    listen(rumbleBox, {
        onClick: () => {
            rumbleLabel.text = pad.canRumble ? 'RUMBLING...' : 'NO RUMBLE HERE';
            void pad.rumble({
                duration: 0.4
            }).then((played) => {
                rumbleLabel.text = played ? 'IT PLAYED' : 'NO RUMBLE HERE';
            });
        },
    });
};
```

`components/status.ts`:

```ts
import { createText, useLoadBitmapFont, useUpdate, type TGamepad } from 'nacatamalon';
import { ARCADE, WARN, DIM, WHITE } from '../settings';

export const Status = ({ pad }: { pad: TGamepad }) => {
    const font = useLoadBitmapFont(ARCADE);

    const status = createText({
        text: 'PRESS ANY BUTTON ON YOUR CONTROLLER',
        font,
        style: {
            fontSize: 8
        },
        tint: WARN,
        transform: {
            x: 14,
            y: 10
        }
    });

    const info = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: DIM,
        transform: {
            x: 14,
            y: 26
        }
    });

    let presses = 0;

    const counter = createText({
        text: 'A PRESSES 0',
        font,
        style: {
            fontSize: 8
        },
        tint: DIM,
        transform: {
            x: 150,
            y: 201
        }
    });

    useUpdate(() => {
        if (!pad.connected) {
            status.text = 'PRESS ANY BUTTON ON YOUR CONTROLLER';
            status.tint = WARN;
            info.text = '';

            return;
        }

        status.text = pad.id.slice(0, 44).toUpperCase();
        status.tint = WHITE;
        // A pad the browser did not recognise puts its buttons wherever it likes, so the names
        // mean nothing on it: that is what rawButton is for, and this is how a game finds out.
        info.text = 'PORT ' + pad.index + '   ' + (pad.mapping === 'standard' ? 'STANDARD' : 'NOT STANDARD: NAMES MEAN NOTHING')
            + '   ' + pad.buttonCount + ' BUTTONS';
        info.tint = pad.mapping === 'standard' ? DIM : WARN;

        if (pad.justPressed('a')) {
            presses += 1;
            counter.text = 'A PRESSES ' + presses;
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useGamepad, useSpawn } from 'nacatamalon';
import { Status } from '../components/status';
import { ButtonLamps } from '../components/button_lamps';
import { AnalogControls } from '../components/analog_controls';
import { Rumble } from '../components/rumble';

export const Tester = () => {
    // Follow the first connected pad: reconnecting can change its browser port.
    const pad = useGamepad();

    useSpawn(Status)({
        pad
    });
    useSpawn(ButtonLamps)({
        pad
    });
    useSpawn(AnalogControls)({
        pad
    });
    useSpawn(Rumble)({
        pad
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { getColor } from 'nacatamalon';

export const WIDTH = 480;
export const HEIGHT = 224;
export const TRIGGER_WIDTH = 160;
export const STICK = {
    x: 260,
    y: 175,
    gap: 110,
    travel: 33
};
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 OFF = getColor('#1b2735');
export const ON = getColor('#4cff91');
export const DIM = getColor('#5b7290');
export const WHITE = getColor('#e8eef5');
export const WARN = getColor('#f5c518');

export const TOP_LEFT = {
    x: 0,
    y: 0
};
```
