# Cocos

The Cocos package (`packages/sdk-engines/cocos`) is a promise-based TypeScript wrapper over `window.ZokoGames.SDK` for **Cocos Creator 3.x**. Names match the JavaScript SDK one to one (`ZokoSDK.game.gameplayStart()`). In the Creator editor, in native builds, or when the SDK script cannot be loaded in a browser, a built-in simulator answers so the game keeps running. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.1): the module and the example type-check in TypeScript strict mode against the official engine declarations of Cocos Creator 3.8.8 (`@cocos/creator-types`), and command-line web builds (web-desktop and web-mobile) of Cocos Creator 3.8.8 ran in a real browser (2026-11-23); the editor Preview mode was not used. Send the Creator version and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails. The JavaScript SDK underneath is the tested part. Release 1.7.1 only adds a script-load timeout and is covered by unit tests; it was re-run in the engine and on production on 2026-11-23 (12 areas).

## Install

Download the Cocos Creator plugin: [/sdk-engines/zokogames-cocos-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-cocos-1.7.1.zip) (the same files as the folder in the repository).

[/sdk-engines/cocos.zip](https://www.zokogames.com/sdk-engines/cocos.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Copy `assets/zokogames/` (`ZokoSDK.ts`, `ZokoClient.ts`, `ZokoTypes.ts`, `ZokoSimulator.ts`, and `examples/ZokoStoreExample.ts`) into your project's `assets/` folder.
2. Paste the contents of `build-templates/zokogames-sdk-snippet.html` (one script tag for `https://sdk.zokogames.com/zokogames-sdk-v1.js`) into the `<head>` of your build templates, `build-templates/web-desktop/index.ejs` and `build-templates/web-mobile/index.ejs`, before the engine starts. Creator renders `index.ejs` files in `build-templates/<platform>/` instead of its default page; if your project has none yet, generate the default ones first as described on the "Custom Project Build Template" page of the Creator manual, then add the tag. A plain `index.html` in that folder would be copied over the rendered page and goes stale when Creator updates its template, so edit `index.ejs`. If the tag is missing, the module injects the script on the first `init()`, but the upload validator looks for the tag, so add it.
3. `import ZokoSDK from "./zokogames/ZokoSDK";` (a named `{ ZokoSDK }` import also works) and call `await ZokoSDK.init()` once at startup.

## Which path

| You are | Do this |
| --- | --- |
| A Cocos hobbyist or small team with a web build | Copy the folder, paste the snippet, wrap ad and save calls as below, build Web Mobile, upload. |
| Writing plain TypeScript tests | Use `ZokoClient.ts` (no engine imports) instead of `ZokoSDK.ts`, which imports `cc`. |

## A working component

One component in your first scene covering init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```ts
import { _decorator, Component, game } from "cc";
import ZokoSDK from "./zokogames/ZokoSDK";
const { ccclass } = _decorator;

@ccclass("ZokoBoot")
export class ZokoBoot extends Component {
  private live = false;
  private adActive = false;

  async start() {
    try { await ZokoSDK.init(); } catch (e) { console.warn("ZokoGames init failed", e); }
    this.live = ZokoSDK.isAvailable;                       // initialised and not "disabled"
    if (!this.live) return this.beginGame();               // the game must run without the portal

    ZokoSDK.game.addSettingsChangeListener((s) => this.applyMute(s.muteAudio));
    this.applyMute(ZokoSDK.game.settings.muteAudio);
    const best = Number(ZokoSDK.data.getItem("best") ?? "0") || 0;   // load: synchronous
    this.beginGame(best);
  }

  // Wrap every ad call. game.pause() stops the main loop; resume in a finally so both outcomes resume.
  async showAd(type: "midgame" | "rewarded"): Promise<boolean> {
    if (!this.live) return false;
    let finished = false;
    try {
      await ZokoSDK.ad.requestAd(type, {
        adStarted: () => { this.adActive = true; game.pause(); },
        adFinished: () => { finished = true; },
        adError: (e) => console.log("no ad:", e.code),       // adCooldown, unfilled, adblock ...
      });
    } catch (e) {
      console.warn("ad call failed", e);                    // for example sdkDisabled
    } finally {
      if (this.adActive) { this.adActive = false; game.resume(); }
    }
    return finished;
  }

  async onRewardClicked() { if (await this.showAd("rewarded")) this.grantReward(); }   // reward only when finished
  async onRoundEnded(score: number) {
    this.onPlayStop();
    this.save(score);
    await this.submitScore(score);
    await this.showAd("midgame");                           // natural break
  }

  onPlayStart() { if (this.live) void ZokoSDK.game.gameplayStart().catch(() => {}); }
  onPlayStop()  { if (this.live) void ZokoSDK.game.gameplayStop().catch(() => {}); }

  save(score: number) {
    if (!this.live) return;
    try { ZokoSDK.data.setItem("best", String(score)); }     // synchronous; uploaded in the background
    catch (e) { console.warn((e as { code?: string }).code); } // dataLimitExceeded
  }

  async submitScore(score: number) {
    if (!this.live) return;
    try {
      const user = await ZokoSDK.user.getUser();
      if (!user) return;                                     // guests are not ranked
      // "" works only on a board WITHOUT an encryption key; see leaderboards for the encrypted form.
      await ZokoSDK.user.submitScore({ encryptedScore: "", score });
    } catch (e) { console.warn((e as { code?: string }).code); }
  }

  private applyMute(mute: boolean) { if (!this.adActive) { /* set your audio master volume: mute ? 0 : 1 */ } }
  private beginGame(_best = 0) {
    if (this.live) void ZokoSDK.game.loadingStop().catch(() => {});   // ends the portal's loading bar
    this.onPlayStart();
  }
  private grantReward() { /* ... */ }
}
```

On a web build the Cocos TypeScript runs in the page, where the Web Crypto API exists, so a keyed leaderboard is practical here: use the `encryptScore` function from the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission), passing `user.__dangerousUserId` and your game id, and send its result as `encryptedScore`. Keep in mind that a key shipped in the browser can be read; for real stakes compute scores on your server.

