# GameMaker

The wrapper (`packages/sdk-engines/gamemaker`) has two files. `zokogames.js` is an extension file for the **HTML5** target and talks to the browser SDK. `zokogames_sim.gml` is GML code for every other target (Windows, macOS, Linux and so on); it defines the same `zoko_*` functions and answers through the same **Async - Social** event layout, so a game runs unchanged in the IDE. The simulator needs GameMaker 2023.1 or newer (it uses `call_later`). A third file, `gml/examples.gml`, is a copy-and-paste controller. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.0): the JavaScript extension runs in a real browser against the SDK, and the function list is checked against `zokogames.js` and `zokogames_sim.gml` (names, argument counts, and which functions return a request id). Not built or run in the GameMaker IDE, so how the IDE reads the extension is not verified. Send the IDE and runtime versions and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails. The JavaScript SDK underneath is the tested part.
>
> Supported export target: HTML5 only. The GX.games (WebAssembly) export is not supported: its runner has no `GMS_API`, so Async - Social events are not delivered.

## Install

Download the GameMaker plugin: [/sdk-engines/zokogames-gamemaker-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-gamemaker-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/gamemaker.zip](https://www.zokogames.com/sdk-engines/gamemaker.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. In the IDE create an **Extension** resource named `ZokoGames`. Add `zokogames.js` and tick **HTML5** only. Add `zokogames_sim.gml` and tick every platform **except** HTML5. The simulator is written in the GML extension format of the manual (one `#define` section per function), so the IDE lists its functions, including internal `__zoko_*` helpers you can leave alone. In the file properties of `zokogames_sim.gml` set **Init Function** to `__zoko_sim_init`, so `global.zoko_sim_config` exists before your first Create event.
2. Declare every function from the [function list](#functions) in the extension, one entry each. GameMaker needs each function declared, with the argument count shown; use return type **double** for ids, numbers and flags and **string** for text and JSON; arguments are **double** for numbers and **string** for ids, keys and JSON. The names are exactly those in `zokogames.js` and `zokogames_sim.gml`. The README in the download has the full table of functions to declare, with their arguments and return values; before 1.6.1 it missed 14 functions and gave the wrong return value for 14 others, so declare from the 1.6.1 table.
3. HTML5 only: load `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the runner starts. The simplest way is the extension's own code injection: open the extension, choose **HTML5** under Platform Settings and add `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` under the `GM_HTML5_PostStyle` tag (it lands inside `<head>`). Alternatively copy the runtime's template `index.html`, add the tag, include it as an Included File and select it in the HTML5 game options. Without it every call fails with `sdkNotLoaded`.
4. Create a **persistent** controller object and paste `gml/examples.gml` into its Create and Async - Social events, or use the controller below. Call `zoko_init()` once, from that object.

## Which path

| You are | Do this |
| --- | --- |
| A GameMaker hobbyist with a finished game | Add the extension, paste the controller below, call `zoko_ad_request_ad` at natural breaks, export HTML5, upload. |
| Starting out | Develop on Windows or macOS with the simulator first, then test the HTML5 export on `localhost`. |

## How calls work

<!-- search: headings-only -->

- **Asynchronous** functions return a request id (a real number) at once. The result arrives later in the **Async - Social** event, never while the calling function is still running, so `async_load` stays valid in the event that made the call.
- **Synchronous** functions (state, settings and cloud save) return a value directly. Booleans are `1` or `0`; structured values are JSON strings, so wrap them in `json_parse`.

Every Async - Social event from the wrapper has `async_load[? "type"] == "zoko"`. Switch on `async_load[? "event"]`:

| Event | When | Fields |
| --- | --- | --- |
| `response` | An asynchronous call finished | `request_id`, `method`, `ok` (1 or 0), `result` (JSON text), `error_code`, `error_message` |
| `ad_started` | The ad began: pause and mute | `request_id` of the `zoko_ad_request_ad` call |
| `ad_finished` | The ad ended: resume | `request_id` |
| `ad_error` | The ad failed: resume | `request_id`, `error_code`, `error_message` |
| `settings_changed` | The portal changed mute or chat | `result` (JSON of `{ disableChat, muteAudio }`) |
| `offline_changed` | The player went offline or came back | `result` (`true` or `false`) |
| `auth_changed` | A player logged in | `result` (JSON of the user) |
| `join_room` | The player joined through an invite | `result` (JSON of the invite parameters) |
| `achievement_unlocked` | An achievement unlocked | `result` (JSON of the achievement) |
| `room_message`, `room_state`, `room_members`, `room_host_changed`, `room_left` (1.7.0), `room_error` | Room data channel, see [below](#room-data-channel) | `result` (JSON) |

`request_id` is 0 for events not tied to one call. Because `result` is JSON text, a string result such as a token is quoted JSON: pass it through `json_parse`.

## A working controller

One persistent object that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```gml
// ---- Create event (persistent object) ----
global.zoko_live = false;            // true when the SDK answered and is not disabled
global.in_ad = false;
global.reward_request = -1;          // request id of the rewarded ad in flight
global.best = 0;
zoko_init_request = zoko_init();
zoko_user_request = -1;

// ---- Async - Social event ----
if (async_load[? "type"] != "zoko") exit;
var _rid = async_load[? "request_id"];

switch (async_load[? "event"]) {
    case "response":
        var _ok = async_load[? "ok"] == 1;
        if (_rid == zoko_init_request) {
            global.zoko_live = _ok && zoko_environment() != "disabled";
            if (global.zoko_live) {
                audio_master_gain(json_parse(zoko_game_get_settings()).muteAudio ? 0 : 1);
                if (zoko_data_has_key("best")) global.best = real(zoko_data_get_item("best"));   // load: synchronous
                zoko_game_loading_stop();                // ends the portal's loading bar: the game can be played now
            }
            room_goto_next();                       // start the game whether or not the SDK is there
        } else if (_rid == zoko_user_request && _ok) {
            var _user = json_parse(async_load[? "result"]);
            // Leaderboard: only a signed-in player is ranked. "" is accepted only by a board WITHOUT an encryption key.
            if (_user != undefined) zoko_user_submit_score("", global.pending_score);
        } else if (!_ok) {
            show_debug_message(async_load[? "error_code"] + ": " + async_load[? "error_message"]);
        }
        break;

    // Pause on ad_started, resume on ad_finished AND ad_error.
    case "ad_started":
        global.in_ad = true;
        audio_pause_all();
        break;
    case "ad_finished":
        global.in_ad = false;
        audio_resume_all();
        if (_rid == global.reward_request) { global.coins += 50; global.reward_request = -1; }   // reward only here
        break;
    case "ad_error":
        global.in_ad = false;
        audio_resume_all();
        if (_rid == global.reward_request) global.reward_request = -1;
        show_debug_message("no ad: " + async_load[? "error_code"]);   // adCooldown, unfilled, adblock ...
        break;

    case "settings_changed":
        audio_master_gain(json_parse(async_load[? "result"]).muteAudio ? 0 : 1);
        break;
}
```

```gml
// ---- Anywhere in the game ----
// The player takes control / play stops:
if (global.zoko_live) zoko_game_gameplay_start();
if (global.zoko_live) zoko_game_gameplay_stop();

// Midgame ad at a natural break (game over, level end):
if (global.zoko_live) zoko_ad_request_ad("midgame");

// Rewarded ad from a button:
if (global.zoko_live) global.reward_request = zoko_ad_request_ad("rewarded");

// Save (synchronous, returns 1 or 0):
if (score > global.best) {
    global.best = score;
    if (global.zoko_live && !zoko_data_set_item("best", string(score))) show_debug_message(zoko_data_get_last_error());
}

// Leaderboard: ask for the user first; the controller's response branch submits.
global.pending_score = score;
if (global.zoko_live) zoko_user_request = zoko_user_get_user();
```

Game logic must not run while `global.in_ad` is true: check it at the top of your Step events (GameMaker has no automatic pause here). Two behaviours follow from the code in `zokogames.js`:

- A failed ad (unfilled, blocked, in cooldown) sends `ad_error` and then a `response` with `ok` 1 for the same request id. A request that cannot start at all (SDK disabled or not initialised) sends only a `response` with `ok` 0 and **no** `ad_error`, which is why the controller above never pauses before `ad_started`.
- The rewarded ad is tied to the request id returned by `zoko_ad_request_ad`; comparing `request_id` in `ad_finished` keeps a midgame ad from granting a reward.

About the leaderboard: a board **with** an encryption key counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and the wrapper has no encryption helper, so `""` works only for a board without a key. Otherwise compute scores on your server and use the server API. The player id for encryption is the `__dangerousUserId` field of the user JSON.

## Functions

<!-- search: headings-only -->

Declare these in the extension. The README of the wrapper has the same list with argument counts.

| JavaScript | GML |
| --- | --- |
| `SDK.init()` | `zoko_init()` (event `response`, method `init`; `result` is a JSON snapshot) |
| `SDK.environment` | `zoko_environment()`, `zoko_is_initialized()`, `zoko_is_qa_tool()`, `zoko_version()` |
| `SDK.ad.requestAd(type)` | `zoko_ad_request_ad("midgame")` or `"rewarded"` |
| `SDK.ad.hasAdblock()` | `zoko_ad_has_adblock()` (`result` is `true` or `false`) |
| `SDK.banner.requestBanner(...)` | `zoko_banner_request_banner(id, width, height, x, y, w, h, area_w, area_h)` |
| `SDK.banner.requestResponsiveBanner(id)` | `zoko_banner_request_responsive_banner(id, x, y, w, h, area_w, area_h)` |
| `clearBanner`, `clearAllBanners` | `zoko_banner_clear_banner(id)`, `zoko_banner_clear_all_banners()` |
| `SDK.game.gameplayStart()` / `gameplayStop()` | `zoko_game_gameplay_start()`, `zoko_game_gameplay_stop()` |
| `loadingStart`, `loadingStop`, `loadingProgress(n)` | `zoko_game_loading_start()`, `zoko_game_loading_stop()`, `zoko_game_loading_progress(n)` |
| `SDK.game.happytime()` | `zoko_game_happytime()` |
| `reportGameCompletedPercentage(n)` | `zoko_game_report_game_completed_percentage(n)` |
| `setGameContext(obj)`, `clearGameContext()` | `zoko_game_set_game_context(json)`, `zoko_game_clear_game_context()` |
| `updateRoom(u)`, `leftRoom()` | `zoko_game_update_room(json)`, `zoko_game_left_room()` |
| `inviteLink(p)` | `zoko_game_invite_link(json)` |
| `SDK.game.settings` | `zoko_game_get_settings()` (JSON text) |
| `isOffline`, `addOfflineListener` | `zoko_game_is_offline()` (1 or 0), event `offline_changed` |
| `isInstantMultiplayer` | `zoko_game_is_instant_multiplayer()` |
| `inviteParams`, `getInviteParam(k)` | `zoko_game_get_invite_params()` (JSON), `zoko_game_get_invite_param(key)` |
| `SDK.user.isUserAccountAvailable` | `zoko_user_is_account_available()` |
| `SDK.user.systemInfo` | `zoko_user_get_system_info()` (JSON text) |
| `SDK.user.getUser()` | `zoko_user_get_user()` (`result` is `null` when signed out) |
| `SDK.user.listFriends(opts)` | `zoko_user_list_friends(page, size)` |
| `SDK.user.getUserToken(opts)` | `zoko_user_get_user_token(signing_key_type)` (`""`, `"IN_GAME_AUTH"` or `"IN_GAME_AUTH_LEGACY"`) |
| `showAuthPrompt`, `showAccountLinkPrompt` | `zoko_user_show_auth_prompt()`, `zoko_user_show_account_link_prompt()` (`result` is `{"response":"yes"}` or `{"response":"no"}`) |
| `SDK.user.submitScore(opts)` | `zoko_user_submit_score(encrypted_score, score)` |
| `SDK.data.getItem(k)` | `zoko_data_get_item(key)` (`""` when missing), `zoko_data_has_key(key)` |
| `setItem`, `removeItem`, `clear` | `zoko_data_set_item(key, value)`, `zoko_data_remove_item(key)`, `zoko_data_clear()`; each returns 1 or 0, and `zoko_data_get_last_error()` returns the error JSON |
| `SDK.store.*` | `zoko_store_is_available()`, `zoko_store_get_catalog_items(limit, offset)`, `zoko_store_get_player_inventory(limit, offset)`, `zoko_store_buy_item(sku)`, `zoko_store_consume_item(sku, qty)`, `zoko_store_set_sandbox(bool)`, `zoko_store_get_purchase_token()` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `zoko_achievements_list()`, `zoko_achievements_unlock(key)`, social event `achievement_unlocked`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `SDK.analytics.trackOrder(p, o)` | `zoko_analytics_track_order(provider, order_json)` |
| `SDK.analytics.track(name, params)` (1.7.0) | `zoko_analytics_track(name, params_json)` |
| `ERROR_CODES` | `zoko_error_codes("store")` (comma separated; also `ad`, `banner`, `user`, `data`, `room`, `general`; empty text for an unknown module) |

Deprecated aliases also exist: `zoko_game_is_instant_join`, `zoko_game_show_invite_button`, `zoko_game_hide_invite_button`, `zoko_user_get_xsolla_user_token`.

Banner rectangles are in pixels of the area described by `area_w` and `area_h` (pass `0` for the browser window size). Request banners on menu rooms only: `zoko_banner_request_banner("menu", 300, 250, x, y, 300, 250, room_width, room_height)`, and `zoko_banner_clear_all_banners()` when leaving.

### Purchases

```gml
// Create
if (zoko_store_is_available()) shop_buy = zoko_store_buy_item("gems_100");

// Async - Social, event "response"
if (async_load[? "request_id"] == shop_buy) {
    if (async_load[? "ok"] == 1) {
        show_debug_message("paid: " + json_parse(async_load[? "result"]).itemId);   // verify on your server
        zoko_store_get_purchase_token();                                            // the token arrives as a response
    } else if (async_load[? "error_code"] == "purchaseCancelled") {
        show_debug_message("closed the checkout");
    } else if (async_load[? "error_code"] == "userNotAuthenticated") {
        zoko_user_show_auth_prompt();
    }
}
```

Check `zoko_store_is_available()` before any purchase UI and verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)).

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `zoko_game_is_kids_mode() == 1` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, switch on `kids_mode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

Declare seven more functions in the extension: `zoko_room_send(data_json)`, `zoko_room_send_to(member_id, data_json)`, `zoko_room_set_state(patch_json)`, `zoko_room_get_state()`, `zoko_room_get_members()`, `zoko_room_is_host()` and `zoko_room_self_id()`. The first three return a request id and answer with a `response` event; incoming data arrives as the social events `room_message`, `room_state`, `room_members`, `room_host_changed` and `room_error`, each with `result` as JSON text. On non-HTML5 targets the simulator is one room with one member that receives its own messages and state changes.

```gml
// Async - Social
switch (async_load[? "event"]) {
    case "room_message":
        var _m = json_parse(async_load[? "result"]);      // { from, data, direct, seq, ts }
        board_place(_m.data.cell, _m.data.mark);
        break;
    case "room_state":
        global.turn = json_parse(async_load[? "result"]).state.turn;
        break;
    case "room_left":
        // result: { reason: "left" | "kicked" | "closed" | "disconnected", roomId }
        break;
    case "room_host_changed":
        if (json_parse(async_load[? "result"]).isHost) zoko_room_set_state(json_stringify({ turn: "X" }));
        break;
}

// on a click
zoko_room_send(json_stringify({ cell: 4, mark: "X" }));
```

## HTML5 export settings that matter

<!-- search: headings-only -->

- **Export** HTML5 to a clean output folder, then zip its **contents** so `index.html` is at the archive root.
- **No pre-compression.** GameMaker writes plain files; upload them as is. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but GameMaker requests plain names, so renamed files would break. The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. In the HTML5 options use "Keep aspect ratio" or "Full scale" so the game fits every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Textures and audio.** Use texture groups so only the first room's textures are in the initial download; use OGG audio and stream music.
- **Loading.** If you report loading yourself, turn the built-in loading bar off and call `zoko_game_loading_start()` at the start of the loading room, `zoko_game_loading_progress(p)` a few times per second (each call produces a `response` event, so not every step), and `zoko_game_loading_stop()` when the player can act.
- **Audio unlock.** Browsers keep audio suspended until the first click or key press. Show a "click to play" room before music.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so `window_set_fullscreen(true)` can work from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Single thread.** The HTML5 target is single-threaded; keep Step events cheap while ads show, and keep memory modest for mobile browsers.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `zoko_game_report_chat(report_json)`, `zoko_game_set_screenshot_provider(enabled)` with `zoko_game_answer_screenshot(url)`, and `zoko_data_mirror_local_storage(options_json)` (stopped with `zoko_data_stop_mirror_local_storage()`). The canvas can only be read right after a frame is drawn, so call `zoko_game_screenshot_tick()` in the Post Draw event; a pending request is answered there (the social event is `screenshot_requested`, with a 1.5 second fallback). The mirror only sees `localStorage`; where your GameMaker runtime saves depends on its version, so test it. Failures arrive as the social event `mirror_error`. Non-HTML5 targets use the GML simulator.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`zoko_ad_request_ad("midgame")`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `ad_error` with `adCooldown` until your game has called `zoko_game_gameplay_start()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `zoko_game_gameplay_start()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **On a non-HTML5 target** the simulator answers one tick later with the same Social events. Edit `global.zoko_sim_config` before `zoko_init()`: `disabled`, `account_available`, `logged_in`, `username`, `user_id`, `friend_count`, `ad_behaviour` (`"fill"`, `"no_fill"` or `"error"`), `ad_duration` (seconds, default 1.5), `adblock`, `offline`, `mute_audio`, `disable_chat`, `store_available`, `verbose`. The simulated store has three items and an in-memory inventory; cloud save is in memory only.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **On an HTML5 export served from `localhost`** the browser SDK runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. A page opened from disk or served from another host is `disabled` unless you add `?useLocalSdk=true`.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded` in the `response`.** The HTML5 page has no SDK script tag.
- **Functions undefined on HTML5.** `zokogames.js` is not ticked for the HTML5 platform.
- **Functions undefined on Windows, macOS or Linux.** `zokogames_sim.gml` is not included for those platforms.
- **No events arrive.** The controller must be persistent, handle **Async - Social**, and filter on `async_load[? "type"] == "zoko"`.
- **`call_later` not found.** Update GameMaker to 2023.1 or newer.
- **`(no GMS_API)` in the console.** The game runs on the GX.games (WebAssembly) export, which is not supported. Export for HTML5.
- **Game stays paused or silent after an ad.** Resume on `ad_error` as well as `ad_finished`.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).
