# 15분 만에 만드는 최소 게임

이 페이지는 `index.html`과 `game.js` 두 파일로 된 작고 완전한 게임을 제공합니다. 빌드 단계 없이 순수 JavaScript를 사용합니다. 그대로 업로드할 수 있습니다. 검증기는 오류나 경고 없이 이를 받아들이고, 미리보기 체크리스트의 모든 필수 항목이 초록색이 됩니다. SDK를 익히는 데 쓰거나, 필요한 부분을 자신의 게임에 복사하세요.

시작하기 전에 브라우저와 폴더를 HTTP로 제공할 방법이 필요합니다(아래 명령은 Node.js와 `npx`를 사용합니다). 스튜디오는 5단계에서만 필요합니다. 만드는 방법은 [30분 만에 첫 게임 출시하기](https://docs.zokogames.com/kr/getting-started/quick-start)에 있습니다. 빌드, 환경 같은 용어는 [용어집](https://docs.zokogames.com/kr/getting-started/glossary)에서 설명합니다.

## 게임 내용

"Target Tap": 플레이어는 15초 동안 원을 최대한 많이 탭합니다. 게임의 각 부분은 SDK 기능을 하나씩 사용합니다.

| 게임에서 | SDK 호출 | 초록색이 되는 체크리스트 줄 |
| --- | --- | --- |
| 페이지가 열림 | `SDK.init()` | SDK 초기화됨 |
| 메뉴 준비 완료 | `SDK.game.loadingStart()`, `SDK.game.loadingStop()` | 게임이 준비되었을 때 loadingStop 호출됨 |
| 플레이어가 **Play**를 누름 | `SDK.game.gameplayStart()` | gameplayStart 호출됨; 첫 gameplayStart가 20초 이내 |
| 라운드가 끝나거나 플레이어가 게임 밖을 클릭함 | `SDK.game.gameplayStop()` | 일시정지, 메뉴, 게임 오버 시 gameplayStop 호출됨 |
| 각 라운드 뒤의 휴식 | `SDK.ad.requestAd("midgame", ...)` | 미드게임 광고가 요청됨; 광고 요청 전에 gameplayStop |
| 광고 후 플레이어가 다시 **Play**를 누름 | `SDK.game.gameplayStart()` | 광고가 끝난 뒤 플레이 재개 |
| **Watch an ad** 버튼 | `SDK.ad.requestAd("rewarded", ...)` | 보상형 광고가 요청됨 |
| 새 최고 점수 | `SDK.data.setItem()`, `SDK.game.happytime()` | 세이브에 데이터 모듈 사용됨; 멋진 순간에 happytime 호출됨 |
| 포털의 음소거 버튼 | `SDK.game.settings`, `SDK.game.addSettingsChangeListener()` | 없음. 심사자가 확인합니다 |

줄 표현은 콘솔에서 게임의 **미리보기 및 QA** 탭에 표시되는 것과 같습니다. 공개 미리보기 도구는 일부 줄에 더 짧은 표현(**loadingStop 호출**, **미드게임 광고 요청**, **Data 모듈 사용**)을 쓰며 광고 구간 규칙에 대한 줄은 없습니다. [테스트 체크리스트](https://docs.zokogames.com/kr/getting-started/testing-checklist)에 둘 다 나와 있습니다.

## 1. index.html 만들기

`target-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>Target Tap</title>
  <!-- The SDK first, then your own code. -->
  <script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
  <style>
    html, body { margin: 0; height: 100%; overflow: hidden; background: #14161f; color: #fff; font: 18px sans-serif; }
    #game { position: relative; height: 100%; touch-action: none; user-select: none; }
    #hud { padding: 12px; }
    #target { position: absolute; width: 64px; height: 64px; border: 0; border-radius: 50%; background: #ffc531; }
    #panel { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; }
    [hidden] { display: none !important; }
    button { font: inherit; padding: 10px 20px; }
  </style>
</head>
<body>
  <div id="game">
    <div id="hud">Score <b id="score">0</b> | Time <b id="time">15</b> | Best <b id="best">0</b></div>
    <button id="target" aria-label="Target" hidden></button>
    <div id="panel">
      <h1>Target Tap</h1>
      <p>Tap the circle as often as you can in 15 seconds.</p>
      <button id="play" disabled>Play</button>
      <button id="reward" hidden>Watch an ad: +5 seconds next round</button>
      <p id="msg"></p>
    </div>
  </div>
  <script src="game.js"></script>
</body>
</html>
```

SDK 스크립트는 `<head>`에서 `game.js`보다 먼저 로드되며, 모든 경로는 상대 경로입니다. **Play** 버튼은 처음에는 비활성화되어 있다가 SDK가 준비되면 활성화됩니다.

## 2. game.js 만들기

이 파일을 `index.html` 옆에 `game.js`로 저장합니다.

```js
// Target Tap: hit the circle as often as you can in 15 seconds.
const SDK = window.ZokoGames && window.ZokoGames.SDK; // undefined if the script was blocked
const $ = (id) => document.getElementById(id);
let ready = false, playing = false, running = false, muted = false, audio = null;
let score = 0, best = 0, timeLeft = 0, bonus = 0, timer = 0;

// Every SDK call goes through here, so the game still runs when the SDK is missing,
// disabled or a call fails. SDK errors are plain { code, message } objects.
async function sdk(call) {
  if (!ready) return undefined;
  try {
    return await call();
  } catch (e) {
    console.warn("SDK:", e.code, e.message);
    return undefined;
  }
}

async function boot() {
  if (SDK) {
    await SDK.init(); // never rejects
    ready = SDK.environment !== "disabled"; // "zokogames", "local" or "disabled"
  }
  await sdk(() => SDK.game.loadingStart());
  best = Number((await sdk(() => SDK.data.getItem("best"))) || 0);
  if (ready) {
    muted = SDK.game.settings.muteAudio; // the portal's mute button
    SDK.game.addSettingsChangeListener((settings) => { muted = settings.muteAudio; });
  }
  $("best").textContent = best;
  $("reward").hidden = !ready;
  await sdk(() => SDK.game.loadingStop()); // the menu is ready
  $("play").disabled = false;
}

function beep() {
  if (muted) return;
  audio = audio || new AudioContext(); // created inside a tap, as browsers require
  const osc = audio.createOscillator();
  osc.connect(audio.destination);
  osc.start();
  osc.stop(audio.currentTime + 0.05);
}

// Starts or stops the round clock and tells the portal. Safe to call twice.
function setRunning(on) {
  if (on === running) return undefined;
  running = on;
  if (on) timer = setInterval(tick, 1000);
  else clearInterval(timer);
  return sdk(() => (on ? SDK.game.gameplayStart() : SDK.game.gameplayStop()));
}

function startRound() {
  score = 0;
  timeLeft = 15 + bonus;
  bonus = 0;
  playing = true;
  $("panel").hidden = true;
  $("target").hidden = false;
  moveTarget();
  render();
  setRunning(true); // input is live: gameplayStart
}

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

async function endRound() {
  playing = false;
  await setRunning(false); // gameplayStop, always before an ad
  $("target").hidden = true;
  $("panel").hidden = false;
  if (score > best) {
    best = score;
    $("best").textContent = best;
    await sdk(() => SDK.data.setItem("best", String(best))); // synchronous; throws on error
    await sdk(() => SDK.game.happytime());
  }
  await showAd("midgame"); // a natural break; the portal decides whether an ad plays
}

// Resolves true only when the ad played to the end.
async function showAd(type) {
  let finished = false;
  $("play").disabled = true;
  await sdk(() => SDK.ad.requestAd(type, {
    adStarted: () => audio && audio.suspend(), // silent while the ad plays
    adFinished: () => { finished = true; },
    adError: (e) => console.info("No ad:", e.code), // adsDisabled before full launch
  }));
  if (audio) audio.resume(); // after adFinished and after adError
  $("play").disabled = false;
  return finished;
}

$("reward").addEventListener("click", async () => {
  const earned = await showAd("rewarded");
  if (earned) bonus = 5; // the reward only after a finished ad
  $("msg").textContent = earned ? "+5 seconds next round" : "No ad right now";
});

$("target").addEventListener("pointerdown", (event) => {
  event.preventDefault();
  if (!running) return;
  score += 1;
  beep();
  moveTarget();
  render();
});

// Clicking outside the game or leaving the tab pauses the round; it continues on return.
window.addEventListener("blur", () => { if (playing) setRunning(false); });
window.addEventListener("focus", () => { if (playing) setRunning(true); });

function moveTarget() {
  const box = $("game").getBoundingClientRect();
  $("target").style.left = `${Math.random() * (box.width - 64)}px`;
  $("target").style.top = `${48 + Math.random() * (box.height - 112)}px`;
}

function render() {
  $("score").textContent = score;
  $("time").textContent = timeLeft;
}

$("play").addEventListener("click", startRound);
boot();
```

## 3. 로컬에서 실행하기

```bash
cd target-tap && npx http-server . -p 8080
# open http://localhost:8080/?sdk_debug=true
```

`localhost`에서 SDK는 로컬 모드로 실행되어 포털 없이 모든 호출에 스스로 응답합니다. 브라우저 콘솔에 `game.loadingStart`와 `game.loadingStop`에 대한 `[ZokoGames SDK]` 줄이 보이고, **Play**를 누르면 `game.gameplayStart`가 보여야 합니다. 15초 후 `Local ad (midgame)`이라고 표시된 자리표시자가 3초 동안 페이지를 덮습니다. 3분 안의 두 번째 라운드에는 midgame 광고가 나오지 않으며(콘솔에 `adCooldown`), 이는 예상된 동작입니다. 다른 응답을 강제하는 매개변수는 [테스트](https://docs.zokogames.com/kr/getting-started/local-testing)에 있습니다.

## 4. 미리보기 체크리스트를 초록색으로 만들기

1. [미리보기 도구](https://www.zokogames.com/kr/preview)를 열고 `http://localhost:8080/`을 입력한 뒤 **게임 불러오기**을 누릅니다.
2. 20초 안에 **Play**를 누르고 라운드가 끝날 때까지 원을 탭합니다.
3. 자리표시자 광고가 끝까지 재생되게 둡니다.
4. **Watch an ad: +5 seconds next round**를 누르고 그 광고도 끝까지 재생되게 둡니다.
5. 다시 **Play**를 누릅니다.

**요건 체크리스트**의 모든 항목이 완료로 표시되고 **배너 요청**만 남아야 합니다. 이 게임에는 배너가 없으며 배너는 선택 사항입니다. 게임을 업로드한 뒤(5단계) 콘솔에서 게임의 **미리보기 및 QA** 탭으로 똑같이 플레이하면 모든 필수 항목이 **통과**로 표시됩니다: **SDK 초기화됨**, **gameplayStart 호출됨**, **첫 gameplayStart가 20초 이내**, **일시정지, 메뉴, 게임 오버 시 gameplayStop 호출됨**, **미드게임 광고가 요청됨**, **광고 요청 전에 gameplayStop**, **광고가 끝난 뒤 플레이 재개**. 각 항목은 [테스트 체크리스트](https://docs.zokogames.com/kr/getting-started/testing-checklist)에서 설명합니다.

## 5. 압축하고 업로드하기

```bash
cd target-tap && zip ../target-tap.zip index.html game.js
unzip -l ../target-tap.zip
```

두 파일 모두 zip의 루트에 있어야 합니다. [30분 만에 첫 게임 출시하기](https://docs.zokogames.com/kr/getting-started/quick-start)에 설명된 대로 새 게임의 **빌드** 단계에서 `target-tap.zip`을 업로드합니다. 빌드가 오류와 경고 없이 검증을 통과하고, SDK 스크립트가 발견되고 init 호출이 감지되었다고 표시되어야 합니다.

## 코드가 규칙을 지키는 방식

- **SDK 없이도 게임이 실행됩니다.** 스크립트가 차단되었거나 환경이 `"disabled"`이면 `sdk()`는 모든 호출을 건너뛰고 모든 실패를 잡습니다. `init()` 자체는 절대 reject하지 않습니다.
- **플레이 시간을 정확히 측정합니다.** `gameplayStart`는 페이지 로드 시가 아니라 **Play**를 누를 때 전송됩니다. `gameplayStop`은 라운드가 끝날 때와 플레이어가 게임 밖을 클릭하거나 탭을 바꿀 때 전송되며, 이때 라운드도 일시정지됩니다.
- **광고는 휴식 시간에만.** midgame 광고는 라운드가 끝날 때 `gameplayStop` 뒤에 요청됩니다. 플레이어가 **Play**를 눌러야만 플레이가 재개되므로 모든 광고 뒤에는 `gameplayStart`가 따릅니다. 광고가 실제로 재생될지는 포털이 결정합니다(재사용 대기시간, 광고 차단기, 광고 없는 회원). 어떤 결과든 게임은 계속됩니다.
- **보상은 광고를 끝까지 본 뒤에만.** `bonus`는 `adFinished`가 실행되었을 때만 지급됩니다. `adError`이면 플레이어는 "No ad right now"를 보고 계속 플레이합니다.
- **소리는 플레이어를 따릅니다.** 첫 탭 전에는 아무 소리도 나지 않고, 포털의 음소거 설정은 시작 시와 변경될 때마다 게임을 음소거하며, 광고가 재생되는 동안 오디오는 일시중단됩니다. [오디오, 일시정지, 광고](https://docs.zokogames.com/kr/guides/audio-and-ads)를 참고하세요.
- **저장 데이터는 작습니다.** 키 하나에 짧은 문자열 하나로, 1,048,576바이트 한도보다 훨씬 작습니다. `getItem`과 `setItem`은 동기식이며 오류 시 예외를 던지고, `sdk()`가 이를 잡습니다.
- **휴대폰에서 동작합니다.** 포인터 이벤트가 마우스와 터치를 모두 다루고, `touch-action: none`이 페이지 스크롤을 막으며, 레이아웃은 어떤 프레임 크기든 채웁니다.

> [!IMPORTANT]
> 광고는 정식 출시 단계의 게임에서만 재생됩니다. 기본 출시 단계에서는 실제 포털이 `adsDisabled`(광고가 없으면 `unfilled`)로 응답하고 `adError` 분기가 실행됩니다. 로컬에서는 대신 3초짜리 자리표시자가 보입니다. 코드 경로는 같습니다.

## 다음 단계 {#next-steps}

- [30분 만에 첫 게임 출시하기](https://docs.zokogames.com/kr/getting-started/quick-start#6-upload-and-read-the-report-5-minutes): 이 게임을 업로드하고 제출하세요.
- [오디오, 일시정지, 광고](https://docs.zokogames.com/kr/guides/audio-and-ads)
