# Online lobby

> nacatamalon/net: a room on a server and two players, all in this page. The same scene runs in the server's room, which decides, and in each player's game, which asks: click a tile to walk, a word to speak.

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

**Click** a tile to walk there, and a word to say it. Each half of the page is a player: Ana and Luis.

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

The same scene runs in three places. In the server's room, made by `createServer`, with no screen and no sound, it decides what happens; in each player's game it shows it and asks. `useNet()` is the network as the scene sees it, the same on both sides, and its `role` says which side the scene is on, so only the part that belongs there is made.

The avatars are shared objects: `useNetSpawn` makes one in every game when the server makes it, and `useShared` keeps where it is in step. The server walks them, and every page sees them gliding a moment behind. A player sends the number of a phrase and the server says the words to everyone.

In a real game the server is `bun server.ts` on a machine of its own with `server.listen(8080)`. Here the line between them is in memory (`connectLoopback`), 80 ms each way, so the lateness is there to see.

## Code

`index.ts`:

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

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

// The server: the same scene, run with no screen, deciding what happens. 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: {
        Lobby: lobbyScene(null)
    },
    step: NET.step,
    // 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 room.
const root = document.querySelector<HTMLElement>('#app')!;

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

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

`components/avatar.ts`:

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

import { tileCenter } from './floor';
import { AVATAR, ROOM } from '../settings';

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

// The same colour for a name on every screen, with nothing sent.
const colorOf = (name: string) => COLORS[[...name].reduce((sum, letter) => sum + letter.charCodeAt(0), 0) % COLORS.length]!;

// One person in the room. The server makes it, and every player's page makes it too, with the same
// name: the server walks it, and where it is and what it says travel on their own.
export const Avatar = (name: string) => {
    const net = useNet();
    const door = tileCenter(ROOM.door.column, ROOM.door.row);
    const place = useTransform(door);
    const target = { ...door };
    let bubbleUntil = 0;
    let now = 0;

    const shared = useShared({
        owner: name,
        fields: { says: '' }
    });

    createShapes({
        shapes: [
            { type: 'ellipse', x: 0, y: 0, radiusX: 6, radiusY: 2, fill: '#00000066' },
            { type: 'rect', x: -4, y: -12, width: 8, height: 11, radius: 2, fill: colorOf(name) },
            { type: 'circle', x: 0, y: -15, radius: 4, fill: '#f2c9a0' }
        ]
    });
    createText({
        text: name,
        anchor: { x: 0.5, y: 1 },
        transform: { y: -21 }
    });

    const bubble = createText({
        text: '',
        tint: '#ffe08a',
        anchor: { x: 0.5, y: 1 },
        transform: { y: -30 }
    });

    useUpdate((delta, time) => {
        now = time;

        // Every page shows what the server says; only the server walks and stops talking.
        bubble.text = shared.fields.says;

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

        const dx = target.x - place.x;
        const dy = target.y - place.y;
        const distance = Math.hypot(dx, dy);
        const step = AVATAR.speed * delta;

        if (distance <= step) {
            place.x = target.x;
            place.y = target.y;
        } else {
            place.x += (dx / distance) * step;
            place.y += (dy / distance) * step;
        }

        if (shared.fields.says !== '' && time > bubbleUntil) {
            shared.fields.says = '';
        }
    });

    // What the server's rules do with it.
    return {
        walkTo: (x: number, y: number) => {
            target.x = x;
            target.y = y;
        },
        say: (text: string) => {
            shared.fields.says = text;
            bubbleUntil = now + AVATAR.bubbleSeconds;
        }
    };
};
```

`components/controls.ts`:

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

import { floorTileAt } from './floor';
import { lineToServer } from '../net/line';
import { NET, PHRASES, ROOM, SCREEN } from '../settings';

// A player's side: connect, and ask to walk or to speak. What the server answers is seen in the
// avatars themselves, which it shares with every page.
export const Controls = ({ name }: { name: string }) => {
    const net = useNet();
    const pointer = usePointer();

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

    createText({
        text: `click to walk · ${Math.round(NET.delay * 1000)} ms away`,
        tint: '#8a93a6',
        transform: { x: 4, y: SCREEN.height - 12 }
    });

    // What the player can say: each word is a button, and what it sends is its number.
    let left = 4;

    PHRASES.forEach((words, phrase) => {
        const button = createText({
            text: `[${words}]`,
            tint: '#ffe08a',
            transform: { x: left, y: 16 }
        });

        left += sizeOf(button).width + 6;
        listen(button, {
            onClick: () => {
                if (net.status === 'online') {
                    net.send('say', { phrase });
                }
            }
        });
    });

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

    net.onConnect(() => {
        status.text = `${net.me} in ${net.room}`;
    });

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

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

        const at = pointer.position();
        const tile = at === null ? null : floorTileAt(at.worldX, at.worldY);

        if (pointer.justPressed() && tile !== null) {
            net.send('walk', tile);
        }
    });
};
```

`components/floor.ts`:

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

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