## State and simulator

<!-- search: headings-only -->

| Member | Meaning |
| --- | --- |
| `ZokoSDK.init()` | Once, first; safe to call twice. Does not reject for a missing script: the simulator takes over (see pitfalls). |
| `ZokoSDK.isInitialized`, `isAvailable`, `isSimulated`, `isSupportedPlatform` | Initialised; initialised and not disabled; the simulator is answering; running in a browser build. |
| `ZokoSDK.environment` | `"local"`, `"zokogames"` or `"disabled"`. |
| `ZokoSDK.isQaTool` | Running in the QA tool. |

`ZokoSDK.configureSimulator(options)` tunes the simulator; call it before `init()`. Options: `disabled`, `accountAvailable`, `loggedIn`, `username`, `userId`, `friendCount`, `adBehaviour` (`"fill"`, `"no_fill"` or `"error"`), `adDurationMs` (default 1500), `adblock`, `muteAudio`, `disableChat`, `kidsMode`, `instantMultiplayer`, `offline`, `storeAvailable`, `verbose`.

## Mapping

<!-- search: headings-only -->

Names are identical to JavaScript; calls return promises (the `data` calls are synchronous). Errors are plain `{ code, message }` objects.

| JavaScript | Cocos (TypeScript) |
| --- | --- |
| `SDK.init()` | `await ZokoSDK.init()` |
| `SDK.ad.hasAdblock()` | `await ZokoSDK.ad.hasAdblock()` |
| `SDK.ad.requestAd(type, cbs)` | `await ZokoSDK.ad.requestAd(type, { adStarted, adFinished, adError })`; resolves after the ad ended, and rejects (for example `sdkDisabled`) without calling `adError` when the call cannot start |
| `SDK.banner.requestBanner(...)` | `ZokoSDK.banner.requestBanner(...)` (needs a DOM container) or `ZokoSDK.banner.requestBannerForNode(id, node, size?)` |
| `SDK.banner.requestResponsiveBanner(id)`, `clearBanner(id)`, `clearAllBanners()` | `ZokoSDK.banner.requestResponsiveBanner(id)`, `ZokoSDK.banner.clearBanner(id)`, `ZokoSDK.banner.clearAllBanners()` |
| `SDK.game.*`, `SDK.user.*`, `SDK.data.*`, `SDK.store.*`, `SDK.analytics.*` | The same names (`game.loadingProgress`, `game.isOffline` with `addOfflineListener` / `removeOfflineListener`, invite params, `store.getPurchaseToken` included) |
| `SDK.achievements.*` | `ZokoSDK.achievements.list()`, `unlock(key)`, `onUnlock(cb)` (returns an unsubscribe function); see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.store`, `.ad`, `.banner`, `.user`, `.data`, `.room`, `.general` |

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `ZokoSDK.game.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, switch on `kidsMode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`ZokoSDK.game.room` passes straight through to the JavaScript `SDK.game.room`. It is `undefined` when the portal's SDK is older than 1.3.0 and in the built-in simulator, which has no room channel, so check it before use and test rooms in a web build. The methods are `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()` and `selfId`, with `onMessage`, `onState`, `onMembers`, `onHostChange` and `onError` (each returns an unsubscribe function) or the `add...Listener` and `remove...Listener` pairs.

```ts
async startMatch() {
  await ZokoSDK.init();
  await ZokoSDK.game.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = ZokoSDK.game.room;
  if (!room) return;                                   // simulator or an older SDK
  room.onMessage((m) => {
    const move = m.data as { cell: number; mark: string };   // data is typed unknown
    this.placeMark(move.cell, move.mark);
  });
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
  room.onError((e) => console.warn("room:", e.code));
}

