# Games and testing

> Write portable games against the GameSDK contract, run them with createGameHost, and unit-test them without a controller.

Source: https://gamepadly.com/sdk/guides/games-and-testing

`@gamepadly/sdk/game` defines a small contract between a game and the page that hosts it. Games written against
it run in any host, and tests can swap the host for a mock controller.

## Write a game

```ts
import { defineGame } from '@gamepadly/sdk/game';
import { createCanvasStage, createGameLoop } from '@gamepadly/sdk/loop';

export default defineGame({
  manifest: { id: 'my-game', maxPlayers: 1 },
  mount(container, sdk) {
    const stage = createCanvasStage(container);
    const actions = sdk.createActions({ actions: { fire: ['r2', 'Space'] } });

    const loop = createGameLoop({
      fixedStep: 1 / 60,
      onUpdate(_dt, now) {
        actions.update(sdk.input.getState(), now);
        if (actions.justPressed('fire')) sdk.haptics.playPreset('recoil');
      },
      onRender() {
        stage.ctx.clearRect(0, 0, stage.width, stage.height);
      },
    });
    loop.start();

    return {
      unmount() {
        loop.dispose();
        stage.dispose();
      },
    };
  },
});
```

`sdk` exposes the active player's `input`, `haptics`, `triggers`, `audio`, and `lightbar`, plus
`players.get(n)` for local multiplayer, `createActions()`, `createMicBlowSensor()`, `storage` for best scores, and
`locale`. Action maps and sensors created through `sdk` are disposed with the game.

## Host it

```ts
import { createGameHost } from '@gamepadly/sdk/game';
import game from './my-game';

const host = createGameHost({ gameId: 'my-game', locale: 'en' });
const instance = await game.mount(container, host.sdk);

connectButton.onclick = () => host.hub.connectWebHID();

// later
instance.unmount();
host.dispose();
```

By default the host mutes controller input and output while the tab is hidden or unfocused, and coordinates with
other tabs of the same site so only one game drives the controller (`pauseWhenUnfocused`, `tabChannelName`).

## Test without hardware

```ts
import { describe, expect, it } from 'vitest';
import { createMockGameSDK } from '@gamepadly/sdk/game';
import game from './my-game';

describe('my-game', () => {
  it('fires with R2 and plays voice-coil haptics on a DualSense', async () => {
    const sdk = createMockGameSDK({ gameId: 'my-game', locale: 'en', players: [{ brand: 'sony' }] });
    const instance = await game.mount(document.createElement('div'), sdk);

    sdk.mockPlayers[0].state.r2 = 1; // press R2
    expect(sdk.haptics.playPreset('recoil')).toBe('4ch_vcm');

    instance.unmount();
  });
});
```

`mockPlayers[n].state` is the mutable input snapshot that `input.getState()` returns. Set sticks, triggers, and
`buttons` directly. Each mock brand reports realistic capabilities and haptic routes: `'sony'` routes to
`'4ch_vcm'`, `'nintendo'` to `'hd_rumble'`, `'xbox'` to `'impulse_triggers'`, and `'generic'` to `'dual_rumble'`.
Pass `tier` to test a narrower setup, such as `'dualsense_hid_only'`, or `players: []` for keyboard only.

Run tests in a DOM environment such as `jsdom` or `happy-dom`.

## The loop helpers

| Helper | Purpose |
| :--- | :--- |
| `createGameLoop({ fixedStep, onUpdate, onRender })` | Fixed-step updates independent of display refresh rate, clamped frame deltas, pauses while the tab is hidden, and `step(now)` for deterministic tests |
| `createCanvasStage(container, options)` | A canvas that fills its container, tracks size changes, and caps device pixel ratio |
| `createDisposables()` | Collects listeners, timers, and cleanups and releases them in reverse order |
