# Attensi Games Laboratory

> GameLab (https://gamelab.attensi.com) is Attensi's internal gallery of browser games. Attensians log in with their Attensi (Entra)
> account to play, star and comment on each other's games, and to publish their own. This guide is for the agents that
> build and publish those games: the manifest, the upload API, a GitHub Action, and the in-game API.

Everything below works without a browser. Only creating the personal access token needs a person to log in.

Games are plain browser games: an HTML entry page plus whatever scripts, styles, images, audio and
WebAssembly it loads. Upload the folder (zipped or as individual files) with a `gamelab.json`
manifest at its root. Uploading again with the same `slug` publishes a new version of the same game.

**Game jams**: anyone can run a jam, a theme and a deadline, and games enter it with one line in `gamelab.json`
(`"jam": "<jam slug>"`). Asked to enter a game in a jam, follow [Game jams](#game-jams).

## Can't reach GameLab yourself? Hand over a zip

If you are an assistant without network access to https://gamelab.attensi.com (a chat session that cannot run curl, or one
whose sandbox blocks the site), do not stop at the code. Build the complete game folder with its `gamelab.json`
exactly as described below, package it as a single **.zip** file with the manifest at its root, and give that
file to the user. Then tell them:

1. Open https://gamelab.attensi.com/upload and log in with their Attensi account.
2. Drop the zip on the page, or click **Choose a zip**.
3. To update the game later, upload a new zip with the same `slug`.

If the user would rather let a coding agent with network access do it, they can create a token at
https://gamelab.attensi.com/settings and follow the steps below.

## 1. Get a personal access token

Open https://gamelab.attensi.com/settings (log in with your Attensi account) and create a token. It is shown once and lasts until you revoke it.
Keep it in an environment variable:

```sh
export GAMELAB_TOKEN=glab_...
```

Attensi Workbench needs no token: it publishes with the person's Attensi sign-in.

## 2. Write gamelab.json

```json
{
  "name": "Star Hopper",
  "slug": "star-hopper",
  "tagline": "Hop between stars before the sun burns out",
  "description": "A longer description shown on the game's page. Plain text; blank lines start new paragraphs.",
  "entry": "index.html",
  "patchNotes": "Faster stars, and the sun now sets more slowly",
  "scoring": { "rankBy": "score", "tiebreak": "time" },
  "multiplayer": { "maxPlayers": 4 },
  "media": ["media/title.png", "media/gameplay.png", "media/trailer.mp4"],
  "achievements": [
    { "id": "first-hop", "title": "First hop", "icon": "achievements/hop.png", "goal": "Land on your first star" },
    { "id": "night-owl", "title": "Night owl", "icon": "achievements/owl.png", "subtext": "Only the sun knows",
      "goal": "Keep hopping after the sun goes out", "hideGoal": true },
    { "id": "black-hole", "title": "Event horizon", "icon": "achievements/hole.png", "goal": "Fall into the black hole", "secret": true }
  ]
}
```

| Field         | Required | Rules                                                                                   |
|---------------|----------|-----------------------------------------------------------------------------------------|
| `name`        | yes      | at most 80 characters                                                                   |
| `slug`        | no       | 2-60 of `a-z`, `0-9` and single dashes; derived from `name` when left out. Identifies the game: reuse it to update |
| `tagline`     | yes      | a quick catch phrase, at most 140 characters                                           |
| `description` | yes      | at most 5000 characters                                                                 |
| `entry`       | no       | path of the HTML page that starts the game; defaults to `index.html`                   |
| `patchNotes`  | no       | what changed in this upload, shown on the game page under "What's new"; at most 5000 characters |
| `jam`         | no       | the slug of the [game jam](#game-jams) to enter the game in, such as `"spooky-week"`; it must be running to join, and joining it leaves any other running jam. Left out, the game stays where it is; `null` takes it out of its running jam. Jams that have ended keep the game, and its trophies, for good |
| `visible`     | no       | `false` keeps the game out of the gallery (you and admins still see it). Default `true`. Once you or an admin toggle visibility on the site, that choice wins over this field |
| `scoring`     | no       | what the leaderboard records. `rankBy`: `score` (higher wins, the default) or `time` (lower wins); optional `tiebreak`: the other one, recorded too and used to break ties. Submissions may only carry the fields named here. `keep`: `best` (the default: each player's best submission ranks them) or `total` (every submission is added to the player's total: wins, kills, goals; needs `rankBy` `score` and no `tiebreak`). `counts`: what a score counts, in your own words, both ways: `{ "singular": "win", "plural": "wins" }`, each free text of 1-32 characters (the two may be the same: `"sheep"`), so the leaderboard reads "1 win" and "12 wins" instead of "12". See [Counting things](#counting-things-wins-kills-goals) |
| `multiplayer` | no       | turns on network play (`gamelab.net`, see [Network games](#network-games)). `maxPlayers`: 2-64, how many a room takes before it turns newcomers away |
| `achievements` | no      | up to 500. Each: `id` (1-64 of `a-z`, `0-9`, `-`, `_`; stable, unlocks are kept by it across updates), `title` (80), `icon` (a picture in the upload), optional `subtext` (300), `goal` (300, what to do), optional `hideGoal` (default `false`: when `true`, players see the title, icon and subtext but not the goal until they have earned it), optional `secret` (default `false`: when `true`, players see only that there is an achievement, as "Secret achievement" with a question mark, and nothing about it, not even its id, until they have earned it). The game alone decides when a goal is met. See [Achievements](#achievements) |
| `media`       | yes      | paths of 1-20 pictures/videos shown in the carousel, in order. At least one must be a picture; the first picture is the cover. Pictures: png, jpg, gif, webp, avif. Videos: mp4, webm |

All paths are relative to the manifest and use `/`. Field names are not case-sensitive, comments (`//`) and trailing
commas are fine, and a field GameLab does not know is refused with the nearest one it does ("unknown field
'multiplayers': did you mean 'multiplayer'?"), so a typo never goes unnoticed.

## 3. Upload

Zip the folder (the manifest may be at the zip's root, or inside its single top-level folder) and send it:

```sh
cd my-game && zip -r ../my-game.zip . && cd ..
curl -fsS -X POST https://gamelab.attensi.com/api/games \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -H "Content-Type: application/zip" \
  --data-binary @my-game.zip
```

Or send the files individually, each `files` field named by its path:

```sh
curl -fsS -X POST https://gamelab.attensi.com/api/games \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -F "files=@gamelab.json;filename=gamelab.json" \
  -F "files=@index.html;filename=index.html" \
  -F "files=@js/game.js;filename=js/game.js" \
  -F "files=@media/title.png;filename=media/title.png"
```

A zip in a form works too, in a `zip` field or any other but `files`: `-F "zip=@my-game.zip"` or
`-F "file=@my-game.zip"` (a file named `.zip`, or sent as `application/zip`, is unpacked).

Uploading an existing slug replaces the game's files and keeps everything players built up: favorites,
kudos, leaderboards, achievements, saves and stored data. To start over, add `?dangerousWipeAllPlayerData=true` to the
upload URL; that deletes every score, achievement, save and stored value of every player (favorites and kudos stay).
Players can also reset their own progress in a game at any time from GameLab's game menu. `?jam=<jam slug>` enters the
game in that jam whatever the manifest says, and `?jam=none` takes it out of its running jam (see [Game jams](#game-jams)).

The response is the published game as JSON (`201` for a new game, `200` for a new version). Its `version` is the
number this upload published (1 for a new game), as `/releases` and `/revisions` number them. Its `notes` list what
the upload did beyond the files, such as joining a jam: tell the user. A rejected
upload answers `400` with every problem listed in `detail`, `409` if the slug belongs to someone else's
game, `413` past the 512 MB limit, and `415` for a body it cannot read. Every `detail` says what GameLab found and
what to change: what the upload held when there is no `gamelab.json`, where a manifest that is too deep sits, a
manifest named in the wrong case, a body that is not a zip (often `curl -d`, which mangles binary files: use
`--data-binary`), a JSON error's line and column, a value of the wrong kind and what belongs there, and every
manifest problem at once. Read it, fix that, and upload again. A refused token answers `401` with why in `detail`
(revoked or mistyped, expired, missing the scope); make a new one and try again.

## Publish from GitHub Actions

To publish on every push, store a token (step 1) as the repository secret `GAMELAB_TOKEN` and add
`.github/workflows/gamelab.yml`:

```yaml
name: Publish to GameLab
on:
  push:
    branches: [main]
  workflow_dispatch:
jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      # build the game here first if it needs it, then point path at the output
      - uses: Attensi/gamelab/publish@main
        with:
          token: ${{ secrets.GAMELAB_TOKEN }}
          path: .    # the folder with gamelab.json at its root, or a .zip
```

With the GitHub CLI, the secret is `gh secret set GAMELAB_TOKEN --body "$GAMELAB_TOKEN"`. The action zips the
folder (leaving out `.git` and `node_modules`), uploads it, fails the run with every reason if GameLab refuses it,
and gives the game's page as the `url` output. `wipe-player-data: true` does what `dangerousWipeAllPlayerData`
does, and `jam: spooky-week` what `?jam=spooky-week` does. It works from any repository in the Attensi organization; anywhere else, run the curl upload above instead.

## Other calls

All take the same `Authorization: Bearer $GAMELAB_TOKEN` header.

| Call                                | Does                                    |
|-------------------------------------|-----------------------------------------|
| `GET https://gamelab.attensi.com/api/games`        | list games                              |
| `GET https://gamelab.attensi.com/api/games/<slug>` | one game, including its play URL        |
| `DELETE https://gamelab.attensi.com/api/games/<slug>` | delete a game you own (admins: any)  |
| `GET https://gamelab.attensi.com/api/games/<slug>/revisions` | the game's kept uploads (owner and admins) |
| `GET https://gamelab.attensi.com/api/games/<slug>/revisions/<version>` | one of them as a zip (owner and admins) |
| `GET https://gamelab.attensi.com/api/jams?active=true` | the game jams running now (leave out `active` for every jam) |
| `GET https://gamelab.attensi.com/api/jams/<slug>`  | one jam: its tally, your votes and, once it has ended, its results |
| `POST https://gamelab.attensi.com/api/jams`        | start a jam: `{ "title", "theme", "endsUtc" }`                |
| `PATCH https://gamelab.attensi.com/api/jams/<slug>` | rewrite a jam's `title`, `theme` or `endsUtc` (its owner and admins); a new end reopens a jam that ended under 12 hours ago |
| `POST https://gamelab.attensi.com/api/jams/<slug>/close` | end a jam now (its owner and admins) |
| `DELETE https://gamelab.attensi.com/api/jams/<slug>` | delete a jam with no games and no votes in it (its owner; admins: any) |
| `DELETE https://gamelab.attensi.com/api/jams/<slug>/games/<game>?reason=...` | take a game out of a running jam (its owner, Jam Masters and admins) |
| `PUT https://gamelab.attensi.com/api/jams/<slug>/games/<game>` | put a game into a running jam, leaving the running jam it was in (its owner, Jam Masters and admins) |
| `PUT https://gamelab.attensi.com/api/jams/<slug>/votes/<game>` | vote for a game in a running jam |
| `DELETE https://gamelab.attensi.com/api/jams/<slug>/votes/<game>` | take that vote back |
| `GET https://gamelab.attensi.com/api/guide`        | this guide                              |

## Revisions and rolling back

GameLab keeps the last 10 uploads of every game as zips, the current one included, however they were sent:
loose files are zipped too. Only the game's owner and admins can list or download them. The list is newest first:

```json
[
  { "version": 7, "patchNotes": "Faster stars", "createdUtc": "2026-10-16T09:12:00Z", "downloadUrl": "/api/games/star-hopper/revisions/7" },
  { "version": 6, "patchNotes": null, "createdUtc": "2026-10-15T14:03:00Z", "downloadUrl": "/api/games/star-hopper/revisions/6" }
]
```

Each zip has `gamelab.json` at its root, exactly as that version was published. To roll back, download the one you
want and upload it again; it becomes a new version, and players keep their progress as with any update:

```sh
curl -fsS -H "Authorization: Bearer $GAMELAB_TOKEN" -o star-hopper-v6.zip https://gamelab.attensi.com/api/games/star-hopper/revisions/6
curl -fsS -X POST https://gamelab.attensi.com/api/games \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -H "Content-Type: application/zip" \
  --data-binary @star-hopper-v6.zip
```

The rolled-back version carries that zip's `patchNotes`; edit them in its `gamelab.json` first to say it is a
rollback. A version no longer kept answers `404`. Deleting a game deletes its revisions with it.

## Game jams

A game jam is a theme and a deadline that anyone at Attensi can set. People enter games until it ends, and everyone
has 3 votes in it, at most one per game and never for their own. When it ends, voting stops and the three games with
the most votes take gold, silver and bronze, for good: a trophy on each game's page. A game can enter one jam after
another, and keeps every trophy it wins.

A jam is named by its **slug**, such as `spooky-week`. Games enter a jam through their uploads. Admins appoint Jam
Masters, who move anyone's games in and out of running jams.

### Enter a game in a jam

1. **Find the jam.** List the jams running now:

   ```sh
   curl -fsS -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/jams?active=true"
   ```

   ```json
   [
     {
       "slug": "spooky-week",
       "title": "Spooky Week",
       "theme": "Something that goes bump in the night",
       "ownerId": "6f1c2d3e-0000-4000-8000-000000000001",
       "owner": "Kari Nordmann",
       "ownerPictureUrl": null,
       "createdUtc": "2026-10-24T09:00:00Z",
       "endsUtc": "2026-10-31T18:00:00Z",
       "closedEarly": false,
       "isActive": true,
       "games": 4,
       "tally": { "voters": 9, "votes": 21 },
       "myVotes": [],
       "votesLeft": 3,
       "canManage": false,
       "canMoveGames": false,
       "canDelete": false,
       "results": null
     }
   ]
   ```

2. **Pick the jam the user named**, by its `title` or `slug`. If more than one could be it, or none is, ask the user
   which they mean, and show them the list. Never guess, and never choose a jam for them.
3. **Tell the user how long is left.** `endsUtc` is UTC: say when that is in the user's own time zone, and warn
   them if it is under an hour away. A game uploaded after the end cannot join.
4. **Name the jam in `gamelab.json`**, next to the other fields:

   ```json
   {
     "name": "Star Hopper",
     "slug": "star-hopper",
     "tagline": "Hop between stars before the sun burns out",
     "description": "A game about stars, for Spooky Week.",
     "media": ["media/title.png"],
     "jam": "spooky-week"
   }
   ```

5. **Upload as usual** ([3. Upload](#3-upload)). The response's `notes` say the game joined:
   `"notes": ["joined Spooky Week, which ends 2026-10-31 18:00 UTC"]`. Tell the user.
6. **Check it worked.** The game's `jam` says where it is:

   ```sh
   curl -fsS -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/games/star-hopper"
   ```

   ```json
   { "slug": "star-hopper", "jam": { "slug": "spooky-week", "title": "Spooky Week", "endsUtc": "2026-10-31T18:00:00Z", "myVote": false }, "trophies": [] }
   ```

   `jam` is the running jam the game is in, `null` for none. `trophies` lists what it won in jams that have ended,
   newest first: `[{ "slug": "summer-jam", "title": "Summer Jam", "endsUtc": "2026-09-01T12:00:00Z", "place": 1 }]`, where
   `place` 1, 2 and 3 are gold, silver and bronze.

### Enter without touching the manifest

The upload itself can name the jam, which wins over whatever `gamelab.json` says (the people's upload page does this):

```sh
curl -fsS -X POST "https://gamelab.attensi.com/api/games?jam=spooky-week" \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -H "Content-Type: application/zip" \
  --data-binary @my-game.zip
```

`?jam=none` takes the game out of its running jam. From GitHub Actions, give the action `jam: spooky-week`.

### Move to another jam, or leave

A game is in one running jam at most. Naming another running jam moves it there; `"jam": null` (or `?jam=none`) takes
it out. Leaving a running jam hands the game's votes back to its voters. Jams that have ended are never left: the game
stays in them, with whatever trophies it won, whatever jam it enters next and whatever its manifest says.

### Updating a game during or after a jam

Update it as often as you like, during the jam and after. Keep `"jam"` as it is, or leave the field out: either way
the game stays in its jam, even once the jam has ended. Updates never touch its votes or results.

A running jam holds no hidden games. Hiding the game while the jam runs (`"visible": false`, or the toggle on the site)
takes it out of the jam and hands its votes back to the voters; shown again, it is in no jam until an upload names the
jam again, and then it starts from zero. A hidden game cannot enter a jam: its upload goes through, and the `notes`
say "not entered in Spooky Week: a hidden game cannot be in a running jam, so show it and upload again to enter". Once the jam has ended, hiding changes
nothing: the game keeps its place, votes and trophy, and the results show people who may not see it only that a hidden
game placed.

### Removed from a jam

A jam's owner (or a Jam Master or an admin) can take a game out of a running jam, with a reason. Read it in the game's activity log:

```sh
curl -fsS -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/games/star-hopper/activity"
```

The entry has `"kind": "RemovedFromJam"`, and its `detail` is three lines: the jam's slug, its title, and the
reason. Fix what the reason says, then upload again naming the jam while it still runs: the game is back in (from
zero votes), and the `notes` say "rejoined Spooky Week, which Kari Nordmann had removed it from".

### Voting

Vote only when the user asks you to, and for the game they name. Each person has 3 votes per jam, one per game, and
none for their own games. A vote can be taken back while the jam runs, which frees it:

```sh
curl -fsS -X PUT -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/jams/spooky-week/votes/space-race"
curl -fsS -X DELETE -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/jams/spooky-week/votes/space-race"
```

Both answer with the jam: `myVotes` lists the games you voted for and `votesLeft` how many you have left. Voting
again for the same game changes nothing. `tally` is public: how many people have voted and how many votes are cast,
never which games they went to. How many votes each game has is shown only once the jam has ended, in `results`:
`[{ "place": 1, "gameSlug": "space-race", "name": "Space Race", "coverUrl": "...", "votes": 7, "hidden": false }]`.
A game hidden since shows only its place and votes to those who may not see it: `hidden` is `true` and its
`gameSlug`, `name` and `coverUrl` are `null`.
Most votes wins; on equal votes, the game that reached its count first. Games without votes do not place.

### Start a jam

Only when the user asks for one. Each person runs one jam at a time. `endsUtc` is when it ends: an ISO time with `Z`
or an offset, after now and at most 2 months ahead. The jam's slug comes from its title, and never changes:

```sh
curl -fsS -X POST "https://gamelab.attensi.com/api/jams" \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "title": "Space Week", "theme": "Anything with stars in it", "endsUtc": "2026-11-14T17:00:00Z" }'
```

It answers `201` with the jam. Its owner can rewrite its `title`, `theme` or `endsUtc` (`PATCH` with any of them: what is
left out stays). A new end must be after now and at most 2 months after the jam started:

```sh
curl -fsS -X PATCH "https://gamelab.attensi.com/api/jams/space-week" \
  -H "Authorization: Bearer $GAMELAB_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "endsUtc": "2026-11-14T18:00:00Z" }'
```

The owner can also end it early, which makes its results final, and delete it while it has no games and no votes:

```sh
curl -fsS -X POST -H "Authorization: Bearer $GAMELAB_TOKEN" "https://gamelab.attensi.com/api/jams/space-week/close"
```

A new `endsUtc` also reopens a jam that ended less than 12 hours ago. Its games and votes stand and voting goes on.
Games hidden or entered in another running jam since then leave it, and their votes go back. The owner may not be running
another jam at the time. After 12 hours a jam's results are set in stone.

### Can I...?

| | While the jam runs | Once it has ended |
|---|---|---|
| Enter a game | yes | no |
| Move a game to another running jam | yes, its votes go back | yes, and it stays in the ended one, trophy and all |
| Take a game out (`null`) | yes, its votes go back | no: an ended jam keeps its games |
| Update a game in it | yes | yes |
| Hide a game in it | yes, it leaves the jam and its votes go back | yes, it keeps its place and trophy |
| Vote, or take a vote back | yes | no |
| Remove someone's game (jam owner, admins) | yes | no |
| Close it early (jam owner, admins) | yes | no |
| Move its end (jam owner, admins) | yes | reopens it, within 12 hours of the end |
| Delete it (jam owner) | only with no games and no votes in it | only with no games and no votes in it |

### When GameLab says no

Every refusal says what happened and what to do next, in `detail`. These are the jam ones, word for word as GameLab
sends them for the examples above (your slugs, titles and times will differ):

| `detail` | What to do |
|---|---|
| `gamelab.json: jam 'spooky-wek' does not exist. Jams running now: spooky-week (Spooky Week, ends 2026-10-31 18:00 UTC)` | use one of the slugs it lists, or ask the user which they meant |
| `gamelab.json: jam 'summer-jam' does not exist. No jam is running right now, so leave jam out of gamelab.json` | there is nothing to enter: tell the user, and upload without `jam` |
| `gamelab.json: Summer Jam ended 2026-10-24 09:00 UTC. A game can stay in a jam it is already in, but cannot join one that has ended. Jams running now: spooky-week (Spooky Week, ends 2026-10-31 18:00 UTC)` | too late for that one: tell the user |
| `jam 'Spooky Week' must be a jam's slug, such as spooky-week, or null to take the game out of its jam: GET /api/jams?active=true lists the jams that run` | name the jam by its `slug`, not its title (in the list of the manifest's problems) |
| `the upload's ?jam= 'Spooky Week' must be a jam's slug, such as spooky-week, or none for no jam: GET /api/jams?active=true lists the jams that run` | the same, for `?jam=` |
| `You cannot vote for your own game` | vote for someone else's |
| `You have cast all 3 of your votes in Spooky Week, for space-race, moon-base and comet-chase. Take one back first: DELETE /api/jams/spooky-week/votes/<game slug>` | ask the user which vote to take back |
| `Spooky Week ended 2026-10-31 18:00 UTC: voting is over, and its results are final` | read `results` instead |
| `You already run Spooky Week, which ends 2026-10-31 18:00 UTC. Close it first (POST /api/jams/spooky-week/close), or wait for it to end: each person runs one jam at a time` | one jam at a time each |
| `endsUtc 2027-01-01 00:00 UTC is too far ahead: a jam lasts at most 2 months, so it must end by 2026-12-24 09:00 UTC` | pick an earlier end |
| `Spooky Week ended 2026-10-31 18:00 UTC, 12 hours or more ago, so its results are final: start a new jam instead` | too late to reopen it: tell the user |

## The game API: `window.gamelab`

Every HTML page of a game gets a `window.gamelab` object before its own scripts run. It talks to GameLab as
the person playing; no setup, no keys. Every call returns a promise.

```js
const me = await gamelab.me()                         // { id, name, firstName, lastName, pictureUrl }; pictureUrl is their photo, or null

// scores: the whole game, or one level; tagged with the current playthrough
await gamelab.submitScore({ score: 1200 })
await gamelab.submitScore({ score: 300, timeMs: 41250, level: "1-2" })
gamelab.newPlaythrough()                              // start a new run (one is started on load)

const board = await gamelab.leaderboard({ level: "1-2", limit: 10 })
// { rankBy, tiebreak, keep, counts, level, levels: [...], entries: [{ rank, player, score, timeMs, achievedUtc, isMe }], me }
const top10 = await gamelab.top(10)                   // just the entries, best first, ranked as the manifest says
const mine = await gamelab.myRank()                   // the player's own entry, or null
const best = await gamelab.myScore()                  // the player's own number: best score, best time (ms) or total; null before any

// achievements declared in gamelab.json; the game decides when one is earned
await gamelab.unlockAchievement("first-hop")          // GameLab shows an "achievement unlocked" toast the first time
await gamelab.unlockAchievement("first-hop", { toast: false })   // ...or draw your own
const list = await gamelab.achievements()             // [{ id, title, iconUrl, subtext, goal, goalHidden, secret, unlocked, unlockedUtc, players, percent }]

// save games: whole states as json, in named slots ("default" when left out)
await gamelab.saveGame({ level: 3, hp: 12, inventory: ["key"] })
const state = await gamelab.loadGame()                // the object back, or null when there is no save
await gamelab.saveGame(state, "autosave")
await gamelab.listSaves()                             // [{ slot, savedUtc }], newest first
await gamelab.deleteSave("autosave")

// the player's own storage for this game: string values up to 32 KB, 1000 keys
await gamelab.data.set("save", { level: 3, coins: 12 })   // non-strings are stored as json
const save = await gamelab.data.getJson("save")           // null when missing
await gamelab.data.get("name")                            // the raw string
await gamelab.data.keys()
await gamelab.data.remove("save")

// network play, for games whose gamelab.json declares multiplayer: see "Network games" below
const room = await gamelab.net.join("k7f2")           // a room code; join() alone makes a fresh one
room.peers                                            // everyone else there: [{ peer, id, name, firstName, lastName, pictureUrl }]
room.onPeers(peers => redrawLobby(peers))             // whenever someone joins or leaves
room.onMessage((data, from) => apply(data, from))     // from is one of the peers
room.send({ x: 10, y: 4 })                            // to everyone else; json, or an ArrayBuffer
const table = await room.sub("table-3")               // a sub-room, "k7f2/table-3": a room of its own, joined beside this one
```

Leaderboards keep each player's best submission, or add every submission up when the manifest says `"keep": "total"`. Players can only ever read and write their own data.
Feature-detect with `if (window.gamelab)` so the game still runs when opened outside GameLab.

### Reference

```ts
interface GameLab {
  /**
   * The person playing. name is their full display name (their first name, for someone who has none); firstName what to
   * call them (their display name without their surname, or all of it when it does not contain the surname, so a name
   * they chose is kept); lastName their surname, or null. pictureUrl is their profile photo (null if they have none), ready for <img src>.
   */
  me(): Promise<{ id: number; name: string; firstName: string; lastName: string | null; pictureUrl: string | null }>

  /** Id of the current run, generated on page load and attached to every submission. */
  readonly playthrough: string
  /** Starts a new run (e.g. after game over) and returns its id. */
  newPlaythrough(): string

  /**
   * Records a result and resolves to the leaderboard it landed on (the level's, or the game's).
   * Send the field named by scoring.rankBy (required), and scoring.tiebreak's if the game has one; any other
   * field is rejected. level and playthrough are free text, at most 64 characters. No level = the whole game.
   * With scoring.keep "total", score is added to the player's total (send 1 per win, or the kills of a round; 0 or
   * more), and the result's me.score is their new total.
   */
  submitScore(result: { score?: number; timeMs?: number; level?: string; playthrough?: string }): Promise<Leaderboard>

  /** Each player's best result (or total) for the whole game, or for one level. limit: 1-100, default 10. */
  leaderboard(options?: { level?: string; limit?: number }): Promise<Leaderboard>
  /** The best `limit` entries (default 10). */
  top(limit?: number, level?: string): Promise<LeaderboardEntry[]>
  /** The player's own entry, or null before their first result. */
  myRank(level?: string): Promise<LeaderboardEntry | null>
  /**
   * The player's own number on the leaderboard, whatever it ranks by: their best score, their best time in ms, or
   * (scoring.keep "total") their total, such as their wins. null before their first result. For the whole game, or one level.
   */
  myScore(level?: string): Promise<number | null>

  /** Every achievement in manifest order, as this player sees it. */
  achievements(): Promise<Achievement[]>
  /** Records that the player earned it; newlyUnlocked is false if they already had it. Shows a toast unless told not to. */
  unlockAchievement(id: string, options?: { toast?: boolean }): Promise<{ newlyUnlocked: boolean }>

  /** Stores any json-serialisable state in a slot (default "default"), replacing what was there. */
  saveGame(state: unknown, slot?: string): Promise<void>
  /** The state saved in a slot, or null. */
  loadGame<T = unknown>(slot?: string): Promise<T | null>
  listSaves(): Promise<{ slot: string; savedUtc: string }[]>
  deleteSave(slot?: string): Promise<void>

  data: {
    /** All of the player's keys for this game, sorted. */
    keys(): Promise<string[]>
    /** The stored string, or null when the key does not exist. */
    get(key: string): Promise<string | null>
    /** get, parsed as json. */
    getJson<T = unknown>(key: string): Promise<T | null>
    /** Stores a value: strings as-is, anything else as json. Creates or replaces the key. */
    set(key: string, value: unknown): Promise<void>
    /** Deletes a key; deleting a missing key is fine. */
    remove(key: string): Promise<void>
  }

  /** Network play; see Network games. Only for games whose gamelab.json declares multiplayer. */
  net: {
    /** A fresh room code: 6 letters and digits that are hard to mix up. */
    newRoom(): string
    /**
     * Joins the room with this code (a fresh one when left out). Resolves once the player is in, with room.peers
     * already filled. Rejects, saying why, when the room is full, the game does not declare multiplayer, or the relay
     * cannot be reached. A code with slashes, "lobby/m-1", is a sub-room (see room.sub).
     */
    join(room?: string): Promise<Room>
  }
}

interface Room {
  /** The room's code, lowercase; for a sub-room its whole path, "lobby/m-1". */
  readonly id: string
  /** The player, as the others see them. */
  readonly me: Peer
  /** Everyone else in the room right now, one entry per tab. */
  readonly peers: Peer[]
  /** False while reconnecting after a dropped link: nothing sent then is delivered. */
  readonly connected: boolean
  /** Called with all the peers whenever someone joins or leaves. */
  onPeers(handler: (peers: Peer[]) => void): Room
  /** Called for every message to this player: json as it was sent, binary as an ArrayBuffer. */
  onMessage(handler: (data: unknown, from: Peer) => void): Room
  /** Called when the link drops (false) and when it is back (true). */
  onConnection(handler: (connected: boolean) => void): Room
  /**
   * Called once when the room stops for good: "left" after leave(); "refused" when it can no longer be had (it filled
   * up while the player was away, the game no longer declares multiplayer, the play session ended); "replaced", rarely,
   * when another connection took this tab's place in the room.
   */
  onClose(handler: (reason: "left" | "refused" | "replaced") => void): Room
  /**
   * Sends json-serialisable data, or an ArrayBuffer or typed array, to everyone else, or to the peers given (a peer,
   * or a user id for all of that person's tabs). Returns false when nobody would get it: alone, or reconnecting.
   * Throws for data it cannot send: undefined, functions, more than 64 KB.
   */
  send(data: unknown, to?: (Peer | number)[]): boolean
  leave(): void
  /**
   * Joins a sub-room below this one, "<this room>/<name>", as join() would: a room of its own on a connection of its
   * own, with its own peers and messages, as separate from this room as any other. This room stays joined; leave
   * either without touching the other. name: 1-32 of letters, digits, '-', '_'. Throws for a name with a '/'.
   */
  sub(name: string): Promise<Room>
}

interface Peer {
  /** This connection, unique in the room: the same person in two tabs is two peers with the same id. */
  peer: string
  /** The person's user id. */
  id: number
  /** Their full display name. */
  name: string
  /** What to call them: their display name without their surname, as for me(). */
  firstName: string
  lastName: string | null
  /** their profile photo, or null; ready for <img src> */
  pictureUrl: string | null
}

interface Leaderboard {
  rankBy: "Score" | "Time"
  tiebreak: "Score" | "Time" | null
  /** "Best": each player's best submission; "Total": all of them added up (scoring.keep). */
  keep: "Best" | "Total"
  /** What a score counts, from scoring.counts, { singular: "win", plural: "wins" }; null for plain points. */
  counts: { singular: string; plural: string } | null
  level: string | null
  /** Every level anyone has submitted a result for. */
  levels: string[]
  entries: LeaderboardEntry[]
  /** The player's own entry, even when it is outside entries; null if they have no result yet. */
  me: LeaderboardEntry | null
}

/**
 * A secret achievement (manifest "secret": true) the player has not earned comes with id, title, iconUrl, subtext
 * and goal all null, secret and goalHidden true: it shows that it is there and nothing else. Earned, it is whole.
 */
interface Achievement {
  id: string | null
  title: string | null
  /** relative to the game's files, so <img src> works from the game page */
  iconUrl: string | null
  subtext: string | null
  /** null while goalHidden */
  goal: string | null
  goalHidden: boolean
  secret: boolean
  unlocked: boolean
  unlockedUtc: string | null
  /** how many players have it */
  players: number
  /** the share of the game's players who have it, 0-100 to one decimal: of everyone who has played it or earned any of its achievements */
  percent: number
}

interface LeaderboardEntry {
  rank: number
  player: string
  /** the player's profile photo, or null; ready for <img src> */
  pictureUrl: string | null
  score: number | null
  timeMs: number | null
  achievedUtc: string
  isMe: boolean
}
```

**Errors**: a rejected call throws an `Error` whose message says what to fix, e.g. *"This game does not
record time - add it to scoring in gamelab.json"*.

| Limit | Value |
|-------|-------|
| Stored value | 32 KB (32768 characters) |
| Keys per player per game | 1000 |
| Key length | 1-128 characters |
| `level`, `playthrough` | 64 characters |
| Leaderboard `limit` | 1-100 |
| Save game | 256 KB of json |
| Save slots per player per game | 20; slot names 1-64 of letters, digits, `-`, `_` |
| Achievements per game | 500 |
| Network message | 64 KB |
| Players per room | about the game's `multiplayer.maxPlayers`, 2-64 (players arriving at the same moment can all get in) |
| Room code | 1-32 of letters, digits, `-`, `_`; any case. A sub-room joins up to 4 of them with `/` |
| `scoring.counts.singular`, `.plural` | 1-32 characters each, free text |

The client is a thin wrapper over plain HTTP under the game's play root, `/play/<slug>/<token>/`: `GET __api/me`, `GET __api/players/<id>/photo`,
`POST __api/scores`, `GET __api/leaderboard?level=&limit=`, `GET __api/achievements`, `POST __api/achievements/<id>`,
`GET __api/saves`, `GET|PUT|DELETE __api/saves/<slot>` with a `{ "state": ... }` body for `PUT`, `GET __api/data`, and
`GET|PUT|DELETE __api/data/<key>` with a `{ "value": "..." }` body for `PUT`, `GET __api/players/<id>` for a player's
`{ id, name, firstName, lastName, pictureUrl }`, and `GET __api/net/<room>?tab=<1-16 of a-z, 0-9>` for a two-hour ticket into a room (a sub-room's path as it is, `net/lobby/m-1`),
`{ server, token, me, expiresUtc, expiresInSeconds }`: a [Styx](https://github.com/PacAnimal/hydra/blob/main/Styx.md) relay,
a token for that room only, and the one name, `u<user id>-<tab>`, it lets this tab hold there. The game's play address is valid for at least 24 hours, and only for the
player who opened it.

## Achievements

Declare each achievement in `gamelab.json` and call `gamelab.unlockAchievement(id)` when the player meets its goal.
GameLab never decides that a goal is met; the game does, and it may call as often as it likes: only the first call
counts, and only it shows the "achievement unlocked" toast. Unlocks are kept by `id`, so keep ids the same across
updates; renaming one is a new achievement.

How much a player sees before earning one is up to you, per achievement:

| Manifest | Before earning it, players see | Use it for |
|----------|-------------------------------|------------|
| (neither) | title, icon, subtext, goal | goals to aim for: "Beat the Hard AI", "Win 10 games" |
| `"hideGoal": true` | title, icon, subtext; the goal reads "Hidden until you earn it" | a hint without the answer: a title like "Night owl" |
| `"secret": true` | only that there is one more achievement: "Secret achievement", a question mark, and the share of players who have it | surprises: easter eggs, hidden rooms |

A secret achievement is kept secret by GameLab itself, not by the game: until the player has it, every list of
achievements (in the game, on the game's page, on someone else's profile) carries it with `id`, `title`, `iconUrl`,
`subtext` and `goal` all `null`. Your game still knows its ids, so unlocking works the same. Draw a locked secret one
as a question mark, and use `title === null`, not `secret`, to tell: `secret` stays `true` after it is earned.

```js
const all = await gamelab.achievements()
for (const a of all)
  a.title === null ? drawSecret(`${a.percent}% of players`) : draw(a.title, a.iconUrl, a.unlocked ? "earned" : a.goal ?? "hidden")
```

Good achievements are about things a player can see themselves doing. Unlock them where the thing happens (the
moment a game is won, a level is cleared, a total passes 10), and unlock anything a player had already earned before
the achievement existed when the game starts: a player with 12 wins who loads a game that has just added "Win 10
games" should get it at once. Network Pong does that from the leaderboard: `myScore()` is the player's total of wins.

## Counting things: wins, kills, goals

By default a leaderboard keeps each player's **best** submission: the high score of a run, the fastest time. Some
games count instead: wins in a duel, kills in a shooter, goals in a season. For those, make every submission add to
the player's **total**, and say what is being counted:

```json
{ "scoring": { "rankBy": "score", "counts": { "singular": "kill", "plural": "kills" }, "keep": "total" } }
```

- `keep: "total"` adds every `submitScore({ score })` to the player's total for the game (or for the `level`, which
  keeps totals of its own). Players rank by their totals, highest first; equal totals go to whoever reached theirs
  first. Scores must be 0 or more: a total never goes down. It needs `rankBy: "score"` and no `tiebreak`.
- `counts` names what the score counts, in your words, both ways; GameLab guesses no plurals. Each is free text of
  1-32 characters, and the two may be the same (`"sheep"`). GameLab's game page then shows "1 kill", "12 kills",
  "most kills in all". The leaderboard hands them back as `counts: { singular, plural }`
  for drawing your own.
- `counts` works with `keep: "best"` too: "Most kills in one round" is
  `{ "rankBy": "score", "counts": { "singular": "kill", "plural": "kills" } }`.
- Only ever submit what was counted, and only what the player earned: GameLab adds up whatever arrives. To count
  wins, the winner submits `1` and the loser submits nothing (losses are not a score).
- `submitScore` resolves to the leaderboard it landed on, and `me.score` there is the player's new total: use it for
  "win 10 games" achievements. `gamelab.myScore()` gives the same number at any time, to show "You have 12 wins".

```js
// a shooter, at the end of each round
const board = await gamelab.submitScore({ score: killsThisRound })
if (board.me.score >= 1000) gamelab.unlockAchievement("thousand-kills")

// a duel, by the winner only
if (iWon) await gamelab.submitScore({ score: 1 })
```

Changing `keep` in a later upload changes how the submissions already made are ranked, not the submissions: switch
a game from `best` to `total` and everyone's past scores are added up.

## Network games

A game whose `gamelab.json` declares `multiplayer` can put players together in **rooms** and pass messages between
them as they play: positions, moves, chat, anything. There is no server to write. Messages go straight from player to
player through GameLab's relay, in a few tens of milliseconds, and GameLab decides who may join which room, so a game
needs no accounts or keys of its own.

**Network Pong** in the gallery is the complete example, and its source is written to be read: a lobby room everyone
is in, with chat and statuses (lurking, waiting, playing); matchmaking that puts a newcomer straight into a game with
whoever has waited longest; challenges by clicking someone; a sub-room for each game; one player running the game for
both; play that pauses while either player looks away; a leaderboard that adds up wins; and achievements. Each file
does one of those, with comments that say why:

| File | Does |
|------|------|
| `src/main.js` | the page: joins the lobby on load, the lobby panel, games against people and the AI, input, the frame loop |
| `src/lobby.js` | the lobby protocol: statuses, matchmaking, challenges, chat |
| `src/match.js` | one game between two people in its sub-room: the host runs the board, the guest follows it |
| `src/pong.js` | the rules, as pure functions: the same code runs for the host, against the AI and in tests |
| `src/ai.js`, `src/sound.js`, `src/render.js`, `src/achievements.js` | the computer player, sound, drawing, which achievements a game earns |

To read it, ask GameLab for the game and fetch the files next to its play page, with your token:

```sh
play=$(curl -fsS -H "Authorization: Bearer $GAMELAB_TOKEN" https://gamelab.attensi.com/api/games/network-pong | jq -r .playUrl)
curl -fsS "https://gamelab.attensi.com${play%/*}/src/lobby.js"
```

### Turn it on

```json
{ "multiplayer": { "maxPlayers": 8 } }
```

### The smallest network game

Everyone in the room sees everyone's pointer. It is the whole game: an `index.html` with this script.

```html
<canvas id="c" width="800" height="600"></canvas>
<script>
const ctx = document.getElementById("c").getContext("2d")
const pointers = new Map()                        // peer -> { name, x, y }

gamelab.net.join("everyone").then(room => {
  room.onMessage((data, from) => {
    if (typeof data?.x !== "number" || typeof data?.y !== "number") return  // check what arrives
    pointers.set(from.peer, { name: from.name, x: data.x, y: data.y })
  })
  room.onPeers(peers => {                          // forget whoever left
    const here = new Set(peers.map(p => p.peer))
    for (const peer of pointers.keys()) if (!here.has(peer)) pointers.delete(peer)
  })
  let last = 0
  addEventListener("pointermove", e => {           // at most 20 updates a second
    if (performance.now() - last < 50) return
    last = performance.now()
    room.send({ x: e.offsetX, y: e.offsetY })
  })
}, error => alert("Could not join: " + error.message))

;(function draw() {
  ctx.clearRect(0, 0, 800, 600)
  for (const p of pointers.values()) ctx.fillText("● " + p.name, p.x, p.y)
  requestAnimationFrame(draw)
})()
</script>
```

### Rooms

- A room is a **code**: 1-32 letters, digits, `-` or `_`, in any case. Everyone who joins the same code is in the
  same room, and each game has its own rooms. `gamelab.net.join()` with no code makes a fresh one; show `room.id` so
  friends can type it in, or have everyone join a fixed code such as `"lobby"`, as the sample game does.
- `join` resolves once the player is in, with `room.peers` already filled: everyone else there, as
  `{ peer, id, name, firstName, lastName, pictureUrl }`. `onPeers` reports every change after that. `room.me` is the
  player in the same shape, and `from` on every message is one of the peers.
- `name` is the person's full display name and `pictureUrl` their profile photo (or null), ready for `<img src>` or a
  canvas. For a friendlier label use `firstName`: their display name without their surname, so someone who goes by a
  name of their own keeps it. A game that wants nicknames lets players pick one and sends it in its own messages.
- **Each tab is its own peer.** The same person can be in a room twice, from two tabs, so key what you keep about
  players by `peer`, not `id`. It also means you can try a network game on your own, in two tabs.
- A room takes about `maxPlayers`; past that, `join` is refused. Players arriving at the very same moment can all get
  in, and someone already in the room can always open another tab, so allow for a few more.

### Sub-rooms

A room can have rooms below it: `room.sub("table-3")` joins `"lobby/table-3"` from the room `"lobby"`, and
`gamelab.net.join("lobby/table-3")` joins the same room directly. Paths go up to 4 deep.

- A sub-room is a **room of its own**: its own peers, its own messages, its own `maxPlayers`. Nobody in `"lobby"` sees
  who is in `"lobby/table-3"` or anything sent there, and the other way round, exactly as for two unrelated rooms.
- Joining one does not leave the room above: a player can be in the lobby and at a table at once, each on its own
  connection, and leave either without touching the other. Peer names (`peer`) differ between the two; the person
  (`id`) is the same, so recognise someone across rooms by `id`.
- Use them to keep a busy room's traffic away from the few players it concerns: the lobby carries chat and who is
  free, and each game's 30 updates a second go to its own sub-room, where only its two players hear them. Name the
  sub-room something the players agree on before they go there, a random id sent in the lobby, as below.

### A lobby: matchmaking, challenges, chat

A common shape for games of two (or a few) players, the one Network Pong uses:

1. Everyone joins one room, `"lobby"`, the moment the game opens, and tells the others what they are doing, as
   `{ t: "state", s: "lurking" | "waiting" | "playing", since }`: in the lobby, wanting a game, or in one. A newcomer
   sends `{ t: "hello" }`, and everyone answers it with their state, straight to the newcomer.
2. A game is agreed with a **challenge**: `{ t: "challenge", match }` with a fresh random `match` id, answered
   `{ t: "accept", match }` or `{ t: "decline", match }`. A waiting player accepts the first challenge it gets and
   declines the rest, so two challengers never get the same opponent. A lurking player is asked, and may say no.
3. Whoever arrives while someone is waiting challenges the one who has waited longest (smallest `since`, then lowest
   `peer`): every machine orders waiters the same way, so two people waiting are paired by the later challenging the
   earlier, never both at once.
4. Both players then join the sub-room `lobby.sub(match)` and play there, staying in the lobby as `"playing"`. After
   the game they leave the sub-room and are `"lurking"` again.

```js
const lobby = await gamelab.net.join("lobby")
lobby.onMessage((m, from) => {
  if (m?.t === "challenge" && typeof m.match === "string" && /^m-[a-z0-9]{1,16}$/.test(m.match) && waiting) {
    waiting = false
    lobby.send({ t: "accept", match: m.match }, [from])
    play(m.match, from, true)                    // the one who was waiting hosts
  } else if (m?.t === "accept" && m.match === myChallenge) play(m.match, from, false)
})
async function play(match, opponent, host) {
  const game = await lobby.sub(match)            // "lobby/m-...": only these two are in it
  // wait until game.peers holds someone with opponent.id, then play; game.leave() when it is over
}
```

`src/lobby.js` is the whole of it, with the timeouts, withdrawn challenges, players who leave halfway and the checks on
every message, and its tests run it between several fake players.

### Messages

- `room.send(data)` sends to everyone else in the room; `room.send(data, [peer])` to some of them. `data` is anything
  JSON can carry, or an `ArrayBuffer` / typed array for binary. At most 64 KB a message.
- Messages from one player arrive in the order they were sent. There is no reply and no delivery receipt, and nothing
  is stored: a player who joins later sees only what is sent after they arrive.
- **`from` is always who really sent a message**, and it cannot be faked. **What they sent can be**: every player runs
  their own copy of your game and can change it. Check that a message has the shape you expect before using it, as
  the example above does, and never let one break your game.

### Patterns that work

**Send state, not every keystroke, and not too often.** Send where you are (or what changed) about 10 times a second
while things change, plus a heartbeat every second or two when nothing does. Draw others moving smoothly between
updates (below) rather than sending more.

**Greet newcomers.** A player who just arrived knows nothing yet. In `onPeers`, send your current state straight to
each new peer, so they see you at once instead of at your next update:

```js
let known = new Set()
room.onPeers(peers => {
  for (const p of peers) if (!known.has(p.peer)) room.send(myState(), [p])
  known = new Set(peers.map(p => p.peer))      // so someone who drops and comes back is greeted again
})
```

**Smooth what you draw.** Keep each player's last reported position as a target, and move what you draw a fraction of
the way towards it every frame, so 10 updates a second look like 60:

```js
other.x += (other.targetX - other.x) * Math.min(1, dt * 12)
```

**Let one player decide what must be the same for everyone** (whose turn it is, where the ball goes, who won). Pick
that player the same way on every machine - for example the lowest `peer` among `room.me` and `room.peers` - and
let the others follow what it sends. When it leaves, `onPeers` fires everywhere, and everyone picks the same new one:

```js
const host = () => [room.me, ...room.peers].map(p => p.peer).sort()[0]
const iAmHost = () => host() === room.me.peer
```

**Pause while someone looks away.** A browser stops animation frames in a hidden tab, and slows its timers to once a
second or less, so a host that is in another tab stops running the game. Have each player send whether they are
there (`document.visibilityState === "visible"`, on `visibilitychange`) and run the game only while both are; say
"waiting for Ann to come back" meanwhile. Network Pong also waits for one click from each player before the first
serve, since browsers play sound only after one.

**Get attention from another tab.** A player waiting in the background will not see a game start. Play a sound (any
sound may play in a background tab once the player has clicked something in the game, such as a "Wait" button) and
flash the tab's title until they come back.

**Scores stay personal.** Each player submits their own result with `gamelab.submitScore`, as in a single-player game.
To count wins, have only the winner submit `1` to a `keep: "total"` leaderboard (see
[Counting things](#counting-things-wins-kills-goals)); the host's word on who won is the one both follow.

### When the link drops

GameLab reconnects by itself, with the same peer, and renews the room's ticket while the game runs. While it is away,
`room.connected` is false, `onConnection(false)` has fired, and `send` returns false: nothing sent then arrives.
Others may have moved meanwhile, so when `onConnection(true)` fires, send your state again. `onClose` fires only when
the room is over for good: `"left"` after `room.leave()`, or `"refused"` when it can no longer be had; tell the player
and offer to join again.

### Trying it out

Open the game in two tabs, or two browsers, and play against yourself; then ask a colleague in. Only one tab of a
window is ever visible, so a game that pauses while a player looks away (as above) needs two windows side by side. Show which room a
tab is in (`room.id`, and a sub-room's too) somewhere on screen while you build it: it makes matchmaking easy to
follow, and Network Pong keeps it for players to see. Opened outside
GameLab, `window.gamelab` does not exist: check for it, and let the game run on its own.

## How games run

Games play in a sandboxed iframe with an opaque origin, isolated from the rest of the site. In practice:

- **Use relative paths** (`js/game.js`, not `/js/game.js`): the game is served from a sub-path.
- Every file of the upload is served to the game except `gamelab.json`, which stays GameLab's (it lists the secret
  achievements). Ask the game API for what it holds instead: `gamelab.achievements()`, `gamelab.leaderboard()`.
- `fetch`, ES modules, WebAssembly, audio and video all work for the game's own files.
- `localStorage` and `sessionStorage` work but are **in-memory only**: saves are lost when the page closes.
  Use `gamelab.saveGame` or `gamelab.data` for anything that should last. Cookies, IndexedDB and service workers are unavailable.
- Pointer lock, fullscreen, gamepads and popups are allowed.
- The game fills the browser window below GameLab's bar, and the bar has a fullscreen button. Design for any
  viewport size and shape, and listen for `resize`.
