There are two paths; pick the one that fits:
- A. You already have an HTML5 game (plain canvas, Phaser, PixiJS, Construct, Unity WebGL…): add one script tag and a few function calls. This is the path for external studios.
- B. You are building a new game inside the Leono Games repository: start from the Phaser template, which already wires up the SDK, test hooks and a smoke test.
A. Integrate an existing HTML5 game
1. Load the SDK
Add the script tag before your game script, in the index.html at the root of your bundle:
<script src="/sdk/v1/wsg-sdk.js"></script>
<script src="./game.js"></script>The SDK file lives on the games origin itself (https://games.leonogames.com/sdk/v1/wsg-sdk.js), so your bundle references it with the root path /sdk/v1/wsg-sdk.js and works in every environment without a rebuild. The script defines the global window.WSG.
Note
This is the only exception to the "relative paths only" rule. Every other file of your game must be loaded with a relative path such as ./game.js or ./assets/bg.png. To run the game on your machine, outside the portal, see how to serve the SDK on the Testing page.
2. Initialize
const ctx = await WSG.init({ gameId: 'tap-rush', version: '1.0.0' });
console.log(ctx.environment); // 'portal' | 'standalone' | 'disabled'gameIdis your game'sslugfromgame.json.- Wait for
init()before calling anything else. Async APIs called earlier are rejected with the codenot_initialized, and lifecycle calls such asgameplayStart()are ignored. init()never fails because of the environment: with no portal, or if the portal doesn't answer within 3 seconds, the SDK runs instandalonemode.
3. Report loading progress
The portal covers the iframe with a "Loading game" overlay that shows the percentage you report. The overlay only goes away when you call loadingFinished() (or after 30 seconds, in which case a load_timeout event is recorded).
WSG.loadingStart();
WSG.loadingProgress(40); // 0..100
WSG.loadingProgress(100);
WSG.loadingFinished(); // required: the game is ready for input4. Start and end a round
function startRound() {
WSG.gameplayStart(); // the player takes control
}
function endRound() {
WSG.gameplayStop(); // game over, back to the menu
}Call gameplayStart() when the player actually takes control, not when a menu opens. The server uses these two moments to count plays, award XP to players and decide whether to accept a score.
5. Submit the score
WSG.gameplayStop();
const result = await WSG.leaderboard.submit(score); // score is an integer ≥ 0
if (result.accepted) {
showBest(result.best, result.rank, result.improved);
} else {
console.warn('Score rejected:', result.reason); // e.g. 'too_fast', 'rate_too_high'
}Submit while gameplay is running or within 10 seconds after gameplayStop(). A rejected score still resolves normally (it doesn't throw) and carries a reason. Every reason is explained on the Scores and leaderboards page.
6. Ads between rounds
async function playAgain() {
await WSG.ads.interstitial({ placement: 'between_rounds' });
startRound();
}The SDK emits pause before the ad appears and resume after it closes. The portal keeps at least 60 seconds between two interstitials; an earlier call returns { shown: false, reason: 'cooldown' } and you simply carry on. Details on the Ads page.
7. Pause when the portal asks
WSG.on('pause', () => game.pause()); // tab hidden, an ad is about to show, the portal opens the leaderboard
WSG.on('resume', () => game.resume());
WSG.on('audio', (enabled) => game.setMuted(!enabled));on() works even before init(). On pause, stop your game loop and mute audio.
Full example
A tiny "tap the circle for 15 seconds" game in plain canvas that uses every step above. These three files make a complete submission: index.html and game.js sit in the dist/ build folder, with game.json next to that folder.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover"
/>
<link rel="icon" href="data:," />
<title>Tap Rush</title>
<style>
html,
body {
margin: 0;
height: 100%;
overflow: hidden;
background: #171430;
touch-action: none;
user-select: none;
-webkit-user-select: none;
}
#stage {
position: fixed;
top: env(safe-area-inset-top, 0px);
right: env(safe-area-inset-right, 0px);
bottom: env(safe-area-inset-bottom, 0px);
left: env(safe-area-inset-left, 0px);
}
canvas {
display: block;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="stage"><canvas id="game"></canvas></div>
<script src="/sdk/v1/wsg-sdk.js"></script>
<script src="./game.js"></script>
</body>
</html>// Tap Rush: tap the circle as many times as you can in 15 seconds.
const GAME_ID = 'tap-rush'; // matches "slug" in game.json
const ROUND_MS = 15000;
const ASSETS = []; // e.g. ['./assets/pop.mp3', './assets/bg.png']
const TEXT = {
vi: {
start: 'Chạm để bắt đầu',
again: 'Chạm để chơi lại',
best: 'Kỷ lục',
newBest: 'Kỷ lục mới!',
rank: 'Hạng',
rejected: 'Điểm không được ghi',
},
en: {
start: 'Tap to start',
again: 'Tap to play again',
best: 'Best',
newBest: 'New best!',
rank: 'Rank',
rejected: 'Score not recorded',
},
};
const stage = document.getElementById('stage');
const canvas = document.getElementById('game');
const g = canvas.getContext('2d');
const state = {
phase: 'menu', // 'menu' | 'playing' | 'over'
score: 0,
best: 0,
timeLeft: ROUND_MS,
rounds: 0,
message: '',
busy: false, // submitting a score or showing an ad
paused: false,
muted: false,
lastTs: 0,
target: { x: 0.5, y: 0.5 },
};
let T = TEXT.en;
let audio = null;
// Events from the portal (registering before init is fine)
WSG.on('pause', () => {
state.paused = true;
});
WSG.on('resume', () => {
state.paused = false;
state.lastTs = 0; // don't count the time spent paused
});
WSG.on('audio', (enabled) => {
state.muted = !enabled;
});
async function preload(urls) {
WSG.loadingStart();
let done = 0;
await Promise.all(
urls.map(async (url) => {
await (await fetch(url)).blob();
done += 1;
WSG.loadingProgress((done / urls.length) * 100);
}),
);
WSG.loadingFinished(); // the portal removes its overlay; the player can start tapping
}
function moveTarget() {
state.target.x = 0.15 + Math.random() * 0.7;
state.target.y = 0.3 + Math.random() * 0.55;
}
function startRound() {
state.phase = 'playing';
state.score = 0;
state.timeLeft = ROUND_MS;
state.message = '';
moveTarget();
WSG.gameplayStart(); // the player takes control
}
async function endRound() {
state.phase = 'over';
state.busy = true;
WSG.gameplayStop(); // round over; the score must be submitted within 10 seconds
try {
const result = await WSG.leaderboard.submit(state.score);
if (result.accepted) {
state.best = result.best;
state.message = result.improved ? T.newBest : `${T.rank} #${result.rank ?? '-'}`;
} else {
state.message = `${T.rejected} (${result.reason})`;
}
} catch (err) {
state.message = `${T.rejected} (${err.code})`;
}
state.rounds += 1;
state.busy = false;
}
async function playAgain() {
state.busy = true;
if (state.rounds % 2 === 0) {
// One ad every 2 rounds; the SDK emits pause/resume around the ad for you.
await WSG.ads.interstitial({ placement: 'between_rounds' });
}
state.busy = false;
startRound();
}
function unlockAudio() {
// iOS only allows audio after the player has touched the screen
if (!audio && window.AudioContext) audio = new AudioContext();
if (audio && audio.state === 'suspended') audio.resume();
}
function beep(freq) {
if (!audio || state.muted || state.paused) return;
const osc = audio.createOscillator();
const gain = audio.createGain();
gain.gain.value = 0.08;
osc.frequency.value = freq;
osc.connect(gain).connect(audio.destination);
osc.start();
osc.stop(audio.currentTime + 0.06);
}
canvas.addEventListener('pointerdown', (event) => {
unlockAudio();
if (state.paused || state.busy) return;
if (state.phase === 'menu') return startRound();
if (state.phase === 'over') return void playAgain();
const rect = canvas.getBoundingClientRect();
const dx = event.clientX - rect.left - state.target.x * rect.width;
const dy = event.clientY - rect.top - state.target.y * rect.height;
if (Math.hypot(dx, dy) <= Math.min(rect.width, rect.height) * 0.12) {
state.score += 1;
moveTarget();
beep(660);
}
});
function resize() {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(stage.clientWidth * dpr);
canvas.height = Math.round(stage.clientHeight * dpr);
g.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function draw() {
const w = stage.clientWidth;
const h = stage.clientHeight;
g.fillStyle = '#171430';
g.fillRect(0, 0, w, h);
g.fillStyle = '#ffffff';
g.textAlign = 'center';
g.font = 'bold 28px system-ui, sans-serif';
g.fillText(String(state.score), w / 2, 48);
if (state.phase === 'playing') {
g.font = '16px system-ui, sans-serif';
g.fillText(`${Math.ceil(state.timeLeft / 1000)}s`, w / 2, 76);
g.fillStyle = '#ff5a36';
g.beginPath();
g.arc(state.target.x * w, state.target.y * h, Math.min(w, h) * 0.12, 0, Math.PI * 2);
g.fill();
} else {
g.font = 'bold 20px system-ui, sans-serif';
g.fillText(state.phase === 'menu' ? T.start : T.again, w / 2, h / 2);
g.font = '16px system-ui, sans-serif';
g.fillText(state.message || `${T.best}: ${state.best}`, w / 2, h / 2 + 32);
}
}
function frame(ts) {
const dt = state.lastTs ? Math.min(ts - state.lastTs, 100) : 0;
state.lastTs = ts;
if (state.phase === 'playing' && !state.paused) {
state.timeLeft -= dt;
if (state.timeLeft <= 0) {
state.timeLeft = 0;
void endRound();
}
}
draw();
requestAnimationFrame(frame);
}
async function boot() {
const ctx = await WSG.init({ gameId: GAME_ID, version: '1.0.0' });
T = TEXT[ctx.locale] || TEXT.en;
const me = await WSG.leaderboard.me(); // current best score, null if never played
if (me) state.best = me.score;
resize();
window.addEventListener('resize', resize);
await preload(ASSETS);
requestAnimationFrame(frame);
}
boot();{
"slug": "tap-rush",
"version": "1.0.0",
"title": "Tap Rush",
"description": {
"vi": "Chạm vào vòng tròn càng nhiều càng tốt trong 15 giây.",
"en": "Tap the circle as many times as you can in 15 seconds."
},
"category": "casual",
"tags": ["one-tap", "timing", "tap"],
"orientation": "any",
"controls": ["tap", "mouse"],
"thumbnail": "./thumbnail.png",
"limits": {
"maxScore": 200,
"maxScorePerSecond": 12,
"minDurationMs": 10000,
"scoreOrder": "desc"
},
"build": { "command": "echo prebuilt", "outDir": "dist" },
"author": { "name": "Your Studio", "url": "https://example.com" }
}How the limits were chosen: a fast human taps about 8 times per second, so maxScorePerSecond = 8 × 1.5 = 12. A round lasts 15 seconds, so real scores rarely pass 120; maxScore 200 leaves headroom. Every round lasts at least 15 seconds, so minDurationMs is 10000 to allow for network delay. The full method is on the game.json page.
Run the example locally by following the Testing page, then read Submitting and publishing to send your submission.
B. A new game from the Phaser template
This path is for teams with access to the Leono Games repository. The packages/game-template template is a Phaser 3 + Vite + TypeScript game already wired to the SDK through the internal @wsg/game-kit package, with Boot → Preload → Menu → Game → GameOver scenes, test hooks and a Playwright smoke test.
1. Create the game
pnpm wsg create my-game # copy the template to games/my-game, set slug and title, run pnpm install
pnpm sync:sdk # build the SDK and copy it to .data/games/sdk/v1
pnpm dev:games # games-server at http://localhost:4000 (keep it in its own terminal)
pnpm --filter my-game dev # Vite at http://localhost:5173Then edit games/my-game/game.json: title, description, category, tags, orientation, controls and, most importantly, limits. Check it with pnpm wsg validate games/my-game.
2. The SDK plugin
The template's src/main.ts initializes the SDK, then attaches WsgPhaserPlugin to the game:
import Phaser from 'phaser';
import { createScaleConfig, resolveWsg, wsgPluginConfig } from '@wsg/game-kit';
import { BACKGROUND_COLOR, GAME_ID, GAME_VERSION, ORIENTATION } from './config';
import { setLocale } from './i18n';
import { Boot } from './scenes/Boot';
import { Game } from './scenes/Game';
import { GameOver } from './scenes/GameOver';
import { Menu } from './scenes/Menu';
import { Preload } from './scenes/Preload';
async function boot(): Promise<Phaser.Game> {
const wsg = await resolveWsg(); // window.WSG from the script tag; falls back to the bundled ESM build
const ctx = await wsg.init({ gameId: GAME_ID, version: GAME_VERSION }); // GAME_ID = slug from game.json
setLocale(ctx.locale);
return new Phaser.Game({
type: Phaser.AUTO,
parent: 'game',
backgroundColor: BACKGROUND_COLOR,
scale: createScaleConfig(ORIENTATION),
scene: [Boot, Preload, Menu, Game, GameOver],
plugins: { global: [wsgPluginConfig({ wsg })] }, // every scene gets this.wsg
});
}
boot();The plugin does most of the integration for you:
| Task | How the plugin handles it |
|---|---|
loadingStart, loadingProgress | Listens to the loader of the Preload scene |
loadingFinished | When the Menu scene is created for the first time |
gameplayStart / gameplayStop | When the Game scene starts, resumes, wakes / pauses, sleeps, shuts down |
pause / resume from the portal | game.loop.sleep() / game.loop.wake() and mutes audio |
audio(false) | Mutes audio; AudioManager saves the player's own mute choice in WSG.storage |
3. Submit the score from a scene
// Trimmed from the template. The Game scene has just paused, so the plugin already called gameplayStop(); submit now.
const result = await this.wsg.submitScore(this.score); // never throws: errors come back as accepted: false
console.log(result.accepted ? `Rank ${result.rank}` : `Rejected: ${result.reason}`);
const sdk = this.wsg.sdk; // this is WSG: ads, storage, share, leaderboard
await sdk.storage.set({ best: state.best, runs: state.runs });
if (state.gameOverCount % 2 === 0) {
await sdk.ads.interstitial({ placement: 'between_rounds' });
}When your game pauses itself (the player hits a pause button) without using scene.pause(), call this.wsg.gameplayStop() and this.wsg.gameplayStart() yourself.
4. Test and release
pnpm --filter my-game test:e2e # build, deploy to the local games-server, Playwright smoke test
pnpm wsg publish games/my-gamepnpm wsg publish runs validate → build → upload → registration with the API. The template's build references the SDK by its root path /sdk/v1/wsg-sdk.js by default (set WSG_SDK_URL to change it), so the same build works on a local games-server on any port and on the real games origin; under vite dev or vite preview the template proxies /sdk/ to the games-server at WSG_GAMES_ORIGIN (default http://localhost:4000). Games created from the template before 2026-10-10 default to the absolute URL http://localhost:4000/sdk/v1/wsg-sdk.js: copy the template's new vite.config.ts, or set WSG_SDK_URL=/sdk/v1/wsg-sdk.js when building. Vite prints a can't be bundled without type="module" attribute warning for that script tag; that is intended, since the SDK must load separately from the games origin rather than be bundled. See also Engines and frameworks and Submitting and publishing.
