# Game module

**Purpose:** `SDK.game` tells the portal what your game is doing (loading, playing, celebrating, in a room) and lets the portal tell your game about player preferences. Every method returns a promise except where noted. Errors that any call can raise (`sdkNotInitialized`, `sdkDisabled`, `timeout`) are listed in [errors](https://docs.zokogames.com/sdk/introduction#errors); the codes below are the ones specific to this module.

## At a glance

Every member of `SDK.game`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `gameplayStart(): Promise<void>` | Nothing. | `sdkNotInitialized`, `sdkDisabled`. A portal that does not answer in time only logs a console warning. | 1.0.0 |
| `gameplayStop(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingStart(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingStop(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingProgress(percentage: number): Promise<void>` | Nothing, as soon as the value is queued. | `invalidArgument` (not a number from 0 to 100), `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `happytime(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `reportGameCompletedPercentage(percentage: number): Promise<void>` | Nothing. | `invalidArgument` (not a number from 0 to 100), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `setGameContext(context: GameContext): Promise<void>` | Nothing. | `invalidArgument` (not a flat object of strings, finite numbers and booleans), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `clearGameContext(): Promise<void>` | Nothing. | `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly settings: GameSettings` | A copy of the current settings, at once. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `addSettingsChangeListener(fn: (settings: GameSettings) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `removeSettingsChangeListener(fn: (settings: GameSettings) => void): void` | Nothing. | Throws `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly isOffline: boolean` | `true` while the player has no connection. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.2.0 |
| `addOfflineListener(fn: (offline: boolean) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws like `addSettingsChangeListener`. | 1.2.0 |
| `removeOfflineListener(fn: (offline: boolean) => void): void` | Nothing. | Throws like `removeSettingsChangeListener`. | 1.2.0 |
| `updateRoom(update: RoomUpdate): Promise<void>` | Nothing. | `invalidArgument` (see below), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `leftRoom(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `inviteLink(params: InviteParams): Promise<string>` | The link to share. | `invalidArgument` (not a flat object of strings), `unexpectedError` (kids mode), `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly inviteParams: InviteParams \| null` | The invite parameters of this launch, or `null`. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `getInviteParam(key: string): string \| null` | One parameter, or `null`. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `addJoinRoomListener(fn: (params: InviteParams) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws like `addSettingsChangeListener`. | 1.0.0 |
| `removeJoinRoomListener(fn: (params: InviteParams) => void): void` | Nothing. | Throws like `removeSettingsChangeListener`. | 1.0.0 |
| `readonly isInstantMultiplayer: boolean` | `true` for a "play together" launch. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `readonly room: RoomApi` | The room data channel (table below). | Its members throw or reject like the rest of the module. | 1.3.0 |
| `reportChat(report: ChatReport): Promise<void>` | Nothing. | `invalidArgument`, `rateLimited`, `unexpectedError`, `sdkNotInitialized`, `sdkDisabled`. | 1.4.0 |
| `onScreenshotRequest(handler: ScreenshotHandler): () => void` | A function that removes the handler. | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.4.0 |
| `showInviteButton(params: InviteParams, options?: { portalOnly?: boolean }): Promise<string>` | The invite link. | As `updateRoom` and `inviteLink`. With `portalOnly: true` the call does not use `updateRoom` (see below). | 1.1.0 (deprecated; `options` added in 1.7.0) |
| `hideInviteButton(options?: { portalOnly?: boolean }): Promise<void>` | Nothing. | As `updateRoom`; with `portalOnly: true` it cannot fail on the room. | 1.1.0 (deprecated; `options` added in 1.7.0) |
| `readonly isInstantJoin: boolean` | Same as `isInstantMultiplayer`. | Throws like `isInstantMultiplayer`. | 1.1.0 (deprecated) |

Since SDK 1.6.2: a read-only `gameId` string on the game module, the portal's id for this game as the portal sends it when the SDK starts (`"local-game"` in local mode). Like `isInstantMultiplayer` it throws `sdkNotInitialized` before `init()` resolves and `sdkDisabled` when the environment is `disabled`. It is not wrapped by the engine plugins yet.

Types: `GameApi`, `GameContext`, `ChatReport`, `GameSettings`, `InviteParams`, `RoomUpdate`, `RoomApi`, `ScreenshotHandler` and `ScreenshotSource` are in the declaration file described in the SDK introduction.

## Lifecycle

```text
init() resolves
  -> loadingStart()                 portal shows its loading bar
  -> loadingProgress(0..100)        optional, repeat
  -> loadingStop()                  loading bar removed, load time recorded
  -> gameplayStart()                first level is live (also removes the loading bar)
       ... gameplayStop() at pause / death / menu / shop ...
       ... gameplayStart() when play resumes ...
  ad:  gameplayStop() -> requestAd -> adStarted (pause + mute) -> adFinished | adError (resume) -> gameplayStart()
```

None of these calls is checked for order, so a wrong order never throws. The portal just records what you send.

## Gameplay events

```ts
gameplayStart(): Promise<void>
gameplayStop(): Promise<void>
```

Call `gameplayStart()` when the player is actively playing and `gameplayStop()` whenever that stops: pause menu, death or results screen, level select, a shop, or before an ad. The portal uses the pair to measure real playtime, which feeds your [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics).

<!-- docs-sample: uses game -->
```js
function resume() { game.running = true; SDK.game.gameplayStart(); }
function pause() { game.running = false; SDK.game.gameplayStop(); }
document.addEventListener("visibilitychange", () => { if (document.hidden) pause(); });
```

Rules of thumb:

- Do not call `gameplayStart` at page load. Call it when the first level is live.
- Do not call either one every frame. Repeated calls in the same state are harmless but noisy.
- Basic launch needs only `gameplayStart`. Full launch needs both, in the right places.
- `gameplayStart()` also removes the portal's loading bar if you never called `loadingStop()`.

Errors: only `sdkNotInitialized` and `sdkDisabled`. The call has no arguments and resolves with nothing. If the portal does not answer within 10 seconds (a busy or closing tab), the call still resolves and the SDK writes a warning to the console, so an unawaited call never becomes an unhandled rejection. `gameplayStart`, `gameplayStop`, `loadingStart`, `loadingStop`, `happytime` and `leftRoom` behave this way. Over the call limits (see the call limits in the SDK introduction: 10 in a burst and 5 a second for all but `leftRoom`, 30 and 10 for `leftRoom`) a call is dropped and still resolves.

## Loading

```ts
loadingStart(): Promise<void>
loadingStop(): Promise<void>
```

Optional. Call `loadingStart()` as the game begins loading assets and `loadingStop()` when it is ready to play. Between the two you may also report progress:

```ts
loadingProgress(percentage: number): Promise<void>
```

`percentage` is a number from 0 to 100; anything else (a string, `NaN`, 101) rejects with `invalidArgument`. The portal shows it as a progress bar, but only between `loadingStart` and `loadingStop`. Values are rounded to a whole number and coalesced: at most one message every 100 ms, with the latest value winning, so calling it every frame is fine. The returned promise resolves as soon as the value is queued, and a failure to deliver it is ignored. `loadingStart` resets the progress; `loadingStop` drops any value still waiting.

The portal records `loadingStop` so it can separate load time from play time, and the [Preview tool](https://www.zokogames.com/preview) ticks it off. See [first frame fast](https://docs.zokogames.com/guides/first-frame).

<!-- docs-sample: uses assets, loadAsset -->
```js
await SDK.game.loadingStart();
for (let i = 0; i < assets.length; i++) {
  await loadAsset(assets[i]);
  SDK.game.loadingProgress(((i + 1) / assets.length) * 100);
}
await SDK.game.loadingStop();
```

## Happy moments

```ts
happytime(): Promise<void>
```

Call it at moments of celebration: a boss defeated, a record broken, a level three-starred. The portal answers with a short confetti celebration over the game and records a `happytime` event. If today's daily puzzle list includes your game, a happy moment also counts as a win for the player's daily streak (once per game load, and ignored in the first two seconds after the game starts). Use it sparingly, a handful of times per session at most. Errors: only the general ones.

## Completion

```ts
reportGameCompletedPercentage(percentage: number): Promise<void>
```

Reports how far through the game the player is, from 0 to 100. A value outside that range, a non-number, or `NaN` rejects with `invalidArgument`. Send it when it changes meaningfully (after a level), not on every frame. The portal does not store the number itself. A value of 100 counts as a win for the daily streak in the same way as `happytime` (see above); lower values have no visible effect.

<!-- docs-sample: uses level, totalLevels -->
```js
await SDK.game.reportGameCompletedPercentage(Math.round((level / totalLevels) * 100));
```

## Game context

```ts
setGameContext(context: Record<string, string | number | boolean>): Promise<void>
clearGameContext(): Promise<void>
```

A flat bag of values describing what the player is doing (current mode, level, difficulty). Values must be strings, numbers or booleans; nesting, arrays or any other value type reject with `invalidArgument`. Each call replaces the previous context. Use `clearGameContext()` when the player returns to a menu. The portal attaches the current context to the report when the player sends feedback or reports a problem, so your support team can see where they were. It keeps at most 30 entries (the first 30 in object order), cuts keys to 60 characters and string values to 200 characters, skips an entry that would take keys and values over 4,000 characters in total, drops the keys `__proto__`, `constructor` and `prototype`, and does not show it anywhere else. `NaN`, `Infinity`, `null`, `undefined`, objects and arrays are not accepted: the SDK rejects the call with `invalidArgument`. Calls over the limit (30 in a burst, 10 a second) are dropped but the newest context is applied once the limit refills.

```js
await SDK.game.setGameContext({ mode: "time-trial", level: 7, hard: false });
```

## Portal settings

```ts
readonly settings: { disableChat: boolean; muteAudio: boolean; kidsMode?: boolean }
addSettingsChangeListener(fn: (settings: GameSettings) => void): () => void
removeSettingsChangeListener(fn: (settings: GameSettings) => void): void
```

The portal owns these player preferences. `settings` returns a copy of the current values (synchronous). Apply them at start and listen for changes.

<!-- docs-sample: uses audio, chatPanel -->
```js
function applySettings(s) {
  audio.setMuted(s.muteAudio);
  chatPanel.hidden = s.disableChat;
}
applySettings(SDK.game.settings);
SDK.game.addSettingsChangeListener(applySettings);
```

If your game has chat or user-generated text, honour `disableChat` fully. That is a [multiplayer](https://docs.zokogames.com/requirements/multiplayer) requirement. `addSettingsChangeListener` throws `invalidArgument` if the argument is not a function; `removeSettingsChangeListener` ignores a function that was never added. The portal sends a change event when the player toggles a setting while the game is open; the listener receives a fresh copy.

In local mode the starting values come from `?disableChat=true`, `?muteAudio=true` and `?kidsMode=true` on the page address (`kidsMode=true` also sets `disableChat`, as on the portal; without it `kidsMode` is `false`), and they do not change by themselves. To test a live change, dispatch the window event `zokogames:local-settings` with `detail` set to any of `{ disableChat, kidsMode, muteAudio }` as booleans (SDK 1.5.1): the SDK updates `settings` and calls your settings listeners (`kidsMode: true` also turns `disableChat` on). The [Preview tool](https://www.zokogames.com/preview) can also send changes.

### Kids mode

Available from SDK 1.5.0. The portal already sends the field on every game, and an older SDK build copies the whole settings object it receives, so on 1.4.1 `settings.kidsMode` is there at run time too, only missing from the type definitions. `settings.kidsMode` is `true` when the game runs in kids mode: the game has the kids flag, or the player is in kids mode (the portal's kids area, or kids mode switched on for the device). Otherwise it is `false`. In kids mode there is no chat, no rooms or invites, no sign-in prompt and no personalised ads, so hide any of those your game shows. The portal sets `disableChat` to `true` in exactly the same cases, so where `kidsMode` is missing (`undefined`, for example an older SDK in local mode) fall back to `disableChat`:

```js
const isKids = (s) => s.kidsMode ?? s.disableChat;
```

The portal sends no separate change event for kids mode: if kids mode is switched on while a game is open, the portal reloads the game, which then starts with `kidsMode: true`; switching it off applies the next time the game loads. Room calls in kids mode fail with `roomUnavailable`, and the platform's realtime servers refuse rooms for kids games as well. Everything else the portal switches off is listed in [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Offline state

```ts
readonly isOffline: boolean
addOfflineListener(fn: (offline: boolean) => void): () => void
removeOfflineListener(fn: (offline: boolean) => void): void
```

Added in SDK 1.2.0. `isOffline` is `true` while the player has no connection, including when the game was launched from the [offline library](https://docs.zokogames.com/guides/offline-play). The portal keeps it current, and listeners receive the new value only when it changes. On a portal that does not send the flag it stays `false`. In local mode it mirrors `navigator.onLine`, and `?offline=true` on the page URL pins it to `true`. `addOfflineListener` throws `invalidArgument` if the argument is not a function.

While offline the portal answers `requestAd` with `unfilled` straight away and `requestBanner` with `bannersDisabled`, so the game carries on without an ad.

<!-- docs-sample: uses leaderboardButton -->
```js
function showNetwork(offline) {
  leaderboardButton.hidden = offline;
}
showNetwork(SDK.game.isOffline);
SDK.game.addOfflineListener(showNetwork);
```

On older SDK versions use `navigator.onLine` with the `online` / `offline` window events instead; see [Making a game playable offline](https://docs.zokogames.com/guides/offline-play).

## Rooms and invites

For games that play together. Read the [multiplayer requirements](https://docs.zokogames.com/requirements/multiplayer) first.

```ts
readonly isInstantMultiplayer: boolean
readonly inviteParams: Record<string, string> | null
getInviteParam(key: string): string | null
updateRoom(update: { roomId?: string; isJoinable?: boolean; isPublic?: boolean; inviteParams?: Record<string, string> }): Promise<void>
leftRoom(): Promise<void>
inviteLink(params: Record<string, string>): Promise<string>
addJoinRoomListener(fn: (params: InviteParams) => void): () => void
removeJoinRoomListener(fn: (params: InviteParams) => void): void
```

- **`showInviteButton` / `hideInviteButton` and the invite button.** The old forms (no options) are the deprecated aliases of `updateRoom({ isJoinable: true, inviteParams })` and `updateRoom({ isJoinable: false })` and behave exactly as before: the portal's **Invite friends** button follows the room. From SDK 1.7.0, `showInviteButton(params, { portalOnly: true })` asks the portal to show its invite button and to put `params` in the link it shares, **without creating or changing a room**, and resolves the same link `inviteLink(params)` returns (same checks and limits on `params`, `invalidArgument` if it is not a flat object of strings). `hideInviteButton({ portalOnly: true })` hides the button again and leaves the room and its `isJoinable` alone, even in a game the portal lists as multiplayer. The ask lasts until the game asks again, until a later `updateRoom` that sets `isJoinable` hands the button back to the room, or until the game reloads. In kids mode the portal shows no invite button: `portalOnly` calls resolve nothing to show and `showInviteButton` rejects with `unexpectedError` like `inviteLink`. Without a signed-in player the button shares the link directly; rooms still need sign-in.
- **`isInstantMultiplayer`** is true when the portal page address has `instantJoin=true` (a "play together" entry) and the player should go straight into a lobby instead of a menu. `isInstantJoin` is the deprecated old name. `showInviteButton(params)` (equivalent to `updateRoom({ isJoinable: true, inviteParams: params })`, and it resolves the invite link) and `hideInviteButton()` (equivalent to `updateRoom({ isJoinable: false })`) are deprecated.
- **`inviteParams`** holds the query parameters of the portal game page the player opened, as strings: the portal's own keys (`roomId`, `instantJoin`, `ref`, `utm_*`) and the flat keys your game put in `updateRoom` or `inviteLink` (the docs use `room`), or `null` when none survive. Other parameters are not passed on. Because `ref` and `utm_*` also arrive on ordinary visits from campaigns, a non-null `inviteParams` does not mean an invite. To tell an invite from a plain launch, read a key your game set (`getInviteParam("room")`) or `roomId`, or check `isInstantMultiplayer` for a "play together" entry. The portal drops parameters that look like credentials (keys such as `token`, `code` or `state`, or token-shaped values) and values over 256 characters; see [what survives the page](https://docs.zokogames.com/guides/multiplayer-invites). Use `getInviteParam("room")` for a single value.
- **`updateRoom`** announces the room you are in. Call it when the player creates or joins a room and again when it changes (full, started). `isJoinable: false` stops the portal offering the invite. `inviteParams` is what a friend's join listener will receive. All values must be strings; `roomId` must be a string, `isJoinable` and `isPublic` booleans, and `update` an object, otherwise the call rejects with `invalidArgument`. `isJoinable` stays as it was if you omit it (a new room starts joinable). If you omit `roomId` the portal generates one; ids are limited to letters, digits, `_`, `.` and `-` (other characters become `_`, 64 characters at most), and the id is always added to `inviteParams` as `roomId`. Rooms and presence need a signed-in player: for guests the call succeeds but nothing is announced. From SDK 1.6.0 the host can also send `isPublic: true` so friends can join the room from their friends list without an invite; rooms are private by default, only the host's value counts, and in kids mode rooms always stay private. The portal accepts at most 16 invite parameters, with keys of 1 to 40 characters from letters, digits, `_`, `.` and `-` (but not `__proto__`, `constructor` or `prototype`) and values of up to 200 characters. A map that breaks any of these limits is ignored silently: the call does not reject, and the invite carries only `roomId` and any parameters from an earlier valid call. Keep parameters small, such as a room code or a level id, and test them in the Preview tool.
- **`leftRoom`** clears the room. Call it when the player leaves the lobby or match.
- **`inviteLink`** returns a promise of a link to the portal's game page (the address in the player's browser bar, `https://<portal>/game/<slug>`, not the game frame's own address) with your parameters added as query parameters. Any query string or hash on the current portal page is not copied; only your parameters are. `params` must be a flat object of strings (`invalidArgument` otherwise). Show it in a "copy invite link" button. Stay within the same limits as `updateRoom`: the link is built as given, but the page that opens it keeps a parameter only when its key has at most 64 characters from the same set and its value at most 256 characters (30 keys at most), and drops the others silently.
- **`addJoinRoomListener`** fires when the player is already in your game and accepts an invite; it also updates `inviteParams` to the new values. Parse the params and move them into the room. See the [friend invite flow](https://docs.zokogames.com/guides/multiplayer-invites#the-friend-invite-flow).

<!-- docs-sample: uses joinRoom, network, copyButton -->
```js
SDK.game.addJoinRoomListener((params) => joinRoom(params.room));

async function createRoom() {
  const room = await network.create();
  await SDK.game.updateRoom({ roomId: room.id, isJoinable: true, inviteParams: { room: room.id } });
  copyButton.onclick = async () => navigator.clipboard.writeText(await SDK.game.inviteLink({ room: room.id }));
}

if (SDK.game.inviteParams?.room) joinRoom(SDK.game.inviteParams.room);
```

## Room data channel

Added in SDK 1.3.0. `SDK.game.room` lets the players of one room exchange small messages and share a tiny state through the platform, so a multiplayer game does not need its own server for simple cases. It is a **game data channel, not a text chat**: it is not moderated or logged as chat, it has no history, and `settings.disableChat` does not switch it off (it only governs the text your game shows). Do not use it to carry free text between players; if you do, the [chat moderation rules](https://docs.zokogames.com/requirements/multiplayer#chat-and-user-content) apply to your game. For a step-by-step walkthrough with a lobby, turns and reconnects, see [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms). The channel exists while the player is in a room, that is after `updateRoom(...)` (or after joining from an invite) and until `leftRoom()`. It needs a signed-in player and a portal with realtime enabled; otherwise calls fail with `roomUnavailable`.

```ts
readonly room: {
  send(data: unknown, options?: { to?: string }): Promise<void>
  onMessage(cb: (m: { from: string; data: unknown; direct: boolean; seq: number; ts: number }) => void): () => void
  setState(patch: Record<string, unknown>): Promise<void>
  getState(): Record<string, unknown>
  onState(cb: (state: Record<string, unknown>, change: { keys: string[]; rev: number; by?: string }) => void): () => void
  members(): Array<{ id: string; username: string; profilePictureUrl: string }>
  onMembers(cb: (members: Array<{ id: string; username: string; profilePictureUrl: string }>) => void): () => void
  isHost(): boolean
  onHostChange(cb: (hostId: string | null, isHost: boolean) => void): () => void
  onError(cb: (error: { code: string; message: string }) => void): () => void
  // The same five listeners in the add/remove form used by the rest of the SDK:
  addMessageListener(cb: (m: RoomMessage) => void): () => void
  removeMessageListener(cb: (m: RoomMessage) => void): void
  addStateListener(cb: (state: Record<string, unknown>, change: RoomStateChange) => void): () => void
  removeStateListener(cb: (state: Record<string, unknown>, change: RoomStateChange) => void): void
  addLeftListener(cb: (event: { reason: "left" | "kicked" | "closed" | "disconnected"; roomId?: string }) => void): () => void
  removeLeftListener(cb: (event: { reason: "left" | "kicked" | "closed" | "disconnected"; roomId?: string }) => void): void
  addMembersListener(cb: (members: RoomMember[]) => void): () => void
  removeMembersListener(cb: (members: RoomMember[]) => void): void
  addHostChangeListener(cb: (hostId: string | null, isHost: boolean) => void): () => void
  removeHostChangeListener(cb: (hostId: string | null, isHost: boolean) => void): void
  addErrorListener(cb: (error: SdkError) => void): () => void
  removeErrorListener(cb: (error: SdkError) => void): void
  readonly selfId: string | null
}
```

- **`send(data, { to })`** relays any JSON value to every other member of the room, or only to the member whose `id` you pass as `to`. You never receive your own messages. It resolves when the portal accepted the call; delivery is best effort (no acknowledgement, no replay for a player who was disconnected). `data` must be JSON-serializable and at most **8 KB** once serialized, otherwise it rejects with `payloadTooLarge` (or `invalidArgument`).
- **`onMessage(cb)`** receives `{ from, data, direct, seq, ts }`. `from` is the sender's platform id and is **set by the platform, never by the sender**, so you can trust it for "who sent this". `seq` increases for every message in the room (gaps are possible, order by it) and `ts` is the server time in milliseconds. `direct` is true when it was sent to you alone. Every `on*` method returns a function that removes the listener. Each one also has an `add<Thing>Listener(cb)` / `remove<Thing>Listener(cb)` pair (`addMessageListener`, `addStateListener`, `addMembersListener`, `addHostChangeListener`, `addErrorListener`), the same convention as `addSettingsChangeListener` and `addJoinRoomListener`; pass the same function to `remove...` that you passed to `add...`. Both forms do the same thing, use whichever you prefer.
- **Shared state.** The room keeps a small key-value state, at most **64 KB** in total. Only the **host** can change it: `setState(patch)` merges the keys of `patch` into the state, and a `null` value removes a key. Keys are 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. The change is applied when the platform confirms it: read it from `getState()` or `onState`, not straight after `await setState(...)`. A player who joins, or reconnects, receives the full current state first. When your game page reloads while the portal still holds the player's room, the SDK picks the room up again at start-up: `members()`, `selfId` and `getState()` fill in shortly after `init()` resolves, without a new `updateRoom` call and without calling your `onMembers` or `onState` listeners for that first restore, so read them once after start-up instead of waiting for an event. A non-host that calls `setState` gets `notHost`; a patch that would push the state over 64 KB is refused with `stateTooLarge`. The state is deleted when the last player leaves.
- **Members and host.** `members()` lists the players in the room including yourself (`selfId` is your own id). The **first player to join is the host**. When the host leaves, the longest-standing remaining member becomes host and `onHostChange` fires on every client with the new host id (it also fires for the first assignment). The shared state survives a host change.
- **Errors.** A call can fail at once (it rejects) or later (the platform reports it through `onError`, for example `rateLimited`, `notHost` or `unknownMember`).

| Code | Meaning |
| --- | --- |
| `notInRoom` | The player is not in a room yet. Call `updateRoom` first. |
| `notHost` | Only the host can change the shared state. |
| `payloadTooLarge` | A message or patch is larger than 8 KB. |
| `stateTooLarge` | The shared state would exceed 64 KB. |
| `unknownMember` | `to` is not a member of the room (or is yourself). |
| `rateLimited` | More than 10 calls a second from the game (after a burst of 30), or more than 20 messages per second on the relay. The excess messages are dropped; **repeated** abuse (10 rejected messages within 10 seconds) closes the player's realtime connection, which then reconnects with a back-off and rejoins the room. |
| `roomUnavailable` | Guest, realtime is not enabled on this portal, or the account has no 13+ birthday (rooms never open in kids mode). |
| `invalidArgument` | A bad argument, such as data that cannot be serialized or an invalid state key. |

**Limits at a glance:** 8 KB per message or patch, 20 messages per second per player on the relay (a burst of 20 is allowed), 64 KB of shared state, and as many players as the lobby size you entered at upload (at most 100). The game page also limits how fast your code may call: `room.send` and `room.setState` each accept a burst of 30 calls and then 10 a second, and a call over that is rejected with `rateLimited` before it reaches the relay, so stay below 10 messages a second on average and batch small updates into one message. Nothing is stored after the room ends and message contents are not logged.

Every member of `SDK.game.room` (all since SDK 1.3.0). Members that read state are synchronous; all of them throw `sdkNotInitialized` or `sdkDisabled` as the rest of the module does.

| Member | Returns | Can fail with |
| --- | --- | --- |
| `send(data, options?)` | `Promise<void>`, when the portal accepted the call. | Rejects at once with `invalidArgument` (data not JSON, `undefined`, or `to` not a non-empty string), `payloadTooLarge`, `notInRoom`, `roomUnavailable`. Later, through `onError`: `unknownMember` (`to` is a string but not a member of the room, or is yourself), `rateLimited`. |
| `setState(patch)` | `Promise<void>`. The state changes when the platform confirms it. | Rejects at once with `invalidArgument` (empty patch, a bad key, or `__proto__`, `constructor`, `prototype` as a key), `payloadTooLarge` (patch over 8 KB), `notHost`, `notInRoom`, `roomUnavailable`. Later, through `onError`: `stateTooLarge`, `notHost`, `rateLimited`. |
| `getState()` | A copy of the shared state; `{}` outside a room. | Throws only the general codes. |
| `members()` | A copy of the member list, yourself included; `[]` outside a room. | Throws only the general codes. |
| `isHost()` | `true` when this player is the host. | Throws only the general codes. |
| `selfId` | This player's platform id, or `null` outside a room. | Throws only the general codes. |
| `onMessage(cb)`, `addMessageListener(cb)`, `removeMessageListener(cb)` | `on*` returns a function that removes the listener; since SDK 1.6.4 `add*` returns the same function (it returned nothing before), and `remove*` returns nothing. | Throws `invalidArgument` when `cb` is not a function. |
| `onState`, `onMembers`, `onHostChange`, `onError` and their `add...Listener` and `remove...Listener` forms | The same as for messages. | The same as for messages. |

Registering the same function twice with `add...Listener` registers it once. Callbacks receive copies, so changing them does not change the SDK's state.

A complete example (cursors, a host-owned round counter and a direct reply):

<!-- docs-sample: uses showRound, slowDown, pointer -->
```js
const SDK = window.ZokoGames.SDK;
await SDK.init();
const room = SDK.game.room;
const cursors = new Map(); // player id -> { x, y }
let round = 0;

await SDK.game.updateRoom({ roomId: "lobby-1", isJoinable: true }); // joining a room starts the channel

room.onMembers((members) => {
  for (const id of cursors.keys()) if (!members.some((m) => m.id === id)) cursors.delete(id);
});
room.onHostChange((hostId, me) => {
  if (me) room.setState({ round: round + 1 }).catch(console.warn); // the new host keeps the game going
});
room.onState((state) => { round = Number(state.round ?? 0); showRound(round); });
room.onMessage(({ from, data, direct }) => {
  const msg = /** @type {{ type: string, x?: number, y?: number }} */ (data); // whatever the sender sent
  if (msg.type === "cursor") cursors.set(from, { x: msg.x, y: msg.y });
  if (msg.type === "ping" && direct) room.send({ type: "pong" }, { to: from });
});
room.onError(({ code }) => {
  if (code === "rateLimited") slowDown(); // stay below 20 messages per second
});

setInterval(() => {
  // 5 sends per second stays well inside the 10 per second the portal accepts; the sender is added by the platform
  room.send({ type: "cursor", x: pointer.x, y: pointer.y }).catch(() => {});
}, 200);

if (room.isHost()) await room.setState({ round: 1, map: "forest" });
```

The module build exports the types `GameApi`, `GameContext`, `RoomApi`, `RoomMessage`, `RoomSendOptions`, `RoomStateChange`, `RoomMember`, `InviteParams`, `RoomUpdate` and `GameSettings`, and the code type `RoomErrorCode`.

**Kids mode.** `send` and `setState` reject with `roomUnavailable`, `updateRoom` and `leftRoom` resolve and announce nothing, `inviteLink` rejects with `unexpectedError`, and the room reads as empty; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Reporting chat

Added in SDK 1.4.0. If your game shows text from other players, give them a way to report it. `reportChat` sends one message to the portal's moderators:

<!-- docs-sample: uses member, lastLines -->
```js
await SDK.game.reportChat({
  reportedName: "Player42",          // 1 to 40 characters
  message: "the reported text",      // 1 to 500 characters
  reason: "abuse",                   // "abuse" | "spam" | "cheating" | "other"
  reportedUserId: member.id,         // optional: the platform id, for example a room member id
  roomId: "room-7",                  // optional, at most 64 characters
  context: lastLines,                // optional: [{ name, text }], the newest 10 lines are kept
});
```

The portal relays the call to `POST /api/sdk/chat-report`, which is same-origin only and takes the game from the portal frame, never from your data. Guests may report; each player can send 5 reports per 10 minutes and 30 per day, and an identical report within 10 minutes is accepted without a new row. In kids mode the report is accepted without recording who sent it.

| Error code | When |
| --- | --- |
| `invalidArgument` | A field is missing or out of range: a text that is empty or only spaces, a `reason` outside the four listed, a `reportedUserId` over 128 characters, a `context` that is not an array of `{ name, text }` lines. Checked in the SDK before anything is sent. |
| `rateLimited` | The player reported too often. |
| `unexpectedError` | The portal could not take the report, did not answer in time, or is too old to know the call. |

`reportChat` is not a replacement for your own filters; see the [chat rules](https://docs.zokogames.com/requirements/multiplayer#chat-and-user-content).

`reportedName` and `message` are supplied by your game and are shown to moderators as unverified, so send the text exactly as the player saw it. `reportedUserId` must be a real player id from the SDK (for example a room member id); an id the portal does not know is not stored. Per game the portal also allows 20 reports per 10 minutes and 100 per day from one network address, and 300 per hour and 2,000 per day in total; a report over a limit is refused with `rateLimited`. Format and bidirectional control characters are stripped from the text and the names.

## Feedback screenshot

Added in SDK 1.4.0. When a player opens the portal's feedback form, the portal may ask your game for an image of the current screen so the player can attach it. The SDK answers for you:

```js
const stop = SDK.game.onScreenshotRequest(async () => {
  // return a Blob, an HTMLCanvasElement, an image data URL, or null for "no image"
  return document.querySelector("canvas");
});
```

- The SDK scales the image so the long edge is at most **1280 px**, encodes JPEG at falling quality until it is at most **1.5 MB**, and answers within **3 seconds** (a slow or failing handler counts as no image). The portal checks the type and size again.
- One handler is active; a second call replaces it. The returned function removes it.
- **Without a handler** the SDK tries the largest visible `<canvas>` on the page. A tainted canvas yields no image. A WebGL canvas only works when it was created with `preserveDrawingBuffer: true` (otherwise it reads back blank, which counts as no image). If your engine cannot set that, register a handler that renders a frame first.
- **Unity WebGL needs a handler**: the canvas is not readable between frames. Capture at the end of the frame and pass the pixels on (helper below).
- Nothing is sent unless the player opens the form and chooses to attach the image.

Unity helper (WebGL): grab the frame in a coroutine, encode it, and hand the data URL to the page. Register the handler once from a `.jslib` or `Application.ExternalEval` that calls `SDK.game.onScreenshotRequest(() => window.__zokoShot ? window.__zokoShot() : null)`, where `__zokoShot` returns the last data URL the C# side stored:

```csharp
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;

public class ZokoScreenshot : MonoBehaviour
{
    [DllImport("__Internal")] static extern void ZokoSetScreenshot(string dataUrl);

    // Call from a UI button or every few seconds while a menu is open; the SDK scales it down.
    public void Capture() => StartCoroutine(CaptureAtEndOfFrame());

    IEnumerator CaptureAtEndOfFrame()
    {
        yield return new WaitForEndOfFrame();
        var tex = ScreenCapture.CaptureScreenshotAsTexture();
        var jpg = tex.EncodeToJPG(75);
        Destroy(tex);
        ZokoSetScreenshot("data:image/jpeg;base64," + System.Convert.ToBase64String(jpg));
    }
}
```

<!-- docs-sample: fragment -->
```js
// ZokoScreenshot.jslib
mergeInto(LibraryManager.library, {
  ZokoSetScreenshot: function (ptr) { window.__zokoShot = UTF8ToString(ptr); },
});
```

The player chooses whether to attach the screenshot to a report. It is stored privately, shown only to the studio and the platform staff, and deleted after 180 days. It is never requested in kids mode. The portal accepts an image of at most 1.5 MB with each side between 16 and 4096 px and refuses anything else.

**Common mistakes.** The ones reviewers and the Preview checklist report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| `gameplayStart()` is called at page load, or never | **First gameplayStart within 20 seconds** shows **Recommended** (it must come within 20 seconds of the frame loading), or **gameplayStart called** stays on **Waiting for you to play**, and playtime is wrong | Call it when the first level is live, and `gameplayStop()` at every pause, menu and before ads. |
| `gameplayStart()` is not called again after an ad or a pause | The Preview checklist warns "resume after an ad" and playtime stops counting | Call it in every resume path. |
| `loadingProgress` is called with `0` to `1` instead of `0` to `100` | A bar stuck near zero | Pass a percentage from 0 to 100. |
| `loadingStart()` is called after the game is already playable | A loading bar over a running game | Call it at the start of loading, and `loadingStop()` when it ends. |
| `setGameContext` gets a nested object or an array | `invalidArgument` | Use a flat object of strings, finite numbers and booleans. |
| `settings.disableChat` or `kidsMode` is read once at start | Chat stays on after the player turns it off | Apply `settings` at start and again in `addSettingsChangeListener`. |
| `inviteParams !== null` is used to detect an invite | True for ordinary visits from a campaign (`ref`, `utm_*`) | Read a key your game set, such as `getInviteParam("room")`. |
| `updateRoom` is given a nested object, a number, or more than 16 parameters | `invalidArgument`, or the whole map is silently ignored by the portal | Flat string values, at most 16 keys, keep each value short. |
| `room.send` runs on every frame | `rateLimited` and dropped messages | Send at most a few messages a second, and batch updates. |
| `room.setState` is called by every player | `notHost` for everyone but the host | Check `room.isHost()` and let the host own the shared state. |
| `room.send` is called before `updateRoom` | `notInRoom` | Call `updateRoom` first, and use the channel only while the player is in a room. |
| Chat text is shown but there is no way to report it | Review rejects unmoderated free text | Call `reportChat` from a "report" button on every message from another player. |
| `inviteParams` is modified in place | The SDK's own copy changes too | Treat it as read-only and copy it first. |

## In local mode

| Member | Local behaviour |
| --- | --- |
| `gameplayStart`, `gameplayStop`, `loadingStart`, `loadingProgress`, `loadingStop`, `reportGameCompletedPercentage`, `setGameContext`, `clearGameContext`, `leftRoom` | Resolve with nothing; the mock records nothing and draws no loading bar. Arguments are still validated. |
| `updateRoom` | Resolves with nothing and, for a signed-in mock player, joins the local room channel (below). |
| `room` | Tabs of the same origin that called `updateRoom` with the same `roomId` (default `local-room`, or the `roomId` of the page address) are connected through a `BroadcastChannel`: open the game in two tabs to test messages, targeting, the shared state and host migration without the portal. Each tab is its own member (`<user id>:<tab id>`) and the tab that joined first is the host; `seq` counts what that tab received. The 8 KB, 20 per second and 64 KB limits and the error codes are the same as on the portal. There is no lobby-size limit. |
| `reportChat` | Validates, logs the report to the console and resolves; nothing is sent. |
| `onScreenshotRequest` | The handler is kept. Test it by dispatching `new CustomEvent("zokogames:local-screenshot", { detail: { respond: console.log } })` on `window`; `respond` receives `{ dataUrl }` or `{ none: true }`. |
| `happytime` | Shows a yellow "Happy time!" toast for 1.5 seconds. |
| `settings` | From `?disableChat=`, `?muteAudio=` and `?kidsMode=` (which also turns `disableChat` on); changes only when the page dispatches `zokogames:local-settings` (SDK 1.5.1). |
| `isOffline` | Mirrors `navigator.onLine`; `?offline=true` pins it to `true`. The offline listeners fire on the browser's `online` and `offline` events, or when the page dispatches `zokogames:local-offline` with `detail: { offline: true }` (ignored under `?offline=true`). |
| `inviteParams` | `null` only when the page address has no query string at all. Otherwise it holds **every** query parameter, including mock switches such as `useLocalSdk` or `sdk_debug`; the real portal passes on only its own keys and your game's flat keys (see above). Read the keys you expect with `getInviteParam`, never test `inviteParams !== null` to detect an invite. |
| `isInstantMultiplayer` | `true` only with `?instantJoin=true` on the address. |
| `inviteLink` | Your own page address (the local page, not a portal address) with your parameters set as query strings. Unlike the portal, it keeps every query parameter already on the page address, so a link made on `?sdk_debug=true` carries that too. It resolves as a promise like the real call. |
| `showInviteButton(params, { portalOnly: true })` / `hideInviteButton({ portalOnly: true })` | Log the request to the console; there is no portal button to change. `showInviteButton` still resolves the local `inviteLink`. |
| `room.addLeftListener` | Fires when the page dispatches the window event `zokogames:local-leave-room` with `detail: { reason }` (`left`, `kicked`, `closed` or `disconnected`; anything else reads as `left`) while the local room is joined. The local room is left first, so `onMembers` listeners see an empty room. |
| `addJoinRoomListener` | Fires when the page dispatches the window event `zokogames:local-join-room` with a flat object of strings as `detail` (SDK 1.5.1), and then updates `inviteParams`. Test the full join path in the [Preview tool](https://www.zokogames.com/preview). |

## When the player is a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Basic launch | Everything in this module works as in full launch. `gameplayStart` and `gameplayStop` are what the portal counts: plays and play time for the launch metrics come only from them (see the basic launch metrics guide). |
| Guest | Everything above works. Rooms and presence need a signed-in player: `updateRoom`, `leftRoom` and friend invites succeed but announce nothing, and `room.send` / `room.setState` fail with `roomUnavailable`. `inviteLink` works and the link can be shared by hand. |
| Offline | `isOffline` is `true`; ads are `unfilled` and banners `bannersDisabled`. Gameplay and loading calls still resolve. |
| Ad blocked or ad-free | No effect on this module. |

Full runnable example of the start-up order:

<!-- docs-sample: uses loadEverything, startFirstLevel -->
```js
await SDK.init();
await SDK.game.loadingStart();
await loadEverything();
await SDK.game.loadingStop();
startFirstLevel();
await SDK.game.gameplayStart();
```

## Next steps

- [User module](https://docs.zokogames.com/sdk/user)
- [Data (cloud save)](https://docs.zokogames.com/sdk/data)
