Приклад для копіювання: один index.html
Ця сторінка - це один файл, який можна вставити, запустити, запакувати в zip і завантажити без жодних змін. Це найменша гра, що використовує всі частини SDK, потрібні для першого надсилання: init, сигнали завантаження, gameplayStart і gameplayStop, одну нагородну рекламу із запасним варіантом і збереження. Це займає близько 10 хвилин. Довший туторіал із двох файлів із міжігровою рекламою та happytime - це Мінімальна гра за 15 хвилин; нумерований шлях, що охоплює й консоль, - Ваша перша гра в мережі за 30 хвилин.
1. Збережіть це як index.html#
Створіть порожню теку з назвою coin-tap і збережіть файл усередині неї як index.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() пропускає кожен виклик, а кнопки, яким потрібен портал, залишаються прихованими. URL скрипта SDK справжній, https://sdk.zokogames.com/zokogames-sdk-v1.js; не копіюйте файл у свій білд.
2. Що робить кожна частина#
| Частина | Виклик SDK | Навіщо вона потрібна |
|---|---|---|
Тег script у <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.
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: ... під час відкриття сторінки, [ZokoGames SDK] call game.loadingStart і call game.loadingStop, перш ніж Play стане активною, потім call game.gameplayStart, коли ви натиснете Play, і call game.gameplayStop через десять секунд. Натискання Watch an ad for +5 seconds на три секунди накриває сторінку заглушкою з підписом Local ad (rewarded), після чого повідомлення змінюється на "+5 seconds next round." Якщо ввести ZokoGames.SDK.environment у консолі, виведеться "local". Додайте &ad_response=unfilled до адреси, щоб побачити запасний варіант ("No ad right now. Play on."), і &ad_response=adsDisabled, щоб побачити, як виглядає базовий запуск. Усі перемикачі описано в розділі тестування.
Потім відкрийте інструмент попереднього перегляду, введіть http://localhost:8080/ і натисніть Завантажити гру, зіграйте один раунд і натисніть кнопку бонусу: чек-лист позначає SDK ініціалізовано (викликано init), Викликано loadingStop, Викликано gameplayStart, Викликано gameplayStop, Запитано нагородну рекламу і Використано модуль даних, а рядок часу показує час до першого gameplayStart менше ніж 20 с. Рядки для міжігрової реклами та happytime лишаються сірими, і це не блокує перше надсилання.
4. Запакуйте в zip#
index.html має лежати в корені архіву. Одна тека верхнього рівня теж приймається, а системні файли, як-от __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 поруч із текою |
| Будь-яка система, через файловий менеджер | Виберіть файли всередині теки (а не саму теку), потім стисніть їх | Zip з index.html у корені |
Перевірте його за допомогою unzip -l coin-tap.zip (macOS, Linux) або tar -tf coin-tap.zip (Windows): у списку має бути index.html без жодного префікса. Старіші версії Windows PowerShell можуть записувати зворотні скісні риски в назви записів zip через Compress-Archive; валідатор відхиляє їх як unsafe_path, тому користуйтеся tar або файловим менеджером.
5. Завантажте його#
Виконайте кроки 6 і 7 зі сторінки Ваша перша гра в мережі за 30 хвилин: перетягніть coin-tap.zip на «Перетягніть сюди zip-архів із грою» на кроці Білд. Ви маєте побачити «Білд v1 пройшов валідацію й опублікований» зі знайденим SDK і без помилок. Сторінці гри ще потрібні ваш власний опис, керування, теги й обкладинки, перш ніж натиснути Надіслати на перевірку.
Подальші кроки#
- Мінімальна гра за 15 хвилин: ті самі ідеї з міжігровою рекламою,
happytimeі налаштуванням вимкнення звуку на порталі. - Вступ до SDK:
init, середовища й кожен код помилки. - Усунення несправностей: коли консоль мовчить або завантаження відхилено.