// A checkered floor, and the door players come in by.
export const Floor = () => {
    const tiles = [];

    for (let row = 0; row < ROOM.rows; row++) {
        for (let column = 0; column < ROOM.columns; column++) {
            const isDoor = column === ROOM.door.column && row === ROOM.door.row;

            tiles.push({
                type: 'rect' as const,
                x: ROOM.left + column * ROOM.tile,
                y: ROOM.top + row * ROOM.tile,
                width: ROOM.tile,
                height: ROOM.tile,
                fill: isDoor ? '#6b4f2a' : (column + row) % 2 === 0 ? '#2b3a55' : '#24304a'
            });
        }
    }

    createShapes({ shapes: tiles });
};

// The middle of a tile, in the game's pixels.
export const tileCenter = (column: number, row: number) => ({
    x: ROOM.left + (column + 0.5) * ROOM.tile,
    y: ROOM.top + (row + 0.5) * ROOM.tile
});

// The tile under a point of the screen, or null outside the floor.
export const floorTileAt = (x: number, y: number) => {
    const column = Math.floor((x - ROOM.left) / ROOM.tile);
    const row = Math.floor((y - ROOM.top) / ROOM.tile);

    if (column < 0 || row < 0 || column >= ROOM.columns || row >= ROOM.rows) {
        return null;
    }

    return { column, row };
};
```

`components/people.ts`:

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

import { Avatar } from './avatar';

type TAvatar = TGameObject & { api: ReturnType<typeof Avatar> };

// Everyone in the room. Both sides ask for the spawner, by the same name; only the server uses it,
// making an avatar for each player who joins and ending it when they leave. Every page, including
// those of the players who come later, gets the same avatars without a word of code here.
export const People = () => {
    const net = useNet();
    const spawnAvatar = useNetSpawn('avatar', Avatar);
    const avatars = new Map<string, TAvatar>();

    if (net.role === 'server') {
        net.onJoin((player) => {
            avatars.set(player, spawnAvatar(player) as TAvatar);
        });

        net.onLeave((player) => {
            const avatar = avatars.get(player);

            if (avatar !== undefined) {
                destroy(avatar);
                avatars.delete(player);
            }
        });
    }

    return {
        of: (player: string) => avatars.get(player)?.api
    };
};
```

`components/rules.ts`:

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

import { floorTileAt, tileCenter } from './floor';
import type { People } from './people';
import { PHRASES } from '../settings';

type TWalk = { column: number; row: number };
type TSay = { phrase: number };

// What only the server decides: whether a step or a word is allowed. A player's page sends what the
// player did; it never says where anyone ends up. What the server does to an avatar reaches every
// page on its own.
export const Rules = ({ people }: { people: ReturnType<typeof People> }) => {
    const net = useNet();

    net.onMessage<TWalk>('walk', (walk, from) => {
        if (from === null || typeof walk?.column !== 'number' || typeof walk.row !== 'number') {
            return;
        }

        const to = tileCenter(Math.round(walk.column), Math.round(walk.row));

        // A tile off the floor is not a walk: a changed page cannot send anyone through the wall.
        if (floorTileAt(to.x, to.y) === null) {
            return;
        }

        people.of(from)?.walkTo(to.x, to.y);
    });

    net.onMessage<TSay>('say', (say, from) => {
        const text = PHRASES[say?.phrase];

        if (from === null || text === undefined) {
            return;
        }

        people.of(from)?.say(text);
    });
};
```

`host/start.ts`:

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

import { lobbyScene } from '../scenes/lobby';
import { SCREEN } from '../settings';

// One player's page: a game of its own, side by side with the other on this page.
export const startPlayer = (root: HTMLElement, name: string) => {
    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'
    });

    // Declare Scenes
    game({
        Lobby: lobbyScene(name)
    });
};
```

`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/lobby.ts`:

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

import { Controls } from '../components/controls';
import { Floor } from '../components/floor';
import { People } from '../components/people';
import { Rules } from '../components/rules';

// The one scene of the game. The server's room runs it, and so does each player's page: `role` says
// which, and only the part that belongs there is made. `name` is who a player's page plays as.
export const lobbyScene = (name: string | null): TSceneFn => () => {
    const net = useNet();

    useSpawn(Floor)();

    const people = useSpawn(People)().api;

    if (net.role === 'server') {
        useSpawn(Rules)({ people });
    } else {
        useSpawn(Controls)({ name: name ?? 'guest' });
    }

    return createScene();
};
```

`settings.ts`:

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

// The floor of the room, in tiles, and where it sits on the screen.
export const ROOM = {
    name: 'lobby',
    columns: 10,
    rows: 6,
    tile: 16,
    left: 40,
    top: 36,
    door: {
        column: 0,
        row: 5
    }
};

export const NET = {
    // Steps a second in the server's room: plenty for walking and chatting.
    step: 20,
    // Seconds each message takes, each way: the two players are 160 ms from the server, there and back.
    delay: 0.08
};

export const AVATAR = {
    speed: 48,
    bubbleSeconds: 2.5
};

// What the players can say. They send the number of the phrase, and the server says the words.
export const PHRASES = ['Hi!', 'Nice!', 'Bye!'];

export const PLAYERS = ['Ana', 'Luis'];
```
