# Online arena

> nacatamalon/net in real time: two players move with their keys and zap each other. Each page moves its own fighter at once and takes the server's word when it comes; the server decides each zap where the zapper saw the other.

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

Ana moves with **WASD** and zaps with **F**; Luis with the **arrows** and **Enter**. Each half of the page is one of them.

`nacatamalon/net` is experimental: it can change from one version to the next.

The line is 80 ms each way, and still each player's own fighter moves the moment a key is pressed. Its `useShared` has an `owner` and a `move`: the server moves it with what that player presses, and their page runs the same `move` at once, ahead of the server; when the server's word comes it starts again from there and runs once more the steps the server had not seen. The other fighter glides a moment behind.

The server reads each player's keys by name with `useNet().actions(player)`, whatever keys they are on that player's machine. A zap is decided with `useNet().rewind(player, fn)`: every shared object is put back where that player saw it when they pressed, so a hit on their screen is a hit.

## Code

`index.ts`:

```ts
import { createServer } from 'nacatamalon/net';

import { startPlayer } from './host/start';
import { openServer } from './net/line';
import { arenaScene } from './scenes/arena';
import { actionsFor, NET, PLAYERS, SCREEN } from './settings';

// The server: the same scene, run with no screen, deciding every move and every zap. In a real game
// it is `bun server.ts` on a machine of its own, and `server.listen(8080)`.
const server = createServer({
    width: SCREEN.width,
    height: SCREEN.height,
    scenes: {
        Arena: arenaScene(null)
    },
    step: NET.step,
    // The same action names the players have; which keys they are is each player's own business.
    actions: actionsFor(PLAYERS[0]!.keys),
    // Each page sends its name as its token, and goes by it in the room.
    admit: ({ token }) => token ?? false
});

openServer(server);

// Two players, each one a game of its own, in the same arena.
const root = document.querySelector<HTMLElement>('#app')!;

root.style.cssText = 'display:grid;grid-template-columns:1fr 1fr;gap:8px';

for (const player of PLAYERS) {
    startPlayer(root, player);
}
```

`components/fighter.ts`:

```ts
import { createShapes, createText, useTransform, useUpdate } from 'nacatamalon';
import { useShared } from 'nacatamalon/net';

import { ARENA, FIGHTER } from '../settings';

const COLORS = ['#ff6b1a', '#3fa7ff', '#7bd66b', '#d66bd0'];

const colorOf = (name: string) => COLORS[[...name].reduce((sum, letter) => sum + letter.charCodeAt(0), 0) % COLORS.length]!;

const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));

// One player's fighter. The server makes it and moves it with what the player presses; the
// player's own page moves it too, at once, with this same `move`, so it answers the keys with no
// wait. The other page shows it gliding, a moment behind.
export const Fighter = (name: string, x: number, y: number) => {
    const place = useTransform({ x, y });

    const shared = useShared({
        owner: name,
        fields: { score: 0, zaps: 0 },
        // Only the movement: the same on the server and, ahead of it, in the player's page.
        move: (input, dt) => {
            const { x: dx, y: dy } = input.direction('left', 'right', 'up', 'down');

            place.x = clamp(place.x + dx * FIGHTER.speed * dt, ARENA.left + FIGHTER.radius, ARENA.right - FIGHTER.radius);
            place.y = clamp(place.y + dy * FIGHTER.speed * dt, ARENA.top + FIGHTER.radius, ARENA.bottom - FIGHTER.radius);
        }
    });

    const ring = createShapes({
        shapes: [{ type: 'circle', x: 0, y: 0, radius: FIGHTER.reach, stroke: { width: 1, color: '#ffe08a' } }],
        visible: false
    });

    createShapes({
        shapes: [{ type: 'circle', x: 0, y: 0, radius: FIGHTER.radius, fill: colorOf(name) }]
    });

    const label = createText({
        text: name,
        anchor: { x: 0.5, y: 1 },
        transform: { y: -FIGHTER.radius - 2 }
    });

    // A zap shows as a ring for a moment: every page sees the count go up.
    let seenZaps = 0;
    let ringUntil = 0;

    useUpdate((_delta, time) => {
        label.text = `${name} ${shared.fields.score}`;

        if (shared.fields.zaps !== seenZaps) {
            seenZaps = shared.fields.zaps;
            ringUntil = time + FIGHTER.flash;
        }

        ring.visible = time < ringUntil;
    });

    return shared;
};
```

