Game SDK
First-party HTML5 games uploaded to the portal can talk to the page that embeds them: report scores to the leaderboards, save progress to the player's account, unlock achievements and ask the player to sign in. The SDK is one small script served by the portal, with no build step required.
Add the script
Load the SDK from the portal (not from a copy inside your bundle) before your game code:
<script src="https://games.vikask.in/sdk/v1.js"></script>
<script>
GamesAlpha.ready().then((context) => {
if (context.signedIn) {
console.log(
`Hello ${context.player.displayName}, best so far: ${context.best}`,
);
}
});
</script>
The script exposes a GamesAlpha global. Every method returns a promise and never throws, so you can call them
without try/catch. Breaking changes will ship as /sdk/v2.js; v1.js keeps working.
Context
GamesAlpha.ready() resolves once the portal has answered, with the current context:
interface Context {
connected: boolean; // false when the game runs outside the portal
signedIn: boolean;
player: {
id: string;
displayName: string;
level: number;
verified?: boolean; // false until the email is verified; scores are saved but not ranked
} | null;
game: { id: string; slug: string } | null;
scoring: {
enabled: boolean;
order: "desc" | "asc"; // which direction counts as better
minScore: number;
maxScore: number;
decimals: number;
unit: string | null;
leaderboards?: boolean; // true when getLeaderboard() has a public board to read
} | null;
cloudSave: boolean;
best: number | null; // the player's personal best on this game
configVersion?: string | null; // version of the admin-managed config, see below
ads?: object | null; // in-game ads settings, used by adBreak()
}
The context changes while the game is open, for example when the player signs in from the prompt. Subscribe
with GamesAlpha.on("context", callback); it returns a function that removes the listener. The game page also
re-sends the context whenever it changes, so a game can update its UI without polling.
Scores
const result = await GamesAlpha.submitScore(1500, { durationMs: 42000 });
if (result.accepted) {
// result.best, result.rank, result.xpGained, result.level, result.levelUp, result.unlocked
}
Two rules apply:
- Scores need an account. For anonymous players the call resolves with
accepted: falseandreason: "anonymous", and the portal shows a sign-in prompt next to the game. CallsubmitScoreagain after the context reportssignedIn: true. - Scoring must be switched on for the game in the admin panel (with its range, direction, decimals and unit).
Until then every submission resolves with
reason: "disabled".
Scores outside the configured range and non-numeric values resolve with reason: "invalid". Submissions that
fail the portal's plausibility checks resolve with accepted: false and no reason. durationMs is optional but
feeds those checks, so send the time the round took when you have it.
Leaderboard
Show the same leaderboard as the game page inside your game:
const board = await GamesAlpha.getLeaderboard({ period: "weekly", limit: 10 });
// board.entries → [{ rank, playerId, displayName, avatarUrl, level, score, me }]
// board.me → { rank, score, verified } for a signed-in player, otherwise null
// board.total → number of ranked players in the period
period is "all" (default), "weekly" or "daily"; limit is 1–50 (default 10). The signed-in player's
row is always current, even right after submitScore, and is marked with me: true. When they rank below
limit, board.me.rank holds their position so you can pin it under the list.
Only players with a verified email are ranked. An unverified player keeps their scores: board.me has their
score with rank: null and verified: false, so show a "verify your email to get ranked" hint. Anonymous
players get the public list with me: null; offer requestSignIn() next to it. The call resolves with an empty
list and reason: "disabled" while scoring or leaderboards are off for the game, and "offline" outside the
portal, so keep a local "your runs" list as the fallback.
Cloud save
await GamesAlpha.saveProgress({ level: 3, coins: 120 }); // → { saved, version }
const saved = await GamesAlpha.loadProgress(); // → { data, version, updatedAt }
Progress is any JSON-serialisable value up to 16 KB per game and is stored on the player's account, so it
follows them across devices. Anonymous players get reason: "anonymous"; keep a localStorage fallback for
them. A value larger than 16 KB resolves with reason: "too_large". Saves are versioned: when a newer save
exists (for example from another tab) you get reason: "conflict"; call loadProgress() and save again.
Achievements
Achievements are defined per game in the admin panel. Rules of type "Score at least" unlock automatically when a qualifying score is accepted. Rules of type "Unlocked by the game" are yours to trigger:
const result = await GamesAlpha.unlockAchievement("first_boss");
// → { unlocked, alreadyUnlocked, xpGained }
Use the achievement key shown in the admin panel. Unknown keys and automatic rules resolve with
reason: "invalid".
Sign-in prompt
await GamesAlpha.requestSignIn(); // → { shown }
Asks the portal to open its sign-in dialog, for example from a "Save your score" button inside the game. When
the player signs in, the context is re-sent with signedIn: true.
Admin-managed config
Levels, word lists, texts and balancing values can be edited by the site owner in the admin panel, without a
new upload. Describe them with a JSON Schema, ship the defaults in your bundle and reference both from a
games-alpha.json file at the root of the zip:
{
"manifestVersion": 1,
"config": {
"schema": "config/schema.json",
"defaults": "config/defaults.json"
}
}
Read the config once at start-up and fall back to the bundled defaults:
const config = await GamesAlpha.getConfig(); // → { version, data } | null
const settings = config
? config.data
: await fetch("config/defaults.json").then((response) => response.json());
data is the effective config: your defaults with the owner's edits merged in (objects merge key by key,
arrays are replaced), validated against your schema. getConfig() resolves null offline, when the game has
no config or when the file cannot be loaded, so the fallback is required. A saved change applies the next time
the game loads; context.configVersion names the version the portal serves. The admin panel's preview can
answer with unsaved values, so do not persist the result.
The admin form is generated from the schema, which supports this subset:
| Keyword | Notes |
|---|---|
type | object, array, string, number, integer, boolean |
properties, required, additionalProperties | Property names match ^[A-Za-z_][A-Za-z0-9_]*$. |
items, minItems, maxItems, uniqueItems | |
enum | Rendered as a select, or as chips for an array of enum values. |
minimum, maximum, multipleOf | multipleOf also sets the input step. |
minLength, maxLength | |
format | word (2–24 lower-case letters) or color (#rrggbb). No pattern. |
title, description, default | Labels and help text in the form. |
x-ui | table, lines, chips, textarea, color or slider. |
$ref | Local references into $defs only. |
x-ui picks the editor: table shows an array of objects as an editable grid (one row per item), lines a
string array as one value per line, chips an array of enum values as toggles, textarea a long string,
color a colour picker and slider a number between minimum and maximum. Top-level properties become the
sections of the form. Schemas nest at most 6 levels and 2000 nodes; the manifest may be 16 KB, the schema
64 KB and the defaults 256 KB, and the defaults must validate. A manifest problem shows up as a bundle warning
in the admin panel and never fails the upload. When a new bundle's schema rejects the saved values, the game
gets that bundle's defaults until the owner fixes them.
Ads
In-game ads come from Google's H5 Games Ads program and run inside your game's page. The SDK loads Google's
Ad Placement API with the portal's settings; you only mark the moments where an ad may show. Declare them in
games-alpha.json:
{
"manifestVersion": 1,
"ads": {
"placements": [
{ "key": "preroll", "type": "preroll", "label": "On load" },
{
"key": "levelComplete",
"type": "next",
"label": "Level complete",
"every": 2
},
{
"key": "pause",
"type": "pause",
"label": "Pause menu",
"enabled": false
}
]
}
}
Keys match ^[a-zA-Z0-9_]{2,40}$ (up to 20 placements); enabled defaults to true and every to 1. The
type tells Google what kind of moment it is:
| Type | When to call it |
|---|---|
preroll | Once on load, before the game starts. Google shows at most one. |
start | After loading, when the player starts playing (for example "Play"). |
pause | When the player pauses the game. |
next | When the player moves on, for example to the next level. |
browse | When the player browses menus or options outside gameplay. |
Then call adBreak at those moments and continue when it resolves:
const result = await GamesAlpha.adBreak("levelComplete", {
beforeAd() {
game.pause();
audio.mute();
},
afterAd() {
audio.unmute();
game.resume();
},
}); // → { shown, status }
startNextLevel();
- Pause gameplay and mute your audio in
beforeAd, and undo both inafterAd.afterAdalways followsbeforeAd, also for aprerolland when Google never reports back. Run the preroll before your game loop and music start; a test or real preroll stays on screen until the player closes it. - The site owner switches placements on or off and changes
everyper game in the admin panel. Withevery: 2only every second call for that key requests an ad; the others resolve withstatus: "skipped". Google can still decide not to show an ad, for example because of its own frequency caps. shownistrueonly when the player saw an ad (status: "viewed"). Other statuses are Google's (dismissed,notReady,frequencyCapped,noAdPreloaded,timeout,error,ignored,invalid,other) or the SDK's:offline,disabled(ads or the placement are off),skipped,unavailable(the ad script was blocked) andtimeout(no ad started within 10 seconds).- In the Games Alpha app the portal serves these breaks with native ads instead of AdSense. Your code stays
the same; the statuses you may see there are
viewed,dismissed,notReady,frequencyCapped,errorandunavailable. - Call
GamesAlpha.setSound(on)whenever the player turns sound on or off, so ads follow the same choice. - Offline,
adBreakresolves with{ shown: false, status: "offline" }. Never block the game on an ad. - Ads only run once the site owner has an approved AdSense account with H5 Games Ads enabled, has entered the publisher ID in the portal settings and has ads on for your game. Test mode serves Google's test ads. Do not add your own AdSense script or ad pop-ups to the bundle.
Offline behaviour
When the game is opened directly, in the admin preview or on a page that does not answer the handshake, the
SDK goes into offline mode after about five seconds: ready() resolves with connected: false and every other
call resolves with reason: "offline". Nothing throws, so a game runs anywhere; treat the portal features as
progressive enhancements.
Reasons
Failed calls carry a reason:
| Reason | Meaning |
|---|---|
anonymous | The player is not signed in. Scores, saves and achievements need an account. |
disabled | Scoring, cloud save or player accounts are switched off in the admin panel. |
invalid | The value was out of range, malformed, or the achievement key is unknown. |
too_large | The progress payload exceeds 16 KB. |
conflict | A newer save exists; reload with loadProgress() and save again. |
unavailable | The portal could not reach the API right now; try again later. |
timeout | The portal did not answer within 10 seconds. |
offline | The game is not running inside the portal (or the handshake failed). |
Checklist
- Include
<script src="https://games.vikask.in/sdk/v1.js"></script>from the portal URL, before your game code. - Call
GamesAlpha.ready()once and keep the context; subscribe toon("context")for sign-in changes. - Report a score at the end of each round with
submitScore(score, { durationMs }), and show the shared board withgetLeaderboard()instead of a device-only high-score table. - Save progress at natural checkpoints, not on every frame, and keep a local fallback for anonymous players.
- Trigger manual achievements with the keys from the admin panel.
- If the owner should tune your game, ship
games-alpha.jsonwith a schema and defaults and read them withgetConfig(), falling back to the bundled defaults. - Call
adBreak(key, { beforeAd, afterAd })only at natural breaks, and pause and mute in the hooks. - Test the bundle both inside the portal and opened directly: the game must work in offline mode too.