# コピー&ペーストの例: index.html 1 つ

このページは、何も変更せずに貼り付けて、実行し、zip にしてアップロードできる 1 つのファイルです。最初の提出に必要な SDK のすべての部分を使う、最小のゲームです。`init`、読み込みのシグナル、`gameplayStart` と `gameplayStop`、フォールバック付きのリワード広告 1 つ、そしてセーブです。所要時間は約 10 分です。ミッドゲーム広告と `happytime` を含む、2 ファイルのより長いチュートリアルは[15分で作る最小のゲーム](https://docs.zokogames.com/jp/getting-started/first-game)、コンソールまで含めた番号付きの道筋は[30 分で最初のゲームを公開](https://docs.zokogames.com/jp/getting-started/quick-start)です。

## 1. これを index.html として保存する

`coin-tap` という名前の空のフォルダーを作り、その中にこのファイルを `index.html` として保存します。ほかに必要なものはありません。

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

SDK がブロックされている場合や `SDK.environment` が `"disabled"` の場合でも、ゲームは動き続けます。`zoko()` はすべての呼び出しをスキップし、ポータルを必要とするボタンは非表示のままです。SDK スクリプトの URL は本物の `https://sdk.zokogames.com/zokogames-sdk-v1.js` です。このファイルをビルドにコピーしないでください。

## 2. 各部分の役割

| 部分 | SDK 呼び出し | 置かれている理由 |
| --- | --- | --- |
| `<head>` 内のスクリプトタグ | なし | `window.ZokoGames.SDK` を定義します。これがないと、アップロードレポートが `no_sdk` を警告します。 |
| `boot()` | `SDK.init()`、続いて `SDK.environment` | `init()` は最初に必須で、拒否されることはありません。失敗は `"disabled"` として現れます。 |
| 読み込み | `SDK.game.loadingStart()`、`SDK.game.loadingStop()` | 読み込み時間とプレイ時間を分けます。最初の画面がプレイできる状態になったら `loadingStop` を呼びます。 |
| **Play** とラウンドの終了 | `SDK.game.gameplayStart()`、`SDK.game.gameplayStop()` | `gameplayStart` は、プレビューのチェックリストが最初に待つ呼び出しです(読み込みから 20 秒以内)。`gameplayStop` はラウンドを閉じ、ウィンドウがフォーカスを失ったときにも実行されます。 |
| ボーナスボタン | `SDK.ad.requestAd("rewarded", { adFinished, adError })` | 報酬は `adFinished` の中だけで与えます。ベーシック公開ではポータルが `adsDisabled` を返すため、最初に目にするのはフォールバックの分岐です。 |
| ベストスコア | `SDK.data.getItem`、`SDK.data.setItem` | 同期で、文字列のみです。エラー時には `{ code, message }` をスローするため、`try` の中に置いています。 |

## 3. 自分のマシンで実行する

`localhost` では、SDK がすべての呼び出しに自分で応答します。ポータルもアカウントも不要です。フォルダーを HTTP で配信し(`file://` はローカルとして扱われません)、`?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
```

ページを開くと `[ZokoGames SDK] Local mode: ...` の行が 1 つ表示され、**Play** が有効になる前に `[ZokoGames SDK] call game.loadingStart` と `call game.loadingStop` が表示されます。**Play** を押すと `call game.gameplayStart`、10 秒後に `call game.gameplayStop` が表示されます。**Watch an ad for +5 seconds** を押すと、`Local ad (rewarded)` というラベルのプレースホルダーが 3 秒間ページを覆い、その後メッセージが "+5 seconds next round." に変わります。コンソールに `ZokoGames.SDK.environment` と入力すると `"local"` が表示されます。アドレスに `&ad_response=unfilled` を付けるとフォールバック("No ad right now. Play on.")を確認でき、`&ad_response=adsDisabled` を付けるとベーシック公開の状態を確認できます。すべてのスイッチは[テスト](https://docs.zokogames.com/jp/getting-started/local-testing)にあります。

次に[プレビューツール](https://www.zokogames.com/jp/preview)を開き、`http://localhost:8080/` と入力して **ゲームを読み込む** を押し、1 ラウンドプレイしてからボーナスボタンを押します。チェックリストでは **SDKを初期化(initを呼び出し)**、**loadingStopを呼び出し**、**gameplayStartを呼び出し**、**gameplayStopを呼び出し**、**リワード広告をリクエスト**、**Dataモジュールを使用** にチェックが付き、タイミングの行には最初の `gameplayStart` までの時間が 20 秒未満と表示されます。ミッドゲーム広告と `happytime` の項目は灰色のままですが、最初の提出の妨げにはなりません。

## 4. zip にする

`index.html` はアーカイブのルートに置く必要があります。最上位に 1 つのフォルダーがある形も受け付けられ、`__MACOSX` や `.DS_Store` などのシステムファイルは無視されます。

| システム | コマンドまたは操作 | 結果 |
| --- | --- | --- |
| macOS または Linux | `cd coin-tap && zip ../coin-tap.zip index.html` | フォルダーの隣に `coin-tap.zip` |
| Windows 10 または 11 | フォルダー内で `tar -a -c -f ..\coin-tap.zip index.html` を実行します | フォルダーの隣に `coin-tap.zip` |
| どのシステムでも、ファイルマネージャーで | フォルダー内のファイルを(フォルダーではなく)選択して圧縮します | `index.html` がルートにある zip |

`unzip -l coin-tap.zip`(macOS、Linux)または `tar -tf coin-tap.zip`(Windows)で確認してください。一覧には `index.html` が表示され、その前に何も付いていてはいけません。古い Windows PowerShell では、`Compress-Archive` が zip のエントリ名にバックスラッシュを書き込むことがあります。バリデーターはそれを `unsafe_path` として拒否するため、`tar` かファイルマネージャーを使ってください。

## 5. アップロードする

[30 分で最初のゲームを公開](https://docs.zokogames.com/jp/getting-started/quick-start#6-upload-and-read-the-report-5-minutes)のステップ 6 と 7 に従います。**ビルド** ステップの **ゲームのzipをここにドロップ** に `coin-tap.zip` をドロップします。SDK が検出され、エラーがない状態で「ビルドv1は検証に合格し、公開されました。」と表示されるはずです。**審査に提出** の前に、掲載情報には独自の説明、操作方法、タグ、カバーがまだ必要です。

## 次のステップ

- [15分で作る最小のゲーム](https://docs.zokogames.com/jp/getting-started/first-game): ミッドゲーム広告、`happytime`、ポータルのミュート設定を加えた、同じ考え方の例です。
- [SDK の概要](https://docs.zokogames.com/jp/sdk/introduction): `init`、環境、すべてのエラーコードを説明します。
- [トラブルシューティング](https://docs.zokogames.com/jp/guides/troubleshooting): コンソールが無反応のときや、アップロードが拒否されたときの対処です。