`components/floor.ts`:

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

import { ARENA } from '../settings';

// The arena's floor and its edge.
export const Floor = () => {
    createShapes({
        shapes: [
            {
                type: 'rect',
                x: ARENA.left,
                y: ARENA.top,
                width: ARENA.right - ARENA.left,
                height: ARENA.bottom - ARENA.top,
                fill: '#1d2638',
                stroke: { width: 1, color: '#3a4a6a' }
            }
        ]
    });
};
```

`components/hud.ts`:

```ts
import { createText, useUpdate } from 'nacatamalon';
import { useNet } from 'nacatamalon/net';

import { lineToServer } from '../net/line';
import { ARENA, SCREEN } from '../settings';

// A player's side: connect, and say how it is going. The keys need nothing here: a page that moves
// a fighter of its own sends what it presses on its own, every step.
export const Hud = ({ name, help }: { name: string; help: string }) => {
    const net = useNet();

    const status = createText({
        text: 'connecting…',
        transform: { x: 4, y: 4 }
    });

    createText({
        text: help,
        tint: '#8a93a6',
        transform: { x: 4, y: SCREEN.height - 10 }
    });

    net.connect(lineToServer(), { room: ARENA.name, token: name });

    net.onDisconnect((reason) => {
        status.text = `out: ${reason}`;
    });

    useUpdate(() => {
        if (net.status !== 'online') {
            return;
        }

        const ping = net.ping === null ? '…' : `${Math.round(net.ping * 1000)} ms`;

        status.text = `${net.me} · ping ${ping}`;
    });
};
```

`components/rules.ts`:

```ts
import { destroy, useUpdate } from 'nacatamalon';
import { useNet, useNetSpawn } from 'nacatamalon/net';
import type { TGameObject } from 'nacatamalon';

import { Fighter } from './fighter';
import { ARENA, FIGHTER } from '../settings';

type TFighter = TGameObject & { api: ReturnType<typeof Fighter> };

// Places to start from, taken in turn.
const STARTS = [
    { x: ARENA.left + 30, y: ARENA.top + 30 },
    { x: ARENA.right - 30, y: ARENA.bottom - 30 },
    { x: ARENA.right - 30, y: ARENA.top + 30 },
    { x: ARENA.left + 30, y: ARENA.bottom - 30 }
];

// The fighters, on both sides: both ask for the spawner by the same name, and only the server uses
// it. The server also decides every zap: from what each player pressed, never from what a page says
// it hit.
export const Rules = () => {
    const net = useNet();
    const spawnFighter = useNetSpawn('fighter', Fighter);

    if (net.role !== 'server') {
        return;
    }

    const fighters = new Map<string, TFighter>();
    let starts = 0;

    const nextStart = () => STARTS[starts++ % STARTS.length]!;

    net.onJoin((player) => {
        const at = nextStart();

        fighters.set(player, spawnFighter(player, at.x, at.y) as TFighter);
    });

    net.onLeave((player) => {
        const fighter = fighters.get(player);

        if (fighter !== undefined) {
            destroy(fighter);
            fighters.delete(player);
        }
    });

    useUpdate(() => {
        for (const [player, fighter] of fighters) {
            if (!net.actions(player).justPressed('zap')) {
                continue;
            }

            fighter.api.fields.zaps += 1;

            // Where everyone was on the zapper's screen when they pressed, not where they are now:
            // the press took a while to get here, and the others moved on meanwhile.
            const hit = net.rewind(player, () => {
                const me = fighter.transform!;

                return [...fighters].filter(([other, them]) => other !== player
                    && Math.hypot(them.transform!.x - me.x, them.transform!.y - me.y) <= FIGHTER.reach + FIGHTER.radius);
            });

            for (const [, them] of hit) {
                fighter.api.fields.score += 1;

                // Back to a corner: the hit player's page takes the server's word for it.
                const at = nextStart();

                them.transform!.x = at.x;
                them.transform!.y = at.y;
            }
        }
    });
};
```

`host/start.ts`:

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

import { arenaScene } from '../scenes/arena';
import { actionsFor, PLAYERS, SCREEN } from '../settings';

// One player's page: a game of its own, side by side with the other on this page, with its own keys.
export const startPlayer = (root: HTMLElement, player: (typeof PLAYERS)[number]) => {
    const host = document.createElement('div');

    host.style.cssText = 'min-width:0';
    root.appendChild(host);

    const game = createGame(host, {
        width: SCREEN.width,
        height: SCREEN.height,
        background: '#121826',
        step: 60,
        actions: actionsFor(player.keys)
    });

    // Declare Scenes
    game({
        Arena: arenaScene(player)
    });
};
```

