# Phaser {#phaser}

Game Phaser chạy trong trình duyệt, nên bạn có hai cách vào. Dùng **plugin Phaser của ZokoGames** (`packages/sdk-engines/phaser`), plugin này tạm dừng vòng lặp game và âm thanh quanh quảng cáo giúp bạn, hoặc gọi trực tiếp [JavaScript SDK](https://docs.zokogames.com/vn/sdk/introduction). Cả hai dùng cùng các lệnh gọi, giới hạn và [mã lỗi](https://docs.zokogames.com/vn/sdk/introduction#errors). Các thuật ngữ như "midgame" và "rewarded" được giải thích trong [bảng thuật ngữ](https://docs.zokogames.com/vn/getting-started/glossary).

> [!NOTE]
> Trạng thái (1.7.1): đã chạy trong trình duyệt thật với Phaser 3.90.0 và 4.2.1 (2026-11-23). Hãy gửi phiên bản Phaser và lỗi chính xác tới [bộ phận hỗ trợ](https://docs.zokogames.com/vn/business/support) nếu lần import đầu tiên thất bại. JavaScript SDK bên dưới là phần đã được kiểm thử. Bản 1.7.1 (thời gian chờ tải script) đã chạy lại 2026-11-23 trong trình duyệt và trên production.

## Cài đặt {#install}

Tải plugin Phaser: [/sdk-engines/zokogames-phaser-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-phaser-1.7.1.zip) (cùng các tệp với thư mục trong kho mã).

[/sdk-engines/phaser.zip](https://www.zokogames.com/sdk-engines/phaser.zip) luôn là phiên bản mới nhất. Checksum: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Danh mục mọi gói engine kèm phiên bản, kích thước và SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

Hãy chọn hướng phù hợp với game của bạn.

| Bạn có | Hãy làm thế này |
| --- | --- |
| Một game Phaser đã hoàn chỉnh (JavaScript hoặc TypeScript) | Sao chép mã nguồn plugin vào dự án và đăng ký plugin (bên dưới), hoặc bỏ qua plugin và dùng [SDK thuần](#without-the-plugin). |
| Một game mới | Bắt đầu từ [bộ khởi đầu](https://docs.zokogames.com/vn/getting-started/starter-kits) `phaser`. Nó đã có plugin trong `src/zoko/`, bốn cảnh và một script `npm run package`. |

Plugin là TypeScript thuần trong `packages/sdk-engines/phaser/src/`: `ZokoPlugin.ts`, `ZokoClient.ts`, `ZokoAdFlow.ts`, `ZokoLoadingBridge.ts`, `ZokoSceneMixin.ts`, `types.ts` và một `index.ts` re-export chúng. Hãy sao chép thư mục (ví dụ vào `src/zokogames-phaser/`) và import từ đó. Bộ khởi đầu có cùng các tệp, đã định dạng, trong `src/zoko/` và không có `index.ts`, nên hãy import `./zoko/ZokoPlugin` ở đó. Peer dependency là `phaser ^3.80.0`; bản thân bộ khởi đầu ghim Phaser 4.2 và được kiểm tra kiểu và build với nó.

Bạn không cần thêm thẻ script: khi thiếu `window.ZokoGames`, plugin tự chèn `https://sdk.zokogames.com/zokogames-sdk-v1.js` (truyền `loadScript: false` để tắt). Thẻ script trong `index.html` vẫn tốt hơn, vì trình xác thực khi tải lên tìm URL của SDK (xem [xác thực build](https://docs.zokogames.com/vn/requirements/build-validation)):

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
```

## Một vòng lặp game hoạt động được với plugin {#a-working-game-loop-with-the-plugin}

Đây là một tệp bao gồm init, quảng cáo midgame, quảng cáo rewarded, bắt đầu và dừng gameplay, lưu và tải, và điểm bảng xếp hạng. Mọi lệnh gọi cổng đều được bọc để game cũng chạy khi SDK là `disabled` (xem [chế độ cục bộ](#test-locally)).

```ts
import Phaser from "phaser";
import { ZokoPlugin } from "./zokogames-phaser/ZokoPlugin";

// SDK calls must never break the game: swallow errors, return a fallback.
async function safe<T>(fn: () => Promise<T> | T, fallback: T): Promise<T> {
  try { return await fn(); } catch { return fallback; }
}

class Boot extends Phaser.Scene {
  constructor() { super("Boot"); }
  async create() {
    const z = this.zoko;                                   // available because of `mapping: "zoko"`
    await safe(() => z.ready(), null);                     // loads the script if missing, then SDK.init()
    const live = (() => { try { return z.sdk.environment !== "disabled"; } catch { return false; } })();
    this.registry.set("live", live);
    if (live) {
      await safe(() => z.sdk.game.loadingStart(), undefined);
      this.registry.set("best", Number(z.sdk.data.getItem("best") ?? "0") || 0);   // load: synchronous
      await safe(() => z.sdk.game.loadingStop(), undefined);
    }
    this.scene.start("Play");
  }
}

class Play extends Phaser.Scene {
  private score = 0;
  constructor() { super("Play"); }

  create() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    const start = () => { if (live) void safe(() => z.sdk.game.gameplayStart(), undefined); };
    const stop = () => { if (live) void safe(() => z.sdk.game.gameplayStop(), undefined); };
    start();                                               // input is live now, not at page load
    this.game.events.on("hidden", stop);
    this.game.events.on("visible", start);
    this.events.once("shutdown", () => {
      this.game.events.off("hidden", stop);
      this.game.events.off("visible", start);
      stop();
    });
    // ... spawn targets, call this.finish() when the round ends
  }

  async finish() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    if (!live) { this.scene.start("Play"); return; }
    await safe(() => z.sdk.game.gameplayStop(), undefined);

    // Save. Writes are batched and sent about a second later; reads are synchronous.
    if (this.score > (this.registry.get("best") as number)) {
      this.registry.set("best", this.score);
      try { z.sdk.data.setItem("best", String(this.score)); } catch { /* dataLimitExceeded */ }
    }
    // Leaderboard (needs a signed-in player and the board enabled in the console).
    await safe(async () => {
      const user = await z.sdk.user.getUser();
      if (!user) return;
      const encryptedScore = await encryptScore(this.score, BOARD_KEY, user.__dangerousUserId, GAME_ID);
      await z.sdk.user.submitScore({ encryptedScore, score: this.score });
    }, undefined);

    // Midgame ad at a natural break. Pauses sound and the loop from adStarted until adFinished OR adError.
    const { finished, error } = await z.requestAd("midgame");
    if (!finished) console.warn("no ad:", error?.code);   // adCooldown, unfilled, adblock ... the game just carries on
    this.scene.start("Play");
  }

  async watchForBonus() {                                   // call from a button press
    const { finished } = await this.zoko.requestAd("rewarded");
    if (finished) this.score += 10;                         // reward only after adFinished
  }
}

new Phaser.Game({
  type: Phaser.AUTO,
  parent: "game",
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
  plugins: { global: [{ key: "ZokoPlugin", plugin: ZokoPlugin, start: true, mapping: "zoko", data: { syncMute: true } }] },
  scene: [Boot, Play],
});
```

`encryptScore`, `BOARD_KEY` và `GAME_ID` đến từ [trang bảng xếp hạng](https://docs.zokogames.com/vn/sdk/leaderboards#client-submission), nơi có hàm hỗ trợ AES-GCM và giải thích vì sao một bảng không có khóa mã hóa chấp nhận `encryptedScore: ""` cùng `score` thường. Chỉ người chơi đã đăng nhập mới được xếp hạng, và một lần gửi vi phạm quy tắc của bảng bị bỏ lặng lẽ trong khi lệnh gọi vẫn resolve.

### Plugin mang lại gì cho bạn {#what-the-plugin-gives-you}

| Thành viên | Hành vi (đã xác minh trong `ZokoPlugin.ts` và `ZokoAdFlow.ts`) |
| --- | --- |
| `ready()` | Tải script SDK nếu thiếu `window.ZokoGames`, rồi chạy `SDK.init()`. Reject với `{ code: "sdkNotLoaded" }` khi không tải được script. Gọi lặp lại an toàn. Khi môi trường không phải `disabled`, nó cũng đăng ký các bộ lắng nghe cài đặt và ngoại tuyến và áp dụng `muteAudio` cho `game.sound.mute` (tùy chọn `syncMute`, mặc định `true`). |
| `requestAd("midgame" \| "rewarded")` | Ở `adStarted` nó tạm dừng mọi âm thanh, tắt tiếng và gọi `game.loop.sleep()`. Ở `adFinished`, ở `adError`, và khi chính yêu cầu ném lỗi, nó đánh thức vòng lặp, khôi phục trạng thái tắt tiếng (`muteAudio` của cổng hoặc giá trị trước đó) và tiếp tục âm thanh. Resolve `{ finished, error? }` và không bao giờ reject vì sự cố quảng cáo. |
| `version` | Phiên bản JavaScript SDK mà plugin được viết cho (`SDK_VERSION`). |
| `isAdPlaying` | `true` khi một quảng cáo đang hiển thị trên màn hình. |
| `events` | Phát `adStarted`, `adFinished`, `adError(error)`, `settingsChange(settings)` và `offlineChange(offline)`. |
| `sdk` | SDK thô. Ném `sdkNotInitialized` trước khi `ready()` resolve. |
| `ad`, `banner`, `user`, `data`, `store`, `analytics`, `gameApi`, `environment`, `isQaTool`, `client` | Client có kiểu. `gameApi` là mô-đun `game` của SDK (`this.game` là đối tượng riêng của Phaser). `client` là `ZokoClient` bên dưới, cũng có `achievements` (`this.zoko.client.achievements.list()`, `unlock(key)`, `onUnlock(cb)`; xem [thành tích](https://docs.zokogames.com/vn/sdk/achievements)). |
| `trackLoading(this.load)` | Báo cáo một loader tới cổng: `loadingStart` ở `start`, `loadingProgress` (0 đến 100) ở `progress`, `loadingStop` ở `complete`. Trả về một hàm gỡ các bộ lắng nghe. |
| `rectFromGameBounds(x, y, w, h)` | Chuyển một hình chữ nhật theo tọa độ game (chiều rộng và chiều cao game đã cấu hình) thành hình chữ nhật canvas chuẩn hóa mà các lệnh gọi banner dùng. |
| `requestBannerAt(id, x, y, w, h, size?)` | Đặt một container DOM lên một hình chữ nhật theo tọa độ game và yêu cầu banner ở đó; không có `size` thì nó yêu cầu kích thước responsive lớn nhất vừa vặn. |

Tệp plugin cũng xuất `runAdFlow`, `bindLoadingProgress`, `withZoko` và `ZOKO_SDK_SCRIPT_URL`, và `ZokoClient` có thể dùng riêng trong kiểm thử đơn vị (nó không cần Phaser). `this.zoko` cũng có sẵn qua `class X extends withZoko(Phaser.Scene)` khi khóa plugin là `ZokoPlugin`.

## Không dùng plugin {#without-the-plugin}

Nếu bạn không muốn dùng plugin, hãy tự gọi SDK. Khởi tạo trước khi tạo `Phaser.Game`, và viết hàm hỗ trợ quảng cáo để nó tiếp tục ở cả hai kết quả.

```js
const SDK = window.ZokoGames?.SDK;
let live = false;

async function main() {
  if (SDK) { await SDK.init(); live = SDK.environment !== "disabled"; }   // init never rejects
  const game = new Phaser.Game({
    type: Phaser.AUTO,
    parent: "game",
    scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
    scene: [Boot, Play],
  });
  if (live) {
    const apply = (s) => { game.sound.mute = s.muteAudio; };
    apply(SDK.game.settings);
    SDK.game.addSettingsChangeListener(apply);
  }
}

function showAd(game, type) {
  if (!live) return Promise.resolve(false);
  let paused = false;
  const pause = () => { if (paused) return; paused = true; game.sound.pauseAll(); game.sound.mute = true; game.loop.sleep(); };
  const resume = () => {
    if (!paused) return; paused = false;
    game.loop.wake();
    game.sound.mute = SDK.game.settings.muteAudio;
    game.sound.resumeAll();
  };
  return new Promise((done) => {
    SDK.ad.requestAd(type, {
      adStarted: pause,
      adFinished: () => { resume(); done(true); },
      adError: () => { resume(); done(false); },
    }).catch(() => { resume(); done(false); });          // throws (for example sdkDisabled) instead of calling adError
  });
}
main();
```

Tạm dừng một cảnh bằng `scene.pause()` là chưa đủ: tween, bộ đếm giờ ở các cảnh khác và trình quản lý âm thanh vẫn chạy. `game.loop.sleep()` dừng toàn bộ bước game. `requestAd` chỉ resolve sau khi `adFinished` hoặc `adError` đã được gửi, nên `await showAd(...)` là chỗ an toàn để tiếp tục logic game.

**Chế độ trẻ em.** Từ phiên bản 1.5.0, wrapper cung cấp giá trị này: `SDK.game.settings.kidsMode` là true khi game chạy ở chế độ trẻ em (game có cờ trẻ em, hoặc người chơi đang ở chế độ trẻ em); khi đó hãy ẩn chat, phòng, lời nhắc đăng nhập và màn hình cửa hàng. Portal không gửi trường này sẽ cho false, vì vậy hãy tiếp tục tôn trọng cả `disableChat`, giá trị mà portal đặt thành true trong cùng các trường hợp. Để kiểm thử, hãy thêm `?kidsMode=true` vào địa chỉ trang ở chế độ cục bộ. Xem [chế độ trẻ em](https://docs.zokogames.com/vn/guides/kids-mode).

## Banner {#banners}

Container banner là các phần tử DOM cạnh canvas, không phải đối tượng game. Chỉ yêu cầu chúng ở các màn hình menu và xóa chúng trước khi chơi.

```html
<div id="game"></div>
<div id="menu-banner" style="width:728px;height:90px;margin:8px auto"></div>
```

```js
SDK.banner.requestBanner({ id: "menu-banner", width: 728, height: 90 }).catch(() => {});
this.events.once("shutdown", () => SDK.banner.clearAllBanners());
```

Với plugin, `await this.zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250")` tạo container cho bạn trên hình chữ nhật đó của canvas. Banner bị từ chối khi một quảng cáo video đang phát (`videoAdPlaying`) và một container chỉ có thể làm mới mỗi 30 giây (`bannerCooldown`).

## Kênh dữ liệu phòng {#room-data-channel}

Được thêm trong SDK 1.3.0. Kênh dữ liệu phòng cho phép những người chơi trong cùng một phòng trao đổi các thông điệp JSON nhỏ và chia sẻ một trạng thái nhỏ mà chỉ chủ phòng mới được ghi, nên một game nhiều người chơi đơn giản không cần máy chủ riêng. Kênh này dành cho dữ liệu game, không phải trò chuyện bằng văn bản. Kênh tồn tại sau `updateRoom` (hoặc sau khi tham gia từ lời mời) và kết thúc với `leftRoom`, cần người chơi đã đăng nhập và một cổng bật thời gian thực (nếu không sẽ là `roomUnavailable`), với các giới hạn sau: 8 KB cho mỗi thông điệp hoặc bản vá, 20 thông điệp mỗi giây, 64 KB trạng thái, khóa trạng thái dài 1 đến 40 ký tự thuộc `A-Z a-z 0-9 _ . : -`. Trên cổng, thông điệp không bao giờ được dội ngược lại cho người gửi; người chơi đầu tiên trong phòng là chủ phòng. Quy tắc đầy đủ và các mã lỗi (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) nằm trong [mô-đun game](https://docs.zokogames.com/vn/sdk/game#room-data-channel) và [hướng dẫn nhiều người chơi](https://docs.zokogames.com/vn/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

Plugin không có hàm hỗ trợ phòng riêng; hãy dùng `game.room` của SDK qua `this.zoko.gameApi.room`. Nó là `undefined` trên SDK cũ hơn 1.3.0, nên hãy kiểm tra trước. Các phương thức: `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()`, `selfId`, và `onMessage`, `onState`, `onMembers`, `onHostChange`, `onError`, mỗi cái trả về một hàm hủy đăng ký. Trên `localhost`, chế độ cục bộ của SDK khiến hai tab trình duyệt trong cùng một id phòng hoạt động như hai người chơi.

```ts
async startMatch() {
  await this.zoko.ready();
  await this.zoko.gameApi.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = this.zoko.gameApi.room;
  if (!room) return;
  room.onMessage((m) => this.placeMark((m.data as { cell: number }).cell));
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
}

onCellClicked(cell: number) { void this.zoko.gameApi.room?.send({ cell, mark: "X" }); }
```

## Mua hàng {#purchases}

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

Hãy kiểm tra `isAvailable` trước khi hiển thị bất kỳ giao diện mua hàng nào và xác minh quyền sở hữu trên máy chủ của bạn. Xem [mua hàng trong game](https://docs.zokogames.com/vn/sdk/purchases). Trên `localhost`, chế độ cục bộ của SDK cung cấp một cửa hàng thử nghiệm.

## Các thiết lập xuất quan trọng trên web {#export-settings-that-matter-on-the-web}

- **Bundle với đường dẫn tương đối.** Vite: `base: "./"`. Đường dẫn tuyệt đối từ gốc (bắt đầu bằng dấu gạch chéo) hỏng dưới origin riêng của game và gây cảnh báo `absolute_path`. Xem [yêu cầu kỹ thuật](https://docs.zokogames.com/vn/requirements/technical#relative-paths-only).
- **Đừng nén trước.** Phaser, khác Unity, yêu cầu tên tệp thường. Một tệp kết thúc bằng `.br` hoặc `.gz` được phục vụ với `Content-Encoding`, nhưng trang của bạn vẫn sẽ yêu cầu tên thường, nên hãy gửi tệp thường. Origin của game có phục vụ hậu tố `.br` hoặc `.gz` với `Content-Encoding` tương ứng và lưu đệm tệp game một năm dưới build id. Việc các tệp thường có được nén khi truyền hay không không được cổng ghi tài liệu hay đảm bảo, và ước tính dung lượng tải ban đầu dùng kích thước chưa nén, nên hãy giữ các tệp nhỏ.
- **Dung lượng.** Gói texture vào atlas và giữ bitrate âm thanh ở mức vừa phải. Hãy tải các màn sau sau cảnh đầu tiên thay vì trong `preload`. Giới hạn tải lên là 1.500 tệp, 250 MB khi giải nén và khoảng 50 MB tải ban đầu (20 MB cho di động); xem [khung hình đầu tiên thật nhanh](https://docs.zokogames.com/vn/guides/first-frame).
- **Kích thước canvas.** Kích thước khung thay đổi theo toàn màn hình và xoay. `Phaser.Scale.FIT` với `autoCenter: CENTER_BOTH` giữ game dễ đọc ở mọi [độ phân giải bắt buộc](https://docs.zokogames.com/vn/requirements/gameplay). Bộ khởi đầu dùng 800 nhân 450.
- **Mở khóa âm thanh.** Trình duyệt chặn âm thanh cho tới sự kiện con trỏ hoặc phím đầu tiên. Trình quản lý âm thanh của Phaser tự xử lý việc mở khóa; hãy bắt đầu nhạc từ một lần nhấn nút hoặc sau sự kiện `unlocked` của trình quản lý âm thanh, không phải vô điều kiện trong `create()`. Quảng cáo và `syncMute` không thay thế điều này.
- **Toàn màn hình.** Ưu tiên nút toàn màn hình trên thanh khung của cổng: nó phóng toàn bộ khung, gồm cả các điều khiển của cổng. Khung mang `allow="fullscreen"`, nên `this.scale.startFullscreen()` được phép, nhưng nó chỉ phóng canvas của bạn; đừng thêm một nút cạnh tranh.
- **Bộ nhớ.** Khung của cổng không có đa luồng hay `SharedArrayBuffer` (cổng không gửi header cách ly cross-origin), điều mà Phaser không cần.

Sau một quảng cáo, một lời nhắc đăng nhập hoặc liên kết tài khoản, hay một giao dịch mua, tiêu điểm bàn phím tự quay về khung game và canvas của nó, nên các phím của người chơi hoạt động lại mà không cần nhấp.

## Báo cáo chat, ảnh chụp màn hình và bản phản chiếu bộ nhớ {#chat-reports-screenshots-and-storage-mirror}

Từ SDK 1.4.0: `zoko.gameApi.reportChat(report)`, `zoko.gameApi.onScreenshotRequest(handler)` và `zoko.data.mirrorLocalStorage({ prefix: "save_" })`. `ready()` đăng ký một bộ cung cấp ảnh chụp màn hình mặc định dựa trên `renderer.snapshot`; truyền `screenshots: false` vào cấu hình plugin để bỏ qua. Bản phản chiếu chỉ bao phủ `localStorage`. Trình mô phỏng chấp nhận cả ba.

## Kiểm thử cục bộ {#test-locally}

Phaser luôn chạy trong trình duyệt, nên không có trình giả lập trong trình soạn thảo. Hãy phục vụ game từ `localhost` (bộ khởi đầu làm việc này bằng `npm run dev`, cổng 5173) và SDK khởi động ở [chế độ cục bộ](https://docs.zokogames.com/vn/getting-started/local-testing) của riêng nó: một lớp phủ ba giây thay cho mỗi quảng cáo, banner là các hộp nét đứt, có hai người chơi giả, và bản lưu đám mây đi vào `localStorage`. Có hai điều hay làm người ta vấp:

- Một yêu cầu midgame thứ hai trong vòng ba phút sau quảng cáo cuối thất bại với `adCooldown`. Đây là quy tắc thật, nên game của bạn phải xử lý được.
- `submitScore` được chấp nhận và không có gì hiển thị trong chế độ cục bộ, và token cục bộ không có chữ ký.

Thêm `?sdk_debug=true` để ghi lại mọi lệnh gọi, `?ad_response=unfilled` để ép quảng cáo thất bại, và `?user_response=logged_out` để kiểm thử luồng khách. Sau đó mở [công cụ Preview](https://www.zokogames.com/vn/preview), nhập địa chỉ cục bộ của bạn và xem danh sách kiểm tra yêu cầu được tích dần.

## API

### `init`

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

| JavaScript | Phaser |
| --- | --- |
| `init` | `await this.zoko.ready()` |
| `environment` | `this.zoko.environment` |
| `isQaTool` | `this.zoko.isQaTool` |

### `ad.*`

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

| JavaScript | Phaser |
| --- | --- |
| `ad.requestAd` | `this.zoko.requestAd(type)` (pausing) or `this.zoko.ad.requestAd(type, callbacks)` |
| `ad.requestAd.adStarted` | `callbacks.adStarted` of `this.zoko.ad.requestAd(type, callbacks)`; `this.zoko.requestAd(type)` pauses for you |
| `ad.requestAd.adFinished` | `callbacks.adFinished`; `requestAd` resolves `{ finished: true }` |
| `ad.requestAd.adError` | `callbacks.adError(error)`; `requestAd` resolves `{ finished: false, error }` |
| `ad.hasAdblock` | `this.zoko.ad.hasAdblock`() |

### `banner.*`

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

| JavaScript | Phaser |
| --- | --- |
| `banner.requestBanner` | `this.zoko.banner.requestBanner({ id, width, height })` |
| `banner.requestResponsiveBanner` | `this.zoko.banner.requestResponsiveBanner`() |
| `banner.clearBanner` | `this.zoko.banner.clearBanner`() |
| `banner.clearAllBanners` | `this.zoko.banner.clearAllBanners`() |

### `game.*`

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

| JavaScript | Phaser |
| --- | --- |
| `game.settings` | `this.zoko.gameApi.settings` |
| `game.addSettingsChangeListener` | `this.zoko.gameApi.addSettingsChangeListener(fn)` / `this.zoko.events.on("settingsChange", fn)` |
| `game.removeSettingsChangeListener` | `this.zoko.gameApi.removeSettingsChangeListener`() |
| `game.gameplayStart` | `this.zoko.gameApi.gameplayStart`() |
| `game.gameplayStop` | `this.zoko.gameApi.gameplayStop`() |
| `game.loadingStart` | `this.zoko.gameApi.loadingStart()` |
| `game.loadingStop` | `this.zoko.gameApi.loadingStop`() |
| `game.loadingProgress` | `this.zoko.gameApi.loadingProgress(percentage)` |
| `game.happytime` | `this.zoko.gameApi.happytime`() |
| `game.reportGameCompletedPercentage` | `this.zoko.gameApi.reportGameCompletedPercentage`() |
| `game.reportChat` | `zoko.gameApi.reportChat(report)` |
| `game.onScreenshotRequest` | `zoko.gameApi.onScreenshotRequest(handler)` / `zoko.useDefaultScreenshot()` |
| `game.setGameContext` | `this.zoko.gameApi.setGameContext`() |
| `game.clearGameContext` | `this.zoko.gameApi.clearGameContext`() |
| `game.isInstantMultiplayer` | `this.zoko.gameApi.isInstantMultiplayer` |
| `game.isInstantJoin` | `this.zoko.gameApi.isInstantJoin` |
| `game.isOffline` | `this.zoko.gameApi.isOffline` |
| `game.addOfflineListener` | `this.zoko.gameApi.addOfflineListener(fn)` / `this.zoko.events.on("offlineChange", fn)` |
| `game.removeOfflineListener` | `this.zoko.gameApi.removeOfflineListener(fn)` |
| `game.updateRoom` | `this.zoko.gameApi.updateRoom`() |
| `game.leftRoom` | `this.zoko.gameApi.leftRoom`() |
| `game.addJoinRoomListener` | `this.zoko.gameApi.addJoinRoomListener`() |
| `game.removeJoinRoomListener` | `this.zoko.gameApi.removeJoinRoomListener`() |
| `game.inviteParams` | `this.zoko.gameApi.inviteParams` |
| `game.inviteLink` | `this.zoko.gameApi.inviteLink`() |
| `game.getInviteParam` | `this.zoko.gameApi.getInviteParam`() |
| `game.showInviteButton` | `this.zoko.gameApi.showInviteButton(params)` |
| `game.hideInviteButton` | `this.zoko.gameApi.hideInviteButton()` |
| `game.room` | `this.zoko.gameApi.room` |
| `game.room.send` | `this.zoko.gameApi.room.send(data, { to })` |
| `game.room.onMessage` | `this.zoko.gameApi.room.onMessage(cb)` |
| `game.room.addMessageListener` | `this.zoko.gameApi.room.addMessageListener(cb)` |
| `game.room.removeMessageListener` | `this.zoko.gameApi.room.removeMessageListener(cb)` |
| `game.room.setState` | `this.zoko.gameApi.room.setState(patch)` |
| `game.room.getState` | `this.zoko.gameApi.room.getState()` |
| `game.room.onState` | `this.zoko.gameApi.room.onState(cb)` |
| `game.room.addStateListener` | `this.zoko.gameApi.room.addStateListener(cb)` |
| `game.room.removeStateListener` | `this.zoko.gameApi.room.removeStateListener(cb)` |
| `game.room.members` | `this.zoko.gameApi.room.members()` |
| `game.room.onMembers` | `this.zoko.gameApi.room.onMembers(cb)` |
| `game.room.addMembersListener` | `this.zoko.gameApi.room.addMembersListener(cb)` |
| `game.room.removeMembersListener` | `this.zoko.gameApi.room.removeMembersListener(cb)` |
| `game.room.isHost` | `this.zoko.gameApi.room.isHost()` |
| `game.room.onHostChange` | `this.zoko.gameApi.room.onHostChange(cb)` |
| `game.room.addHostChangeListener` | `this.zoko.gameApi.room.addHostChangeListener(cb)` |
| `game.room.removeHostChangeListener` | `this.zoko.gameApi.room.removeHostChangeListener(cb)` |
| `game.room.selfId` | `this.zoko.gameApi.room.selfId` |
| `game.room.onError` | `this.zoko.gameApi.room.onError(cb)` |
| `game.room.addLeftListener` | `this.zoko.gameApi.room.addLeftListener(cb)` |
| `game.room.removeLeftListener` | `this.zoko.gameApi.room.removeLeftListener(cb)` |
| `game.room.addErrorListener` | `this.zoko.gameApi.room.addErrorListener(cb)` |
| `game.room.removeErrorListener` | `this.zoko.gameApi.room.removeErrorListener(cb)` |

### `user.*`

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

| JavaScript | Phaser |
| --- | --- |
| `user.isUserAccountAvailable` | `this.zoko.user.isUserAccountAvailable` |
| `user.systemInfo` | `this.zoko.user.systemInfo` |
| `user.getUser` | `this.zoko.user.getUser`() |
| `user.listFriends` | `this.zoko.user.listFriends`() |
| `user.getUserToken` | `this.zoko.user.getUserToken`() |
| `user.showAuthPrompt` | `this.zoko.user.showAuthPrompt`() |
| `user.addAuthListener` | `this.zoko.user.addAuthListener`() |
| `user.removeAuthListener` | `this.zoko.user.removeAuthListener`() |
| `user.showAccountLinkPrompt` | `this.zoko.user.showAccountLinkPrompt`() |
| `user.submitScore` | `this.zoko.user.submitScore`() |
| `user.getXsollaUserToken` | `this.zoko.user.getXsollaUserToken()` |

### `data.*`

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

| JavaScript | Phaser |
| --- | --- |
| `data.getItem` | `this.zoko.data.getItem(key)` |
| `data.setItem` | `this.zoko.data.setItem(key, value)` |
| `data.removeItem` | `this.zoko.data.removeItem`() |
| `data.clear` | `this.zoko.data.clear`() |
| `data.mirrorLocalStorage` | `zoko.data.mirrorLocalStorage(options)` |

### `store.*`

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

| JavaScript | Phaser |
| --- | --- |
| `store.isAvailable` | `this.zoko.store.isAvailable` |
| `store.getCatalogItems` | `this.zoko.store.getCatalogItems({ limit, offset })` |
| `store.getPlayerInventory` | `this.zoko.store.getPlayerInventory({ limit, offset })` |
| `store.buyItem` | `this.zoko.store.buyItem(itemId)` |
| `store.consumeItem` | `this.zoko.store.consumeItem`() |
| `store.getPurchaseToken` | `this.zoko.store.getPurchaseToken()` |
| `store.setSandbox` | `this.zoko.store.setSandbox`() |

### `achievements.*`

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

| JavaScript | Phaser |
| --- | --- |
| `achievements.list` | `this.zoko.achievements.list()` |
| `achievements.unlock` | `this.zoko.achievements.unlock(key)` |
| `achievements.onUnlock` | `this.zoko.achievements.onUnlock(fn)` |

### `analytics.*`

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

| JavaScript | Phaser |
| --- | --- |
| `analytics.trackOrder` | `this.zoko.analytics.trackOrder`() |
| `analytics.track` | `this.zoko.analytics.track(name, params)` |

### `constants`

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

| JavaScript | Phaser |
| --- | --- |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.<module>` |
| `SDK_VERSION` | `this.zoko.version` |

## Lỗi thường gặp {#known-pitfalls}

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

- **`trackLoading` trước `ready()`.** Cầu nối tải của plugin gọi SDK từ sự kiện `start` của loader. Nếu lúc đó `ready()` chưa hoàn tất, lệnh gọi đó thất bại với `sdkNotInitialized` (một promise bị từ chối; nó không còn ném ngoại lệ trong trình xử lý sự kiện) và việc tải không được báo cáo. Hãy gọi `await this.zoko.ready()` trước trong một scene khởi động, rồi gọi `trackLoading(this.load)` trong `init()` của scene tiếp theo có tải tài nguyên.
- **`sdkNotLoaded`.** Script bị chặn hoặc ngoại tuyến và `loadScript` bị tắt hoặc thất bại. Game của bạn vẫn nên khởi động được; bộ khởi đầu cho thấy mẫu này.
- **Các lệnh gọi trên một SDK disabled ném `sdkDisabled`.** Hãy kiểm tra `sdk.environment !== "disabled"` trước, như ở trên, nếu không một rejection không được xử lý sẽ đến console của bạn.
- **Âm thanh vẫn tắt tiếng sau quảng cáo.** Có thứ gì đó khác đã đổi `sound.mute` trong lúc quảng cáo. Plugin khôi phục giá trị `muteAudio` của cổng, hoặc giá trị nó thấy ở `adStarted`.
- **`this.zoko` là undefined.** Hãy đăng ký plugin với `mapping: "zoko"`, hoặc mở rộng `withZoko(Phaser.Scene)` và giữ khóa là `ZokoPlugin`.
- **Banner sai chỗ.** `requestBannerAt` chuyển đổi tọa độ game bằng kích thước game đã cấu hình; hãy kiểm tra chế độ Scale Manager của bạn.
- **Phần thưởng bị trao hai lần.** Chỉ trao khi `finished === true`, không bao giờ khi nhấn nút.

## Tiếp theo {#next}

- JavaScript thuần với một bộ kết xuất khác: [HTML5 thuần, Three.js và PixiJS](https://docs.zokogames.com/vn/engines/html5-libraries).
- Mọi engine trong một cái nhìn: [tổng quan về engine](https://docs.zokogames.com/vn/engines/overview).
- Tải lên: nén zip đầu ra của build với `index.html` ở gốc kho (`npm run package` trong bộ khởi đầu làm việc này), rồi làm theo [hướng dẫn gửi game](https://docs.zokogames.com/vn/getting-started/submission-walkthrough).
