llms.txt
Compare with other sites' llms.txt files →# antics — multiplayer for AI-generated web games
Deploy a web game — one HTML file or a multi-file project — and get a multiplayer link with a
leaderboard. No backend, no accounts for players. This file is the complete integration reference —
if you are an LLM generating a game, you can hold the whole API in view at once.
## Import
// ES module (recommended), served same-origin when your game is deployed on antics:
import { joinRoom, getLeaderboard, interpolate } from "/sdk/v1.js";
// or from npm: import { joinRoom } from "antics-sdk";
// or classic <script src="/sdk/v1.global.js"></script> then use window.antics.joinRoom
When your game is deployed on antics, call joinRoom({}) with NO arguments: the SDK auto-detects
the server (same origin) and the room code (from the ?room= the page provides). That is the
whole integration for a hosted game.
## Core rules (read these)
- Two state surfaces. `room.state` is SHARED and only the HOST may write it (world, NPCs,
game phase, scores). Each player writes only their OWN slice via `room.me.setState(...)`
(their position, input, cosmetics). Do not route every player's movement through the host.
- Latency: act on your OWN client at once, then sync — never make another client detect your
action and echo the result back (that stacks two network hops and feels laggy). A shooter
should detect its OWN hits and drop the target's health bar immediately, then `send` a `hit`
event the victim applies as authoritative damage. (This is "favor-the-shooter": responsive,
and it trusts each client about its own shots — fine for casual games, not cheat-proof.)
IT IS ABOUT THE EFFECT, NOT ABOUT POSITIONS. Trusting a client's claim about damage it
dealt is fine. Trusting its claim about where a SHARED object is — the ball, the puck, the
bomb — is not the same trick: that client's copy of the object is behind by definition, so
adopting its position rewinds the object for everyone else, most visibly for whoever has
the best connection. Take the impulse; clamp the position to a plausible drift from your own.
- STAMP ANYTHING THAT MOVES, AND REPLAY IT FORWARD BY ITS AGE. This is the single biggest
netcode mistake on the classic tier and it does not look like a mistake — the game runs
fine next to you and badly across an ocean. A patch you receive was written one leg ago and
the sender has moved on since; if you ease toward its raw contents you are easing toward
the past, and THE CORRECTION IS THE LAG. Smoothing harder only spreads it out. So:
// sender — one extra number, on the SHARED clock (never Date.now(): that is
// per-device and comparing two of them across the wire is meaningless)
room.setState({ ball: { x, y, vx, vy, at: room.now() } })
// receiver — advance it to NOW before you use it, then ease toward THAT
const age = Math.min(400, room.now() - snap.at) // clamp: never extrapolate wildly
const target = advance(snap, age / 1000) // your own integrator, ideally the
// real one so it respects walls/floors
Three things that bite even after you do this:
(1) Adopt the sender's VELOCITY once per snapshot, not once per frame — re-applying it
every frame pins velocity to that packet's value for the whole gap between packets, so
gravity and drag stop accumulating and the object flies flat, then jerks on arrival.
Gate on a sequence number.
(2) Extrapolate remote players too. Their velocity is already in the slice; using it only
for animation leaves them metres behind at any real running speed. And scale your
smoothing by dt — a fixed per-frame lerp constant smooths twice as slowly in wall time
at 30fps as at 60, so phones get double the lag.
(3) Do not difference room.now() across devices without a MINIMUM filter. It is only as
good as an RTT sampled by a timer sitting behind your render loop, and a stalled main
thread inflates it — two clients on ONE MACHINE can read apparent ages of 400ms+. Every
error source only ADDS delay, so keep the running minimum per sender (leaking upward
slowly so a genuinely worsening link is still tracked) and add locally-measured time
since arrival. Over-extrapolating is worse than under: it puts things where they have
never been.
VERIFY IT: `verify_game { simulateLatencyMs: 150 }` (or 250) works on BOTH tiers and is the
only way you will ever see this — you are testing on loopback, which is the one network
condition your players will never have. `interpolate`/`interpolateGroup` below handle the
SMOOTHING half of this well; they do not handle the age half, so stamp regardless.
CLEAR HELD-KEY STATE ON WINDOW BLUR (`addEventListener("blur", () => keys.clear())` —
and send a neutral input if you forward input state to a server): when a player switches
windows mid-keypress, the keyup fires in the NEWLY focused window and yours never sees
it, so the key stays "held" forever. In a multiplayer game the stuck player keeps
walking — off ledges, into hazards — while their window sits unattended (found by a
human playtest: an unattended fighter death-looped off the stage and haunted the other
player's screen as a shaking ghost at the respawn point).
RECONCILE the sync: after you predict that drop, the victim's next state still shows FULL hp
(they haven't applied your hit yet), so blindly copying their authoritative hp every frame
snaps the bar back up for a frame, then "really" updates a round-trip later. Render
`hp = min(predicted, authoritative)`. To allow respawns/heals, snap the prediction back up
ONLY when the authoritative value RISES above its OWN previous value (track last-seen
authoritative hp) — NOT whenever authoritative > predicted. That second test is true the
instant you predict a hit, so re-snapping there reintroduces the exact lag. Same idea for any
value you predict locally then also receive over the network.
Other clients REPLAY your events — they don't run your logic — so anything you detect locally
(a projectile impact, a melee hit, a trap trigger) needs its OWN visual on each client. E.g. a
bullet others spawned from your `shoot` event flies THROUGH the victim to a wall on their
screens unless every client gives it collision (stop + spark on overlap with any non-owner
player); keep authority single-sourced — only the owner `send`s the hit.
- Presence is immediate; there is no lobby. The instant `joinRoom` resolves you are in
`room.players` for everyone, and any state you write is visible to all of them at once. If
your game has a start / ready / menu screen, gate spawning AND rendering on your OWN flag —
don't mark a player alive or draw them until they actually enter. Otherwise a player sitting
on the menu shows up to others as a frozen "ghost" at their initial position.
EVEN A SINGLE-PLAYER GAME shares its room: the share link puts every visitor in ONE room,
with the player count in the chrome bar — two people staring at unrelated boards with no
explanation reads as broken. Acknowledge co-presence: render other players as translucent
ghosts running their own attempt (mirror your position into room.me.setState and draw
room.players — a dozen lines), or show "N racing this course" from room.players.length.
The leaderboard is already shared either way.
- State is a flat key/value map, last-writer-wins. A value of `null` DELETES that key.
- Write every frame if you want — the SDK coalesces writes to ~20 Hz automatically.
- Host can change AT ANY TIME — not only when the host leaves. The SDK hands host over
when a page is backgrounded, and when its rAF loop stops for 5s (a tab that threw, lost
its renderer, or got starved); the server re-elects too if the host stops writing shared
state. So authority can move while that player is still connected and still "playing".
Use `room.isHost` / `room.onHostChange(...)`, re-check `isHost` before every host-only
write (the relay rejects the rest with `NOT_HOST`), and keep host-owned state in
`room.state` so whoever inherits it can carry on — never in a host-only local variable.
- KEEPING THE HOST IS AN OPT-IN: `joinRoom({ keepHost: true })`. A connected host then keeps
authority through a hidden page or a stalled loop, and the match waits for it to recover
instead of moving to another player. For a presenter-hosted big room (a laptop on a
projector hosting 64 phones), not for a pocketed phone. A real disconnect or leave still
elects a replacement, and a resumed player does not take authority back. Keep the match
machine in `onHostTick` so a renderer that stops does not stop the game it is keeping.
- No key needed to start. `joinRoom({})` works instantly (keyless). A key (`pk_...`) makes
rooms + leaderboards persistent.
- Deployed games run in a sandboxed iframe (opaque origin): localStorage, sessionStorage,
and cookies are UNAVAILABLE there — accessing them THROWS; if you must touch them, wrap
in try/catch. NO FEATURE TEST WORKS, so do not write one: `typeof localStorage` THROWS
(it is an accessor, and typeof only spares you an UNDECLARED name), and
`'localStorage' in window` returns true and tells you nothing. Uncaught at module scope
this is a blank canvas on production only, while every local test passes — the game runs
same-origin at the top of a tab everywhere except production. `try` is the only guard.
A preference you cannot remember is one you do not remember: degrade, never throw.
Player id + name are stable for the SESSION (including reconnects within
the grace window) but do NOT survive a reload or a later visit — never key durable data
on them. Cross-session storage today = the project leaderboard (per player-NAME in
public reads), nothing else; design "remember my best" features around that honestly.
- The hosting page already shows the room code, an invite link + QR, and the live player
count in a bar above your game — don't re-render those (it just duplicates the chrome). It does
NOT draw a leaderboard or any in-canvas UI. If your game wants a leaderboard, render it yourself
from the data (see Example 3) — it's optional, many games don't need one.
## API (the entire surface)
const room = await joinRoom({
game?: string, // project id (keyed mode); omit for keyless
room?: string, // room code to join; omit to create one (auto-read from ?room= if hosted)
key?: string, // publishable key pk_...; omit for keyless
name?: string, // display name; default "Guest N" (auto-read from ?name= in the
// page URL when omitted — so a verify capture can name its player
// via urlParams: { name: "TestBot" } and a shared link can carry one)
keepHost?: boolean, // keep a connected host through stalls (see the host bullet above)
});
Your game runs in a sandboxed iframe with NO localStorage — but the hosting room page
owns a persistent per-browser name and passes it in as ?name= automatically. To let
players set their name from inside your game (recommended: a lobby input), rename in
place and ask the page to remember it:
const accepted = await room.rename("Ada"); // resolves with the moderated name
parent.postMessage({ antics: "save_name", name: accepted }, "*");
room.onPlayerRename(p => { /* p.name changed; same id, state, host, score */ });
`rename` keeps the player's id, per-player state, host role and leaderboard identity;
nobody leaves or joins, and peers get `onPlayerRename`, not `onLeave`/`onJoin`. The server
trims, caps at 32 characters and filters the name; an empty or filtered name REJECTS the
promise (`BAD_MESSAGE`, "Choose another name."), and the old name stays. Screens cannot
rename. `save_name` makes the page keep it for every game the player opens there; the
app's page ignores it, because there the name is the account's.
The older path still works: `parent.postMessage({ antics: "set_name", name: "Ada" }, "*")`
(optional `{ params: { autoready: "1" } }` comes back as ?autoready=1). The page saves the
name and RELOADS your iframe with the new ?name= — you rejoin the same room renamed, so
treat it as a navigation: re-arm any "ready" button via the autoready passthrough, and
never commit it from a blur handler (the reload eats the click that caused the blur).
Prefer `rename`: a reload is a fresh join (new player id, per-player state and host role
gone), a rename is not. Empty name reverts to "Guest N" on either path.
WHO IS PLAYING (`room.identity`): OPTIONAL, AND NULL IS THE NORMAL ANSWER.
Some players have accounts on antics. Your game can know which, without ever handling
a credential:
const room = await joinRoom({});
room.identity; // { signedIn, playerId, name, avatar } or null
room.onIdentity((id) => { /* they signed in or out mid-session */ });
`null` means nothing framed your game (a local file, a capture, your own page), and a
signed-out player is `{ signedIn: false, playerId: null, name: <their name> }`, which is
what every player looked like before accounts existed. So a game that reads this still
works for the guests who are most of them, and a game that ignores it is unaffected.
`playerId` is an opaque hash SCOPED TO YOUR GAME: stable for that person across sessions
and devices, and different in every other game, so it is the right key for "have I seen
this player before" and useless for anything else. Do not parse it.
WHAT YOU WILL NEVER RECEIVE, by design: the session token, the email, the account id, the
provider. Your game runs in a sandboxed opaque origin and cannot reach the page's storage,
and the identity payload is built to be worth nothing to a game that asks for it in bad
faith. The chrome answers `parent.postMessage({ antics: "who" }, "*")` from anybody, which
is safe precisely because the answer carries nothing to steal.
The raw `antics:"identity"` message also carries `lang`: the language the player reads, a
lowercase code such as "fr", the same for everybody on that page (on the TV, the party host's),
and nothing a game could not read from `navigator.language` anyway. The frame URL carries it too
as `?lang=`, for your first paint. Absent means English. See "Languages" below.
THE FRONT DOOR (`antics: "mint"`) — ASK FOR A ROOM INSTEAD OF CREATING ONE.
`/p/<slug>` boots your game with NO room (`?menu=1` in the frame's query): arriving is
not playing, so the page shows YOUR menu and the address bar stays on the permanent
link. When the player picks a door, ask the page for a room:
parent.postMessage({ antics: "mint", entry: "multi" }, "*"); // play with strangers
parent.postMessage({ antics: "mint", entry: "private" }, "*"); // a room of your own
// optional: { params: { mode: "arena" } } — rides into the reloaded frame's query
// refusals come back DOWN: { antics: "mint_failed", reason: "..." } — show the sentence
parent.postMessage({ antics: "home" }, "*"); // take the TOP page back to /p/<slug>
The page mints server-side and reloads your frame into `?room=<code>&entry=<entry>`; it
never navigates the top page, so what the player copies is still your permanent link.
On a project with `roomTarget` set, `entry:"multi"` resolves the POOLED room — strangers
who clicked the same link meet — while `"private"` always mints fresh. Read `?entry=` on
boot if the two doors should play differently.
YOU GET THIS FOR FREE — the SDK asks on your behalf. If you call `joinRoom({})` on a `/p/`
page with no room, the SDK posts the mint itself (`entry: "multi"`) and joins the room the
page grants, WITHOUT reloading your game. So a game that never speaks the contract still
gets a project-scoped room: scores on your real leaderboard, 16 players, and a working
`/r/<code>` invite. If the page refuses or does not answer, the SDK falls back to an
unkeyed room and says so in the console.
Speak the contract YOURSELF when you want to choose: a front door with two buttons (play
with strangers vs a room of your own), a menu whose state should ride into the room via
`params`, or anything else the SDK cannot decide for you. The SDK only asks when nothing
else has — an explicit `room`, or a `?room=` already in your URL, means somebody decided.
The SDK also reports the room it joined UP to the page automatically (`antics: "room"`) —
you never send this one; it is what fills the header's code and player count.
WHAT THE PAGE TELLS YOU BACK, in your frame's query — read these on boot:
?room=<CODE> the room you are in
?entry=multi|private WHICH DOOR the player pressed (only after a mint)
?pool=1 THIS ROOM IS SHARED WITH STRANGERS — set however they arrived: a mint
that resolved the pool, or a copied /r/<code> invite into it
?menu=1 no room yet; show your front door
?fresh=1 a room nobody chose (a /g/ mint landing) — fine to show your menu; an
INVITE link never carries it, and must never show one
?name=<name> the player's saved name (joinRoom reads this for you)
`entry` and `pool` are different questions and you almost always want `pool`. `entry=multi`
means the player pressed MULTIPLAYER, which on a project with no roomTarget still mints them
a private room. `pool=1` means the room is actually shared. Anything that must hold for
strangers — a mode nobody may change for others, no auto-start on a full lobby, seating a
late arrival instead of making them wait — keys off `pool`.
SHAREABLE DEEP LINKS (`share()` / `sharedState()`) — HAND SOMEBODY THE SCENE, NOT THE GAME.
A state of your game that fits in a URL — a seed, a puzzle, a level somebody built, the
arrangement on screen — can travel in the /p/ page's FRAGMENT, and land the person who opens
it on exactly that. A fragment never reaches the server or the CDN, so this costs no deploy,
no database row and no cache entry, and the link stays your project's permanent one.
import { share, sharedState, quiet } from "/sdk/v1.js";
const url = await share(code); // the page composes the link AND opens its share sheet
// (copy field + QR). Rejects if the state is refused or
// the page does not answer — keep a local fallback.
const code = sharedState(); // this page's fragment without the "#", "" if none
quiet(); // call at natural pauses (a level end, a menu, a scene
// change) so the platform can time its prompts kindly
THE LIMIT IS 8192 CHARACTERS, and the characters must be fragment-safe: `A-Z a-z 0-9` and
`. _ ~ : @ ! $ & ' ( ) * + , ; = / ? -`. No percent escapes, no spaces, no "#". Anything else
is REFUSED whole (the page never repairs a state — half a scene is a link to a scene nobody
shared). base64url of a compact binary encoding is the shape that fits: quantise, cap how
many things you serialise, and if it will not fit, share a recipe rather than a world.
YOU NEVER COMPOSE THE LINK. You hand up a state string and the page builds
`<origin>/p/<slug>#<state>` itself: the origin and the slug are facts your frame does not
hold, and a link is a claim about both. Outside a frame, `share()` composes from your own
document's URL, so a game served anywhere else still works.
`sharedState()` IS HOSTILE INPUT. It is whatever a stranger typed after a "#", so read it the
way you would read a network packet: check a version tag of your own, clamp every number to
the caps your sim already keeps, whitelist every enum, refuse the whole state on any field
that does not fit, and fall back to your normal start. Never size an array from it, never
feed it to `eval`/`Function`, never trust a length it declares. Refuse loudly (a line on
screen) rather than silently dealing three quarters of somebody's scene.
A POOLED ROOM IS A ROLLIN