# Esempio da copiare: un solo index.html

Questa pagina è un unico file che puoi incollare, eseguire, comprimere e caricare senza cambiare nulla. È il gioco più piccolo che usa ogni parte dell'SDK di cui ha bisogno un primo invio: `init`, i segnali di caricamento, `gameplayStart` e `gameplayStop`, una pubblicità rewarded con ripiego e un salvataggio. Richiede circa 10 minuti. Il tutorial più lungo, in due file, con una pubblicità midgame e `happytime` è [Crea un gioco minimo in 15 minuti](https://docs.zokogames.com/it/getting-started/first-game); il percorso numerato che include la console è [Il tuo primo gioco online in 30 minuti](https://docs.zokogames.com/it/getting-started/quick-start).

## 1. Salva questo come index.html {#1-save-this-as-index-html}

Crea una cartella vuota chiamata `coin-tap` e salva il file al suo interno come `index.html`. Non serve nient'altro.

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Coin Tap</title>
  <!-- The real SDK script. It must come before your own code. -->
  <script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
  <style>
    html, body { margin: 0; height: 100%; background: #14161f; color: #fff; font: 18px sans-serif; text-align: center; }
    main { padding-top: 12vh; }
    button { font: inherit; padding: 12px 24px; margin: 6px; }
    #coin { width: 120px; height: 120px; border-radius: 50%; border: 0; background: #ffc531; touch-action: manipulation; }
    [hidden] { display: none !important; }
  </style>
</head>
<body>
  <main>
    <h1>Coin Tap</h1>
    <p>Score <b id="score">0</b> | Time <b id="time">10</b> | Best <b id="best">0</b></p>
    <p><button id="coin" aria-label="Coin" hidden></button></p>
    <p id="msg">Loading...</p>
    <button id="play" disabled>Play</button>
    <button id="bonus" hidden>Watch an ad for +5 seconds</button>
  </main>
  <script>
    var SDK = window.ZokoGames && window.ZokoGames.SDK; // undefined if the script was blocked
    var $ = function (id) { return document.getElementById(id); };
    var usable = false, running = false, score = 0, best = 0, left = 10, extra = 0, timer = 0;

    // Every SDK call goes through here: if the SDK is missing, disabled or a call fails, the game still runs.
    // SDK errors are plain { code, message } objects, not Error instances.
    function zoko(call) {
      if (!usable) return Promise.resolve(undefined);
      return Promise.resolve().then(call).catch(function (e) {
        console.warn("SDK:", e && e.code, e && e.message);
      });
    }

    function boot() {
      var ready = SDK ? SDK.init() : Promise.resolve(); // init() never rejects
      return ready
        .then(function () { usable = !!SDK && SDK.environment !== "disabled"; })
        .then(function () { return zoko(function () { return SDK.game.loadingStart(); }); })
        .then(function () {
          if (usable) { // saves are synchronous and throw on error, so keep them inside try
            try { best = Number(SDK.data.getItem("best")) || 0; } catch (e) { console.warn("SDK:", e.code); }
          }
          $("best").textContent = best;
          $("bonus").hidden = !usable;
          return zoko(function () { return SDK.game.loadingStop(); }); // the first screen is ready
        })
        .then(function () { $("msg").textContent = "Tap the coin as often as you can."; $("play").disabled = false; });
    }

    function setRunning(on) {
      if (on === running) return;
      running = on;
      clearInterval(timer);
      if (on) timer = setInterval(tick, 1000);
      zoko(function () { return on ? SDK.game.gameplayStart() : SDK.game.gameplayStop(); });
    }

    function startRound() {
      score = 0; left = 10 + extra; extra = 0;
      $("play").hidden = $("bonus").hidden = true;
      $("coin").hidden = false;
      $("msg").textContent = "";
      render();
      setRunning(true); // input is live now: gameplayStart
    }

    function tick() { left -= 1; render(); if (left <= 0) endRound(); }

    function endRound() {
      setRunning(false); // round over: gameplayStop
      $("coin").hidden = true;
      $("play").hidden = false;
      $("bonus").hidden = !usable;
      $("msg").textContent = "Round over: " + score;
      if (score > best) {
        best = score;
        $("best").textContent = best;
        if (usable) {
          try { SDK.data.setItem("best", String(best)); } catch (e) { console.warn("SDK:", e.code); }
        }
      }
    }

    // Rewarded ad with a fallback: the reward is granted only when the ad finished; every other outcome just carries on.
    $("bonus").addEventListener("click", function () {
      var finished = false;
      $("bonus").disabled = $("play").disabled = true;
      zoko(function () {
        return SDK.ad.requestAd("rewarded", {
          adFinished: function () { finished = true; },
          adError: function (e) { console.info("No ad:", e.code); } // adsDisabled before full launch, unfilled, adblock...
        });
      }).then(function () {
        $("bonus").disabled = $("play").disabled = false;
        if (finished) { extra = 5; $("msg").textContent = "+5 seconds next round."; }
        else { $("msg").textContent = "No ad right now. Play on."; } // the fallback
      });
    });

    $("coin").addEventListener("pointerdown", function (e) { e.preventDefault(); if (running) { score += 1; render(); } });
    $("play").addEventListener("click", startRound);
    window.addEventListener("blur", function () { if (running) setRunning(false); });  // pause when focus leaves
    window.addEventListener("focus", function () { if (!$("coin").hidden) setRunning(true); });
    function render() { $("score").textContent = score; $("time").textContent = left; }
    boot();
  </script>
</body>
</html>
```

Il gioco continua a funzionare quando l'SDK è bloccato o `SDK.environment` è `"disabled"`: `zoko()` salta ogni chiamata e i pulsanti che richiedono il portale restano nascosti. L'URL dello script dell'SDK è quello reale, `https://sdk.zokogames.com/zokogames-sdk-v1.js`; non copiare il file nella tua build.

## 2. Cosa fa ogni parte {#2-what-each-part-does}

| Parte | Chiamata SDK | Perché c'è |
| --- | --- | --- |
| Tag script nell'`<head>` | nessuna | Definisce `window.ZokoGames.SDK`. Senza di esso il report di caricamento avvisa con `no_sdk`. |
| `boot()` | `SDK.init()`, poi `SDK.environment` | `init()` è richiesto per primo e non viene mai rifiutato; un fallimento si manifesta come `"disabled"`. |
| Caricamento | `SDK.game.loadingStart()`, `SDK.game.loadingStop()` | Separa il tempo di caricamento dal tempo di gioco. Chiama `loadingStop` quando la prima schermata è giocabile. |
| **Play** e la fine del round | `SDK.game.gameplayStart()`, `SDK.game.gameplayStop()` | `gameplayStart` è la prima chiamata che la checklist di Preview aspetta (entro 20 secondi dal caricamento); `gameplayStop` chiude il round e viene eseguito anche quando la finestra perde il focus. |
| Pulsante bonus | `SDK.ad.requestAd("rewarded", { adFinished, adError })` | Ricompensa solo in `adFinished`. Nel lancio base il portale risponde `adsDisabled`, quindi il ramo di ripiego è quello che vedrai per primo. |
| Miglior punteggio | `SDK.data.getItem`, `SDK.data.setItem` | Sincroni e solo con stringhe; lanciano `{ code, message }` in caso di errore, quindi stanno dentro `try`. |

## 3. Eseguilo sulla tua macchina {#3-run-it-on-your-machine}

Su `localhost` l'SDK risponde da sé a ogni chiamata: nessun portale, nessun account. Servi la cartella via HTTP (`file://` non conta come locale), poi apri l'indirizzo con `?sdk_debug=true`.

```bash
cd coin-tap
npx http-server . -p 8080
# or, without Node.js:
python3 -m http.server 8080
# open http://localhost:8080/?sdk_debug=true
```

Dovresti vedere una riga `[ZokoGames SDK] Local mode: ...` quando la pagina si apre, `[ZokoGames SDK] call game.loadingStart` e `call game.loadingStop` prima che **Play** diventi attivo, poi `call game.gameplayStart` quando premi **Play** e `call game.gameplayStop` dopo dieci secondi. Premendo **Watch an ad for +5 seconds** la pagina viene coperta per tre secondi da un segnaposto con l'etichetta `Local ad (rewarded)`, poi il messaggio cambia in "+5 seconds next round." Digitando `ZokoGames.SDK.environment` nella console viene stampato `"local"`. Aggiungi `&ad_response=unfilled` all'indirizzo per vedere il ripiego ("No ad right now. Play on."), e `&ad_response=adsDisabled` per vedere com'è il lancio base. Tutti gli interruttori sono nei [test](https://docs.zokogames.com/it/getting-started/local-testing).

Poi apri lo [strumento Preview](https://www.zokogames.com/it/preview), digita `http://localhost:8080/` e premi **Carica il gioco**, gioca un round e premi il pulsante bonus: la checklist spunta **SDK inizializzato (init chiamato)**, **loadingStop chiamato**, **gameplayStart chiamato**, **gameplayStop chiamato**, **Annuncio rewarded richiesto** e **Modulo dati usato**, e la riga dei tempi mostra il tempo fino al primo `gameplayStart` sotto i 20 s. Le voci per le pubblicità midgame e `happytime` restano grigie, il che non blocca un primo invio.

## 4. Comprimilo {#4-zip-it}

`index.html` deve stare nella radice dell'archivio. Viene accettata anche una cartella di primo livello, e i file di sistema come `__MACOSX` e `.DS_Store` vengono ignorati.

| Sistema | Comando o azione | Risultato |
| --- | --- | --- |
| macOS o Linux | `cd coin-tap && zip ../coin-tap.zip index.html` | `coin-tap.zip` accanto alla cartella |
| Windows 10 o 11 | Nella cartella, esegui `tar -a -c -f ..\coin-tap.zip index.html` | `coin-tap.zip` accanto alla cartella |
| Qualsiasi sistema, con un gestore di file | Seleziona i file dentro la cartella (non la cartella), poi comprimili | Uno zip con `index.html` nella radice |

Controllalo con `unzip -l coin-tap.zip` (macOS, Linux) o `tar -tf coin-tap.zip` (Windows): l'elenco deve mostrare `index.html` senza nulla davanti. Le versioni più vecchie di Windows PowerShell possono scrivere barre rovesciate nei nomi delle voci dello zip con `Compress-Archive`; il validatore le rifiuta come `unsafe_path`, quindi usa `tar` o il gestore di file.

## 5. Caricalo {#5-upload-it}

Segui i passaggi 6 e 7 di [Il tuo primo gioco online in 30 minuti](https://docs.zokogames.com/it/getting-started/quick-start#6-upload-and-read-the-report-5-minutes): trascina `coin-tap.zip` su **Trascina qui lo zip del tuo gioco** nel passaggio **Build**. Dovresti vedere "La build v1 ha superato la convalida ed è stata pubblicata" con l'SDK rilevato e nessun errore. La scheda del gioco richiede ancora la tua descrizione, i comandi, i tag e le copertine prima di **Invia per la revisione**.

## Prossimi passi {#next-steps}

- [Crea un gioco minimo in 15 minuti](https://docs.zokogames.com/it/getting-started/first-game): le stesse idee con una pubblicità midgame, `happytime` e l'impostazione di silenzio del portale.
- [Introduzione all'SDK](https://docs.zokogames.com/it/sdk/introduction): `init`, gli ambienti e ogni codice di errore.
- [Risoluzione dei problemi](https://docs.zokogames.com/it/guides/troubleshooting): quando la console resta in silenzio o il caricamento viene rifiutato.