`net/line.ts`:

```ts
import { connectLoopback } from 'nacatamalon/net';
import type { TNetConnection, TServer } from 'nacatamalon/net';

import { NET } from '../settings';

let server: TServer | null = null;

// The server lives in this same page, so the players reach it through a line in memory.
export const openServer = (running: TServer) => {
    server = running;
};

// The one line that changes in a real game: it returns the server's address, 'wss://…', instead.
export const lineToServer = (): TNetConnection => {
    if (server === null) {
        throw new Error('Open the server before the players connect.');
    }

    return connectLoopback(server, { delay: NET.delay });
};
```

`scenes/arena.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { useNet } from 'nacatamalon/net';
import type { TSceneFn } from 'nacatamalon';

import { Floor } from '../components/floor';
import { Hud } from '../components/hud';
import { Rules } from '../components/rules';

// The one scene of the game, run by the server's room and by each player's page. `player` is who a
// page plays as, and `null` in the room.
export const arenaScene = (player: { name: string; help: string } | null): TSceneFn => () => {
    const net = useNet();

    useSpawn(Floor)();
    useSpawn(Rules)();

    if (net.role === 'client' && player !== null) {
        useSpawn(Hud)(player);
    }

    return createScene();
};
```

`settings.ts`:

```ts
import type { TActionMap } from 'nacatamalon';

export const SCREEN = {
    width: 240,
    height: 160
};

// The floor the fighters move on, in the game's pixels.
export const ARENA = {
    name: 'arena',
    left: 8,
    top: 24,
    right: 232,
    bottom: 148
};

export const NET = {
    // A game of quick reactions: the room runs 60 steps a second, as each player's game does.
    step: 60,
    // Seconds each message takes, each way: 160 ms there and back, a player far from the server.
    delay: 0.08
};

export const FIGHTER = {
    speed: 70,
    radius: 6,
    // How far a zap reaches.
    reach: 24,
    // How long the ring of a zap shows, in seconds.
    flash: 0.15
};

type TKeys = { left: string; right: string; up: string; down: string; zap: string };

// Both players share this page and its keyboard, so each gets keys of their own. In a real game
// every player is on their own machine and they all use the same.
export const PLAYERS: Array<{ name: string; keys: TKeys; help: string }> = [
    { name: 'Ana', keys: { left: 'a', right: 'd', up: 'w', down: 's', zap: 'f' }, help: 'WASD to move · F to zap' },
    { name: 'Luis', keys: { left: 'ArrowLeft', right: 'ArrowRight', up: 'ArrowUp', down: 'ArrowDown', zap: 'Enter' }, help: 'arrows to move · Enter to zap' }
];

// The actions, by name. The server reads them by name too, whatever key each player pressed.
export const actionsFor = (keys: TKeys): TActionMap =>
    (Object.keys(keys) as Array<keyof TKeys>).map((name) => ({
        name,
        bindings: [{ type: 'key', key: keys[name] }]
    }));
```