onCellClicked(cell: number) { void ZokoSDK.game.room?.send({ cell, mark: "X" }); }
```

## Banners

Banners are drawn in the page, not in the canvas. Add a UI node with a `UITransform` where the banner should sit and let the module place a container over it. Request banners on menu scenes only.

```ts
await ZokoSDK.banner.requestBannerForNode("menu-banner", this.bannerSlot);            // largest size that fits
await ZokoSDK.banner.requestBannerForNode("menu-banner", this.bannerSlot, "300x250"); // a static size
await ZokoSDK.banner.clearBanner("menu-banner");
```

`ZokoSDK.rectOfNode(node)` returns the node's normalised rectangle for `ZokoSDK.banner.requestBannerForRect(id, rect, size?)`. A node without a `UITransform` fails with `invalidArgument`.

## Purchases

```ts
if (ZokoSDK.store.isAvailable) {
  try {
    const items = await ZokoSDK.store.getCatalogItems({ limit: 20 });
    const { itemId } = await ZokoSDK.store.buyItem(items[0].sku);
    const token = await ZokoSDK.store.getPurchaseToken();      // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}
```

Verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)). `examples/ZokoStoreExample.ts` is a ready component.

## Web export settings that matter

- **Build target:** **Web Mobile** or **Web Desktop**. Leave **Remote server address** empty: everything must ship in the zip, with relative paths.
- **No pre-compression.** Cocos does not write `.br` or `.gz`; upload the build as is. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but Cocos requests plain names, so renamed files would break. The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Size.** Use **Auto Atlas**, compressed texture formats (ETC2 or ASTC for mobile) and OGG or MP3 audio at modest bitrates. Split rarely used content into **Asset Bundles** loaded after the first scene. Disable unused engine modules in Project Settings > Feature Cropping. Remote bundles count toward the initial download only when fetched before the first frame.
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Set a design resolution and a resolution policy (Fixed Height or Show All) so the game fits every [required resolution](https://docs.zokogames.com/requirements/gameplay); `requestBannerForNode` assumes the canvas fills the page for exact placement.
- **Audio unlock.** Browsers keep audio suspended until the first tap or click. Start music from a "tap to play" screen, not in `start()`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so Cocos' own fullscreen call works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** Mobile browsers have small heaps; release unused bundles and avoid loading every scene's textures up front.
- **Loading.** Call `ZokoSDK.game.loadingStart()` before `director.preloadScene(name, (done, total) => void ZokoSDK.game.loadingProgress((done / total) * 100))`, and `loadingStop()` when the first scene runs.

Upload: build, zip the build folder **contents** so `index.html` is at the archive root, upload it in the developer console, and run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `sdk.game.reportChat(report)`, `sdk.game.onScreenshotRequest(handler)` and `sdk.data.mirrorLocalStorage({ prefix: "save_" })` (returns a stop function). `init()` registers a default provider that reads the game canvas at `Director.EVENT_AFTER_DRAW`; turn it off with `sdk.useDefaultScreenshots(false)` before `init()`. Cocos `sys.localStorage` is the browser `localStorage` on web, so it can be mirrored. The editor simulator validates the same limits.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`ZokoSDK.ad.requestAd("midgame", ...)`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `adError` with `adCooldown` until your game has called `ZokoSDK.game.gameplayStart()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoSDK.game.gameplayStart()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **In the Creator editor and in native builds** `ZokoSDK.isSimulated` is true. The simulator keeps cloud save in `localStorage` when available.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **A web preview or build on `localhost`** uses the real JavaScript SDK's [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. On another host without the portal around it, the environment is `disabled`, so calls reject with `sdkDisabled`; add `?useLocalSdk=true` to test.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded`.** The SDK script did not load (offline, blocked, or the build template snippet is missing).
- **`sdkNotInitialized`.** `await ZokoSDK.init()` first.
- **"Cannot find module `cc`".** You are running the file outside Creator; use `ZokoClient.ts` in plain TypeScript tests.
- **The simulator answers when the script is blocked.** In a browser, if `sdk.zokogames.com` is unreachable (offline, an extension), `init()` falls back to the simulator instead of failing, so fake ads and a fake player appear. In production that is harmless, but do not read it as proof the real SDK works; check `ZokoSDK.isSimulated` and `environment` in your test builds.
- **Banner node errors.** The node needs a `UITransform` and the canvas should fill the page.
- **Game stays paused after an ad.** Resume in a `finally`, as above.
- **Native builds.** Only the simulator exists; the real SDK is a web feature.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).
