# Phaser

I giochi Phaser girano nel browser, quindi hai due modi per integrarli. Usa il **plugin Phaser di ZokoGames** (`packages/sdk-engines/phaser`), che mette in pausa per te il ciclo di gioco e l'audio durante gli annunci, oppure chiama direttamente l'[SDK JavaScript](https://docs.zokogames.com/it/sdk/introduction). Entrambi usano le stesse chiamate, gli stessi limiti e gli stessi [codici di errore](https://docs.zokogames.com/it/sdk/introduction#errors). Il gergo come "midgame" e "rewarded" è spiegato nel [glossario](https://docs.zokogames.com/it/getting-started/glossary).

> [!NOTE]
> Stato (1.7.1): eseguito in un browser reale con Phaser 3.90.0 e 4.2.1 (2026-11-23). Se la prima importazione fallisce, invia al [supporto](https://docs.zokogames.com/it/business/support) la versione di Phaser e l'errore esatto. L'SDK JavaScript sottostante è la parte testata. La versione 1.7.1 (timeout di caricamento dello script) è stata rieseguita il 2026-11-23 in un browser e in produzione.

## Installazione {#install}

Scarica il plugin Phaser: [/sdk-engines/zokogames-phaser-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-phaser-1.7.1.zip) (gli stessi file della cartella nel repository).

[/sdk-engines/phaser.zip](https://www.zokogames.com/sdk-engines/phaser.zip) è sempre l'ultima versione. Checksum: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Indice di tutti i pacchetti per motore con versione, dimensione e SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

Scegli il percorso adatto al tuo gioco.

| Hai | Fai questo |
| --- | --- |
| Un gioco Phaser finito (JavaScript o TypeScript) | Copia i sorgenti del plugin nel tuo progetto e registra il plugin (sotto), oppure salta il plugin e usa l'[SDK puro](#without-the-plugin). |
| Un nuovo gioco | Parti dallo [starter kit](https://docs.zokogames.com/it/getting-started/starter-kits) `phaser`. Ha già il plugin in `src/zoko/`, quattro scene e uno script `npm run package`. |

Il plugin è TypeScript puro in `packages/sdk-engines/phaser/src/`: `ZokoPlugin.ts`, `ZokoClient.ts`, `ZokoAdFlow.ts`, `ZokoLoadingBridge.ts`, `ZokoSceneMixin.ts`, `types.ts` e un `index.ts` che li riesporta. Copia la cartella (per esempio in `src/zokogames-phaser/`) e importa da lì. Lo starter kit contiene gli stessi file, formattati, in `src/zoko/` e non ha `index.ts`, quindi lì importa `./zoko/ZokoPlugin`. La dipendenza peer è `phaser ^3.80.0`; lo starter kit stesso fissa Phaser 4.2 e ne supera il controllo dei tipi e la build.

Non devi aggiungere un tag script: quando `window.ZokoGames` manca, il plugin inietta da solo `https://sdk.zokogames.com/zokogames-sdk-v1.js` (passa `loadScript: false` per disattivarlo). Un tag script in `index.html` è comunque meglio, perché il validatore del caricamento cerca l'URL dell'SDK (vedi [validazione della build](https://docs.zokogames.com/it/requirements/build-validation)):

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

## Un ciclo di gioco funzionante con il plugin {#a-working-game-loop-with-the-plugin}

È un unico file che copre init, un annuncio midgame, un annuncio rewarded, inizio e fine del gameplay, salvataggio e caricamento e un punteggio in classifica. Ogni chiamata al portale è avvolta in modo che il gioco funzioni anche quando l'SDK è `disabled` (vedi la [modalità locale](#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` e `GAME_ID` vengono dalla [pagina delle classifiche](https://docs.zokogames.com/it/sdk/leaderboards#client-submission), che ha l'helper AES-GCM e spiega perché una classifica senza chiave di cifratura accetta `encryptedScore: ""` con il `score` in chiaro. Solo i giocatori con accesso effettuato entrano in classifica, e un invio che viola una regola della classifica viene scartato in silenzio mentre la chiamata si risolve comunque.

### Cosa ti offre il plugin {#what-the-plugin-gives-you}

| Membro | Comportamento (verificato in `ZokoPlugin.ts` e `ZokoAdFlow.ts`) |
| --- | --- |
| `ready()` | Carica lo script dell'SDK se `window.ZokoGames` manca, poi esegue `SDK.init()`. Viene rifiutata con `{ code: "sdkNotLoaded" }` quando lo script non si carica. Si può chiamare più volte senza rischi. Quando l'ambiente non è `disabled` registra anche i listener delle impostazioni e dell'offline e applica `muteAudio` a `game.sound.mute` (opzione `syncMute`, predefinita `true`). |
| `requestAd("midgame" \| "rewarded")` | Su `adStarted` mette in pausa tutto l'audio, lo silenzia e chiama `game.loop.sleep()`. Su `adFinished`, su `adError` e quando la richiesta stessa lancia un errore, risveglia il ciclo, ripristina il muto (il `muteAudio` del portale o quello che era prima) e riprende l'audio. Si risolve con `{ finished, error? }` e non viene mai rifiutata per problemi di annuncio. |
| `version` | La versione dell'SDK JavaScript per cui è stato scritto il plugin (`SDK_VERSION`). |
| `isAdPlaying` | `true` mentre un annuncio è sullo schermo. |
| `events` | Emette `adStarted`, `adFinished`, `adError(error)`, `settingsChange(settings)` e `offlineChange(offline)`. |
| `sdk` | L'SDK grezzo. Lancia `sdkNotInitialized` prima che `ready()` si sia risolta. |
| `ad`, `banner`, `user`, `data`, `store`, `analytics`, `gameApi`, `environment`, `isQaTool`, `client` | Il client tipizzato. `gameApi` è il modulo `game` dell'SDK (`this.game` è l'oggetto proprio di Phaser). `client` è il `ZokoClient` sottostante, che ha anche `achievements` (`this.zoko.client.achievements.list()`, `unlock(key)`, `onUnlock(cb)`; vedi [obiettivi](https://docs.zokogames.com/it/sdk/achievements)). |
| `trackLoading(this.load)` | Segnala un loader al portale: `loadingStart` su `start`, `loadingProgress` (da 0 a 100) su `progress`, `loadingStop` su `complete`. Restituisce una funzione che stacca i listener. |
| `rectFromGameBounds(x, y, w, h)` | Converte un rettangolo in coordinate di gioco (larghezza e altezza configurate del gioco) nel rettangolo normalizzato del canvas usato dalle chiamate dei banner. |
| `requestBannerAt(id, x, y, w, h, size?)` | Posiziona un contenitore DOM sopra un rettangolo in coordinate di gioco e vi richiede un banner; senza `size` richiede la dimensione responsive più grande che ci sta. |

Il file del plugin esporta anche `runAdFlow`, `bindLoadingProgress`, `withZoko` e `ZOKO_SDK_SCRIPT_URL`, e `ZokoClient` si può usare da solo nei test unitari (non richiede Phaser). `this.zoko` è disponibile anche tramite `class X extends withZoko(Phaser.Scene)` quando la chiave del plugin è `ZokoPlugin`.

## Senza il plugin {#without-the-plugin}

Se non vuoi un plugin, chiama l'SDK da solo. Inizializza prima di creare il `Phaser.Game` e scrivi l'helper degli annunci in modo che riprenda in entrambi gli esiti.

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

Mettere in pausa una sola scena con `scene.pause()` non basta: i tween, i timer delle altre scene e il gestore audio continuano a girare. `game.loop.sleep()` ferma l'intero passo di gioco. `requestAd` si risolve solo dopo che `adFinished` o `adError` è stato consegnato, quindi `await showAd(...)` è un punto sicuro in cui riprendere la logica di gioco.

**Modalità bambini.** Dalla versione 1.5.0 il wrapper lo espone: `SDK.game.settings.kidsMode` è true quando il gioco gira in modalità bambini (un gioco con il flag bambini, o un giocatore in modalità bambini); nascondi allora chat, stanze, richieste di accesso e schermate del negozio. Un portale che non invia il campo dà false, quindi continua a rispettare anche `disableChat`, che il portale imposta a true negli stessi casi. Per provarlo, aggiungi `?kidsMode=true` all'indirizzo della pagina in modalità locale. Vedi [modalità bambini](https://docs.zokogames.com/it/guides/kids-mode).

## Banner {#banners}

I contenitori dei banner sono elementi DOM accanto al canvas, non oggetti di gioco. Richiedili solo nelle schermate di menu e puliscili prima di giocare.

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

Con il plugin, `await this.zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250")` crea per te il contenitore su quel rettangolo del canvas. I banner vengono rifiutati mentre un annuncio video è in riproduzione (`videoAdPlaying`) e un contenitore può aggiornarsi solo ogni 30 secondi (`bannerCooldown`).

## Canale dati della stanza {#room-data-channel}

Aggiunto nell'SDK 1.3.0. Il canale dati della stanza permette ai giocatori di una stanza di scambiarsi piccoli messaggi JSON e di condividere un minuscolo stato che scrive solo l'host, così un semplice gioco multiplayer non ha bisogno di un server proprio. Serve per i dati di gioco, non per la chat di testo. Esiste dopo `updateRoom` (o dopo l'ingresso da un invito) e termina con `leftRoom`, richiede un giocatore con accesso effettuato e un portale con il realtime abilitato (altrimenti `roomUnavailable`), e ha questi limiti: 8 KB per messaggio o patch, 20 messaggi al secondo, 64 KB di stato, chiavi di stato da 1 a 40 caratteri di `A-Z a-z 0-9 _ . : -`. Sul portale i messaggi non tornano mai al mittente; il primo giocatore nella stanza è l'host. Le regole complete e i codici di errore (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) sono nel [modulo game](https://docs.zokogames.com/it/sdk/game#room-data-channel) e nella [guida al multiplayer](https://docs.zokogames.com/it/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

Il plugin non ha helper propri per le stanze; usa `game.room` dell'SDK tramite `this.zoko.gameApi.room`. È `undefined` su un SDK precedente alla 1.3.0, quindi controllalo prima. Metodi: `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()`, `selfId`, e `onMessage`, `onState`, `onMembers`, `onHostChange`, `onError`, ciascuno dei quali restituisce una funzione di annullamento dell'iscrizione. Su `localhost` la modalità locale dell'SDK fa comportare due schede del browser nello stesso id di stanza come due giocatori.

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

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

Controlla `isAvailable` prima di mostrare qualsiasi interfaccia di acquisto e verifica la proprietà sul tuo server. Vedi [acquisti in-game](https://docs.zokogames.com/it/sdk/purchases). Su `localhost` la modalità locale dell'SDK offre uno store di prova.

## Impostazioni di esportazione importanti sul web {#export-settings-that-matter-on-the-web}

- **Fai il bundle con percorsi relativi.** Vite: `base: "./"`. I percorsi assoluti dalla radice (che iniziano con una barra) si rompono sull'origine propria del gioco e generano l'avviso `absolute_path`. Vedi i [requisiti tecnici](https://docs.zokogames.com/it/requirements/technical#relative-paths-only).
- **Non precomprimere.** Phaser, a differenza di Unity, chiede nomi di file semplici. Un file che termina in `.br` o `.gz` viene servito con `Content-Encoding`, ma la tua pagina richiederebbe comunque il nome semplice, quindi fornisci file semplici. L'origine del gioco serve davvero un suffisso `.br` o `.gz` con il `Content-Encoding` corrispondente e mette in cache i file di gioco per un anno sotto l'id della build. Se i file semplici vengano compressi in transito non è documentato né garantito dal portale, e la stima del download iniziale usa le dimensioni non compresse, quindi tieni i file piccoli.
- **Dimensioni.** Raggruppa le texture in atlanti e tieni l'audio a bitrate modesti. Carica i livelli successivi dopo la prima scena invece che in `preload`. I limiti di caricamento sono 1.500 file, 250 MB decompressi e circa 50 MB di download iniziale (20 MB per i dispositivi mobili); vedi [primo frame veloce](https://docs.zokogames.com/it/guides/first-frame).
- **Dimensionamento del canvas.** La dimensione del frame cambia con lo schermo intero e la rotazione. `Phaser.Scale.FIT` con `autoCenter: CENTER_BOTH` mantiene il gioco leggibile a ogni [risoluzione richiesta](https://docs.zokogames.com/it/requirements/gameplay). Lo starter kit usa 800 per 450.
- **Sblocco dell'audio.** I browser bloccano l'audio fino al primo evento di puntatore o di tasto. Il gestore audio di Phaser gestisce da solo lo sblocco; avvia la musica da una pressione di pulsante o dopo l'evento `unlocked` del gestore audio, non incondizionatamente in `create()`. Gli annunci e `syncMute` non sostituiscono questo passaggio.
- **Schermo intero.** Preferisci il pulsante dello schermo intero nella barra del frame del portale: mette a schermo intero l'intero frame, compresi i controlli del portale. Il frame porta `allow="fullscreen"`, quindi `this.scale.startFullscreen()` è consentito, ma mette a schermo intero solo il tuo canvas; non aggiungere un pulsante concorrente.
- **Memoria.** Nel frame del portale non ci sono thread né `SharedArrayBuffer` (il portale non invia intestazioni di isolamento cross-origin), cosa di cui Phaser non ha bisogno.

Dopo una pubblicità, una richiesta di accesso o di collegamento dell'account o un acquisto, il focus della tastiera torna da solo alla cornice del gioco e al suo canvas, così i tasti del giocatore funzionano di nuovo senza un clic.

## Segnalazioni di chat, screenshot e mirror dell'archiviazione {#chat-reports-screenshots-and-storage-mirror}

Dalla versione 1.4.0 dell'SDK: `zoko.gameApi.reportChat(report)`, `zoko.gameApi.onScreenshotRequest(handler)` e `zoko.data.mirrorLocalStorage({ prefix: "save_" })`. `ready()` registra un provider di screenshot predefinito basato su `renderer.snapshot`; passa `screenshots: false` nella configurazione del plugin per saltarlo. Il mirror copre solo `localStorage`. Il simulatore accetta tutte e tre.

## Testare in locale {#test-locally}

Phaser gira sempre in un browser, quindi non c'è un simulatore nell'editor. Servi il gioco da `localhost` (lo starter kit lo fa con `npm run dev`, porta 5173) e l'SDK parte nella sua [modalità locale](https://docs.zokogames.com/it/getting-started/local-testing): un overlay di tre secondi sostituisce ogni annuncio, i banner sono riquadri tratteggiati, esistono due giocatori finti e i salvataggi cloud vanno in `localStorage`. Due cose mettono in difficoltà:

- Una seconda richiesta midgame entro tre minuti dall'ultimo annuncio fallisce con `adCooldown`. È la regola reale, quindi il tuo gioco deve gestirla.
- `submitScore` viene accettato e non mostra nulla di visibile in modalità locale, e il token locale non è firmato.

Aggiungi `?sdk_debug=true` per registrare ogni chiamata, `?ad_response=unfilled` per forzare il fallimento dell'annuncio e `?user_response=logged_out` per provare il percorso ospite. Poi apri lo [strumento Preview](https://www.zokogames.com/it/preview), inserisci il tuo indirizzo locale e guarda la lista dei requisiti spuntarsi.

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

## Problemi noti {#known-pitfalls}

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

- **`trackLoading` prima di `ready()`.** Il ponte di caricamento del plugin chiama l'SDK dall'evento `start` del loader. Se `ready()` non si è ancora risolto, quella chiamata fallisce con `sdkNotInitialized` (una promise rifiutata; non lancia più un'eccezione dentro il gestore dell'evento) e il caricamento non viene segnalato. Chiama prima `await this.zoko.ready()` in una scena di avvio, poi `trackLoading(this.load)` nell'`init()` della scena successiva che carica risorse.
- **`sdkNotLoaded`.** Lo script è stato bloccato o sei offline e `loadScript` è disattivato o è fallito. Il tuo gioco dovrebbe comunque avviarsi; lo starter kit mostra lo schema.
- **Le chiamate su un SDK disabilitato lanciano `sdkDisabled`.** Controlla prima `sdk.environment !== "disabled"`, come sopra, altrimenti una rejection non gestita arriva alla tua console.
- **L'audio resta muto dopo un annuncio.** Qualcos'altro ha cambiato `sound.mute` durante l'annuncio. Il plugin ripristina il valore `muteAudio` del portale, o il valore visto a `adStarted`.
- **`this.zoko` è undefined.** Registra il plugin con `mapping: "zoko"`, oppure estendi `withZoko(Phaser.Scene)` e mantieni la chiave `ZokoPlugin`.
- **Banner nel posto sbagliato.** `requestBannerAt` converte le coordinate di gioco usando la dimensione di gioco configurata; controlla la modalità dello Scale Manager.
- **Ricompensa assegnata due volte.** Assegnala solo con `finished === true`, mai alla pressione del pulsante.

## Avanti {#next}

- JavaScript puro con un altro renderer: [HTML5 puro, Three.js e PixiJS](https://docs.zokogames.com/it/engines/html5-libraries).
- Tutti i motori a colpo d'occhio: [panoramica dei motori](https://docs.zokogames.com/it/engines/overview).
- Caricamento: comprimi in zip l'output della build con `index.html` alla radice dell'archivio (`npm run package` nello starter kit lo fa), poi segui la [guida alla sottomissione](https://docs.zokogames.com/it/getting-started/submission-walkthrough).
