# Phaser

Phaser 게임은 브라우저에서 실행되므로 연동 방법이 두 가지 있습니다. 광고 앞뒤로 게임 루프와 사운드를 대신 일시정지해 주는 **ZokoGames Phaser 플러그인**(`packages/sdk-engines/phaser`)을 사용하거나, [JavaScript SDK](https://docs.zokogames.com/kr/sdk/introduction)를 직접 호출하세요. 둘 다 같은 호출, 한도, [오류 코드](https://docs.zokogames.com/kr/sdk/introduction#errors)를 사용합니다. "미드게임", "보상형" 같은 전문 용어는 [용어집](https://docs.zokogames.com/kr/getting-started/glossary)에 설명되어 있습니다.

> [!NOTE]
> 현재 상태(1.7.1): 실제 브라우저에서 Phaser 3.90.0 및 4.2.1을 대상으로 실행했습니다(2026-11-23). 처음 임포트가 실패하면 Phaser 버전과 정확한 오류를 [지원](https://docs.zokogames.com/kr/business/support)으로 보내 주세요. 그 아래의 JavaScript SDK는 테스트가 완료된 부분입니다. 1.7.1 릴리스(스크립트 로드 제한 시간)는 2026-11-23에 브라우저와 프로덕션에서 다시 실행했습니다.

## 설치 {#install}

Phaser 플러그인을 내려받으세요: [/sdk-engines/zokogames-phaser-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-phaser-1.7.1.zip) (저장소의 폴더와 같은 파일입니다).

[/sdk-engines/phaser.zip](https://www.zokogames.com/sdk-engines/phaser.zip)은 항상 최신 버전입니다. 체크섬: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). 모든 엔진 패키지의 버전, 크기, SHA-256 목록: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

게임에 맞는 경로를 고르세요.

| 여러분이 가진 것 | 할 일 |
| --- | --- |
| 완성된 Phaser 게임(JavaScript 또는 TypeScript) | 플러그인 소스를 프로젝트에 복사하고 플러그인을 등록하거나(아래), 플러그인 없이 [순수 SDK](#without-the-plugin)를 사용하세요. |
| 새 게임 | `phaser` [스타터 키트](https://docs.zokogames.com/kr/getting-started/starter-kits)로 시작하세요. `src/zoko/` 아래에 플러그인, 장면 네 개, `npm run package` 스크립트가 이미 들어 있습니다. |

플러그인은 `packages/sdk-engines/phaser/src/`에 있는 순수 TypeScript로, `ZokoPlugin.ts`, `ZokoClient.ts`, `ZokoAdFlow.ts`, `ZokoLoadingBridge.ts`, `ZokoSceneMixin.ts`, `types.ts`, 그리고 이들을 다시 내보내는 `index.ts`로 구성됩니다. 폴더를 복사해(예를 들어 `src/zokogames-phaser/`) 거기서 임포트하세요. 스타터 키트에는 같은 파일이 포맷된 채로 `src/zoko/`에 들어 있고 `index.ts`가 없으므로, 거기서는 `./zoko/ZokoPlugin`을 임포트하세요. 피어 의존성은 `phaser ^3.80.0`이며, 스타터 키트 자체는 Phaser 4.2에 고정되어 있고 이 버전으로 타입 검사와 빌드를 거칩니다.

스크립트 태그를 추가할 필요는 없습니다. `window.ZokoGames`가 없으면 플러그인이 `https://sdk.zokogames.com/zokogames-sdk-v1.js`를 직접 주입합니다(끄려면 `loadScript: false`를 넘기세요). 그래도 `index.html`의 스크립트 태그가 더 낫습니다. 업로드 검증기가 SDK URL을 찾기 때문입니다([빌드 검증](https://docs.zokogames.com/kr/requirements/build-validation) 참고).

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

## 플러그인을 사용한 동작하는 게임 루프 {#a-working-game-loop-with-the-plugin}

init, 미드게임 광고, 보상형 광고, 게임플레이 시작과 중지, 저장과 불러오기, 리더보드 점수를 모두 다루는 파일 하나입니다. 모든 포털 호출은 감싸져 있어서 SDK가 `disabled`일 때도 게임이 실행됩니다([로컬 모드](#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`, `GAME_ID`는 [리더보드 페이지](https://docs.zokogames.com/kr/sdk/leaderboards#client-submission)에서 가져옵니다. 그곳에 AES-GCM 도우미가 있으며, 암호화 키가 없는 보드가 일반 `score`와 함께 `encryptedScore: ""`를 받아들이는 이유도 설명되어 있습니다. 로그인한 플레이어만 순위에 오르며, 보드 규칙을 어기는 제출은 호출이 정상적으로 resolve되더라도 조용히 버려집니다.

### 플러그인이 제공하는 것 {#what-the-plugin-gives-you}

| 멤버 | 동작(`ZokoPlugin.ts`와 `ZokoAdFlow.ts`에서 확인) |
| --- | --- |
| `ready()` | `window.ZokoGames`가 없으면 SDK 스크립트를 불러온 다음 `SDK.init()`을 실행합니다. 스크립트를 불러올 수 없으면 `{ code: "sdkNotLoaded" }`로 reject합니다. 반복 호출해도 안전합니다. 환경이 `disabled`가 아니면 설정 및 오프라인 리스너도 등록하고 `muteAudio`를 `game.sound.mute`에 적용합니다(옵션 `syncMute`, 기본값 `true`). |
| `requestAd("midgame" \| "rewarded")` | `adStarted`에서 모든 사운드를 일시정지하고 음소거하며 `game.loop.sleep()`을 호출합니다. `adFinished`, `adError`, 그리고 요청 자체가 throw될 때 루프를 깨우고, 음소거를 복원하며(포털의 `muteAudio` 또는 이전 값) 사운드를 재개합니다. `{ finished, error? }`로 resolve되며 광고 문제로는 절대 reject되지 않습니다. |
| `version` | 플러그인이 대상으로 하는 JavaScript SDK 버전(`SDK_VERSION`). |
| `isAdPlaying` | 광고가 화면에 있는 동안 `true`입니다. |
| `events` | `adStarted`, `adFinished`, `adError(error)`, `settingsChange(settings)`, `offlineChange(offline)`를 발생시킵니다. |
| `sdk` | 원시 SDK입니다. `ready()`가 resolve되기 전에는 `sdkNotInitialized`를 던집니다. |
| `ad`, `banner`, `user`, `data`, `store`, `analytics`, `gameApi`, `environment`, `isQaTool`, `client` | 타입이 지정된 클라이언트입니다. `gameApi`는 SDK의 `game` 모듈입니다(`this.game`은 Phaser 자체 객체입니다). `client`는 내부의 `ZokoClient`로, `achievements`도 가지고 있습니다(`this.zoko.client.achievements.list()`, `unlock(key)`, `onUnlock(cb)`; [업적](https://docs.zokogames.com/kr/sdk/achievements) 참고). |
| `trackLoading(this.load)` | 로더를 포털에 보고합니다. `start`에서 `loadingStart`, `progress`에서 `loadingProgress`(0~100), `complete`에서 `loadingStop`을 호출합니다. 리스너를 해제하는 함수를 반환합니다. |
| `rectFromGameBounds(x, y, w, h)` | 게임 좌표(설정된 게임 너비와 높이)의 사각형을 배너 호출이 사용하는 정규화된 캔버스 사각형으로 변환합니다. |
| `requestBannerAt(id, x, y, w, h, size?)` | 게임 좌표의 사각형 위에 DOM 컨테이너를 배치하고 그 자리에 배너를 요청합니다. `size`가 없으면 들어맞는 가장 큰 반응형 크기를 요청합니다. |

플러그인 파일은 `runAdFlow`, `bindLoadingProgress`, `withZoko`, `ZOKO_SDK_SCRIPT_URL`도 내보내며, `ZokoClient`는 단위 테스트에서 단독으로 사용할 수 있습니다(Phaser가 필요 없습니다). 플러그인 키가 `ZokoPlugin`이면 `class X extends withZoko(Phaser.Scene)`로도 `this.zoko`를 사용할 수 있습니다.

## 플러그인 없이 {#without-the-plugin}

플러그인을 원하지 않으면 SDK를 직접 호출하세요. `Phaser.Game`을 만들기 전에 초기화하고, 광고 도우미는 두 결과 모두에서 재개하도록 작성하세요.

```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();
```

`scene.pause()`로 장면 하나만 일시정지하는 것으로는 충분하지 않습니다. 트윈, 다른 장면의 타이머, 사운드 매니저는 계속 실행됩니다. `game.loop.sleep()`은 게임 스텝 전체를 멈춥니다. `requestAd`는 `adFinished` 또는 `adError`가 전달된 뒤에야 resolve되므로, `await showAd(...)` 뒤는 게임 로직을 재개하기에 안전한 지점입니다.

**키즈 모드.** 버전 1.5.0부터 래퍼가 이 값을 제공합니다. 게임이 키즈 모드로 실행될 때(어린이용 플래그가 있는 게임, 또는 키즈 모드인 플레이어) `SDK.game.settings.kidsMode` 값은 true입니다. 이때는 채팅, 룸, 로그인 안내, 상점 화면을 숨기세요. 이 필드를 보내지 않는 포털에서는 false가 되므로, 포털이 같은 경우에 true로 설정하는 `disableChat`도 계속 따르세요. 테스트하려면 로컬 모드에서 페이지 주소에 `?kidsMode=true`를 추가하세요. [키즈 모드](https://docs.zokogames.com/kr/guides/kids-mode)를 참고하세요.

## 배너 {#banners}

배너 컨테이너는 게임 오브젝트가 아니라 캔버스 옆의 DOM 요소입니다. 메뉴 화면에서만 요청하고 플레이 전에 지우세요.

```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());
```

플러그인을 쓰면 `await this.zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250")`가 캔버스의 그 사각형 위에 컨테이너를 대신 만들어 줍니다. 동영상 광고가 재생되는 동안에는 배너가 거부되며(`videoAdPlaying`), 컨테이너는 30초에 한 번만 새로고침할 수 있습니다(`bannerCooldown`).

## 방 데이터 채널 {#room-data-channel}

SDK 1.3.0에서 추가되었습니다. 방 데이터 채널을 사용하면 한 방의 플레이어끼리 작은 JSON 메시지를 주고받고 호스트만 쓸 수 있는 아주 작은 상태를 공유할 수 있어서, 간단한 멀티플레이어 게임에는 자체 서버가 필요 없습니다. 이것은 게임 데이터용이며 텍스트 채팅용이 아닙니다. `updateRoom` 이후(또는 초대로 참여한 이후)부터 `leftRoom`까지 존재하고, 로그인한 플레이어와 실시간 기능이 켜진 포털이 필요하며(그렇지 않으면 `roomUnavailable`), 한도는 메시지 또는 patch당 8 KB, 초당 메시지 20개, 상태 64 KB, 그리고 `A-Z a-z 0-9 _ . : -`로 이루어진 1~40자의 상태 키입니다. 포털에서는 메시지가 보낸 사람에게 되돌아오지 않으며, 방의 첫 번째 플레이어가 호스트입니다. 전체 규칙과 오류 코드(`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`)는 [game 모듈](https://docs.zokogames.com/kr/sdk/game#room-data-channel)과 [멀티플레이어 가이드](https://docs.zokogames.com/kr/guides/multiplayer-invites#6-exchange-game-data-in-the-room)에 있습니다.

플러그인에는 방 전용 도우미가 없으므로 `this.zoko.gameApi.room`을 통해 SDK의 `game.room`을 사용하세요. SDK가 1.3.0보다 오래되면 `undefined`이므로 먼저 확인하세요. 메서드: `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()`, `selfId`, 그리고 `onMessage`, `onState`, `onMembers`, `onHostChange`, `onError`(각각 구독 해제 함수를 반환합니다). `localhost`에서는 SDK의 로컬 모드가 같은 방 id의 브라우저 탭 두 개를 두 명의 플레이어처럼 동작하게 합니다.

```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" }); }
```

## 구매 {#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;
  }
}
```

구매 UI를 표시하기 전에 `isAvailable`을 확인하고 소유 여부는 서버에서 검증하세요. [게임 내 구매](https://docs.zokogames.com/kr/sdk/purchases)를 참고하세요. `localhost`에서는 SDK의 로컬 모드가 테스트 스토어를 제공합니다.

## 웹에서 중요한 내보내기 설정 {#export-settings-that-matter-on-the-web}

- **상대 경로로 번들링하세요.** Vite에서는 `base: "./"`입니다. 슬래시로 시작하는 루트 절대 경로는 게임 자체 오리진에서 깨지며 `absolute_path` 경고를 일으킵니다. [기술 요구 사항](https://docs.zokogames.com/kr/requirements/technical#relative-paths-only)을 참고하세요.
- **사전 압축하지 마세요.** Unity와 달리 Phaser는 일반 파일 이름을 요청합니다. `.br`이나 `.gz`로 끝나는 파일은 `Content-Encoding`과 함께 서빙되지만 페이지는 여전히 일반 이름을 요청하므로, 일반 파일로 배포하세요. 게임 오리진은 `.br` 또는 `.gz` 접미사를 일치하는 `Content-Encoding`과 함께 서빙하고, 게임 파일을 빌드 id 아래에서 1년간 캐시합니다. 일반 파일이 전송 중에 압축되는지는 포털이 문서화하거나 보장하지 않으며, 초기 다운로드 추정치는 압축하지 않은 크기를 사용하므로 파일을 작게 유지하세요.
- **크기.** 텍스처는 아틀라스로 묶고 오디오는 적당한 비트레이트로 유지하세요. 이후 레벨은 `preload`가 아니라 첫 장면 뒤에 로드하세요. 업로드 한도는 파일 1,500개, 압축 해제 후 250 MB, 초기 다운로드 약 50 MB(모바일은 20 MB)입니다. [첫 프레임을 빠르게](https://docs.zokogames.com/kr/guides/first-frame)를 참고하세요.
- **캔버스 크기.** 프레임 크기는 전체 화면과 회전에 따라 바뀝니다. `autoCenter: CENTER_BOTH`와 함께 쓰는 `Phaser.Scale.FIT`는 모든 [필수 해상도](https://docs.zokogames.com/kr/requirements/gameplay)에서 게임을 읽기 쉽게 유지합니다. 스타터 키트는 800 x 450을 사용합니다.
- **오디오 잠금 해제.** 브라우저는 첫 포인터 또는 키 이벤트 전까지 소리를 막습니다. Phaser의 사운드 매니저가 잠금 해제를 직접 처리합니다. 음악은 `create()`에서 무조건 시작하지 말고 버튼 입력이나 사운드 매니저의 `unlocked` 이벤트 이후에 시작하세요. 광고와 `syncMute`는 이를 대체하지 않습니다.
- **전체 화면.** 포털 프레임 바의 전체 화면 버튼을 쓰는 것이 좋습니다. 이 버튼은 포털의 컨트롤을 포함해 프레임 전체를 전체 화면으로 만듭니다. 프레임에 `allow="fullscreen"`이 있으므로 `this.scale.startFullscreen()`도 허용되지만, 이것은 캔버스만 전체 화면으로 만듭니다. 경쟁하는 버튼을 추가하지 마세요.
- **메모리.** 포털 프레임에는 스레드와 `SharedArrayBuffer`가 없지만(포털은 cross-origin isolation 헤더를 보내지 않습니다), Phaser에는 필요하지 않습니다.

광고, 로그인이나 계정 연결 창, 구매가 끝나면 키보드 포커스가 저절로 게임 프레임과 canvas로 돌아오므로, 클릭하지 않아도 플레이어의 키가 다시 작동합니다.

## 채팅 신고, 스크린샷, 저장소 미러

SDK 1.4.0부터: `zoko.gameApi.reportChat(report)`, `zoko.gameApi.onScreenshotRequest(handler)`, `zoko.data.mirrorLocalStorage({ prefix: "save_" })`가 있습니다. `ready()`는 `renderer.snapshot`을 기반으로 한 기본 스크린샷 제공자를 등록합니다. 건너뛰려면 플러그인 설정에 `screenshots: false`를 전달하세요. 미러는 `localStorage`만 다룹니다. 시뮬레이터는 세 가지를 모두 받아들입니다.

## 로컬 테스트 {#test-locally}

Phaser는 항상 브라우저에서 실행되므로 에디터 시뮬레이터가 없습니다. 게임을 `localhost`에서 서빙하면(스타터 키트는 `npm run dev`, 포트 5173으로 처리합니다) SDK가 자체 [로컬 모드](https://docs.zokogames.com/kr/getting-started/local-testing)로 시작합니다. 광고마다 3초짜리 오버레이가 대신 표시되고, 배너는 점선 상자이며, 가짜 플레이어 둘이 있고, 클라우드 저장은 `localStorage`로 갑니다. 사람들이 자주 걸려 넘어지는 점이 두 가지 있습니다.

- 마지막 광고로부터 3분 안에 두 번째 미드게임을 요청하면 `adCooldown`으로 실패합니다. 이것은 실제 규칙이므로 게임이 처리해야 합니다.
- 로컬 모드에서 `submitScore`는 받아들여지지만 눈에 보이는 일은 일어나지 않으며, 로컬 토큰은 서명되지 않습니다.

`?sdk_debug=true`를 추가하면 모든 호출을 로그로 남기고, `?ad_response=unfilled`는 광고 실패를 강제하며, `?user_response=logged_out`은 게스트 경로를 테스트합니다. 그다음 [미리보기 도구](https://www.zokogames.com/kr/preview)를 열어 로컬 주소를 입력하고 요구 사항 체크리스트가 채워지는 것을 지켜보세요.

## 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` |

## 알려진 함정 {#known-pitfalls}

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

- **`ready()` 이전의 `trackLoading`.** 플러그인의 로딩 브리지는 로더의 `start` 이벤트에서 SDK를 호출합니다. 그때까지 `ready()`가 완료되지 않았다면 그 호출은 `sdkNotInitialized`로 실패하고(거부된 promise이며, 이제 이벤트 핸들러 안에서 예외를 던지지 않습니다) 로딩은 보고되지 않습니다. 먼저 부트 씬에서 `await this.zoko.ready()`를 호출하고, 그다음 에셋을 로드하는 다음 씬의 `init()`에서 `trackLoading(this.load)`를 호출하세요.
- **`sdkNotLoaded`.** 스크립트가 차단되었거나 오프라인이고 `loadScript`가 꺼져 있거나 실패했습니다. 그래도 게임은 시작해야 합니다. 스타터 키트에 그 패턴이 있습니다.
- **비활성화된 SDK에 대한 호출은 `sdkDisabled`를 던집니다.** 위처럼 먼저 `sdk.environment !== "disabled"`를 확인하세요. 그렇지 않으면 처리되지 않은 rejection이 콘솔에 나타납니다.
- **광고 뒤에도 소리가 음소거된 상태로 남음.** 광고 중에 다른 무언가가 `sound.mute`를 바꾼 것입니다. 플러그인은 포털의 `muteAudio` 값, 또는 `adStarted` 시점에 본 값을 복원합니다.
- **`this.zoko`가 undefined.** 플러그인을 `mapping: "zoko"`로 등록하거나, `withZoko(Phaser.Scene)`를 확장하고 키를 `ZokoPlugin`으로 유지하세요.
- **배너가 엉뚱한 곳에 표시됨.** `requestBannerAt`은 설정된 게임 크기를 사용해 게임 좌표를 변환합니다. Scale Manager 모드를 확인하세요.
- **보상이 두 번 지급됨.** 버튼을 누를 때가 아니라 `finished === true`일 때만 지급하세요.

## 다음 단계 {#next}

- 다른 렌더러를 쓰는 순수 JavaScript: [순수 HTML5, Three.js, PixiJS](https://docs.zokogames.com/kr/engines/html5-libraries).
- 모든 엔진 한눈에 보기: [엔진 개요](https://docs.zokogames.com/kr/engines/overview).
- 업로드: 빌드 출력을 `index.html`이 압축 파일의 루트에 오도록 zip으로 묶고(스타터 키트의 `npm run package`가 이를 수행합니다), [제출 안내](https://docs.zokogames.com/kr/getting-started/submission-walkthrough)를 따르세요.
