### Get Item Example (Construct - JavaScript) Source: https://docs.crazygames.com/sdk/data Example of retrieving data for a specific key using the data module in Construct. ```javascript const value = window.ConstructCrazySDK.data.getItem("keyName"); ``` -------------------------------- ### Leaderboard Configuration Example Source: https://docs.crazygames.com/sdk/leaderboards-mvp This JSON object demonstrates the required parameters for configuring a leaderboard, excluding the Leaderboard Guide which is set separately. It specifies score labeling, sorting, value constraints, cooldown, and scoring type. ```json { "encryptionKey": "dGhpcyBpcyBhIDMyLWJ5dGUga2V5IGZvciB0ZXN0aW4=", "scoreLabel": "POINTS", "scoreSorting": "DESC", "minValue": 0.0, "maxValue": 500000.0, "cooldownSeconds": 10, "isIncremental": false } ``` -------------------------------- ### Data Module API and Get Item Example (JavaScript - General) Source: https://docs.crazygames.com/sdk/data The data module API mirrors localStorage. Example shows how to retrieve a stored 'level' value. ```javascript clear(): void; getItem(key: string): string | null; removeItem(key: string): void; setItem(key: string, value: string): void; // example usage: CrazySDK.data.getItem("level"); ``` -------------------------------- ### Set Item Example (JavaScript) Source: https://docs.crazygames.com/sdk/data Example of how to set a value in the data module using JavaScript. ```javascript window.CrazyGames.SDK.data.setItem("gold", 100); ``` -------------------------------- ### System Info Object Example - Godot (Not Supported) Source: https://docs.crazygames.com/sdk/user An example of the system info object structure for Godot, though this method is not supported. It outlines the expected data fields. ```json { "countryCode": "US", "locale": "en-US", "device": { "type": "desktop" }, "os": { "name": "Windows", "version": "10" }, "browser": { "name": "Chrome", "version": "107.0.0.0" }, "applicationType": "web" } ``` ```json { "countryCode": "US", "locale": "en-US", "device": { "type": "desktop" }, "os": { "name": "Windows", "version": "10" }, "browser": { "name": "Chrome", "version": "107.0.0.0" }, "applicationType": "web" } ``` -------------------------------- ### Set Item Example (C#) Source: https://docs.crazygames.com/sdk/data Example of how to set an integer value in the data module using C#. ```csharp CrazySDK.Data.SetInt("gold", 100); ``` -------------------------------- ### Xsolla API Interaction Example (GML) Source: https://docs.crazygames.com/sdk/in-game-purchases Illustrates the process of interacting with the Xsolla REST API using http_request calls in GameMaker Language. This includes getting a user token, listing items, requesting payment tokens, and opening the paystation. ```gml // 1) Get user token (e.g., crazy_user_get_xsolla_user_token) then: // 2) Use http_request() calls to: // * List owned items: GET https://store.xsolla.com/api/v2/project/{project_id}/user/inventory/items // - Requires Bearer user token (in the header DS map set _header[? "Authentication"] = "Bearer "). // - Shows items the current user owns. // - Supports filtering (by SKU, group, type) and pagination (see Xsolla docs). // * List available items: GET https://store.xsolla.com/api/v2/project/{project_id}/items/virtual_items // - Returns a paged list of all virtual items in your store. // - Pass Bearer user token if you want personalized results (promotions, restricted items). // - Supports optional query params (see Xsolla docs). // * Request a payment token: POST https://store.xsolla.com/api/v2/project/{project_id}/payment/item/{item_sku} // - Requires Bearer user token. // - Use body to pass extra params: { "quantity": 5, "sandbox": true }. // - The HTTP Async Event will return the payment token. // 3) After you have a payment token open the paystation using the helper method: var cb = function(evt) { switch (evt.type) { case CRAZY_XSOLLA_EVENT_INIT: show_debug_message("IAP init"); break; case CRAZY_XSOLLA_EVENT_OPEN: show_debug_message("IAP open"); break; case CRAZY_XSOLLA_EVENT_LOAD: show_debug_message("IAP load"); break; case CRAZY_XSOLLA_EVENT_STATUS: show_debug_message("IAP status: " + json_stringify(evt.payload)); break; case CRAZY_XSOLLA_EVENT_STATUS_INVOICE: show_debug_message("IAP invoice: " + json_stringify(evt.payload)); break; ``` -------------------------------- ### Get User Data with Promises (HTML5) Source: https://docs.crazygames.com/sdk/intro Handle asynchronous SDK operations using Promises with .then() and .catch() if await is not available. This example shows how to retrieve user data. ```javascript // await example try { const user = await window.CrazyGames.SDK.user.getUser(); console.log(user); } catch (e) { console.log("Get user error: ", e); } // .then .catch example window.CrazyGames.SDK.user .getUser() .then((user) => console.log(user)) .catch((e) => console.log("Get user error: ", e)); ``` -------------------------------- ### Check if SDK is Started (GameMaker) Source: https://docs.crazygames.com/sdk/intro Verify if the CrazyGames SDK has been successfully initialized and is ready to be used in your GameMaker game. ```gml crazy_started() ``` -------------------------------- ### Loading Start/Stop Source: https://docs.crazygames.com/sdk/game Functions to track the start and end of game loading. `loadingStart` should be called when loading begins, and `loadingStop` when loading is complete. ```APIDOC ## Game Loading Start/Stop ### Description Functions to track the start and end of game loading. `loadingStart` should be called when loading begins, and `loadingStop` when loading is complete. ### Methods - `loadingStart()`: Call when game loading begins. - `loadingStop()`: Call when game loading is complete. ### Usage Examples **HTML5/Unity/GameMaker/Construct/Godot/Cocos:** ```javascript window.CrazyGames.SDK.game.loadingStart(); window.CrazyGames.SDK.game.loadingStop(); ``` **C++ (Construct):** ```cpp crazy_game_loading_start(); crazy_game_loading_stop(); ``` **Note:** These calls are not supported for Unity and Godot as loading is handled by their respective export processes. ``` -------------------------------- ### Access Game Settings (Python) Source: https://docs.crazygames.com/sdk/game Access game settings in Python. This example shows how to get the settings object, which contains options like `disableChat`. ```python crazy_game_settings() ``` -------------------------------- ### HTML Banner Container Setup Source: https://docs.crazygames.com/sdk/banners Define an HTML container for a banner with specified dimensions. ```html ``` -------------------------------- ### Basic User Token Retrieval (JavaScript) Source: https://docs.crazygames.com/sdk/user A minimal example demonstrating how to call `getUserToken` and catch potential errors. Useful for quick integration checks. ```javascript try { const token = await CrazySDK.user.getUserToken(); } catch (e) { } ``` -------------------------------- ### Gameplay Start/Stop Source: https://docs.crazygames.com/sdk/game Functions to track when users start playing or pause their game. `gameplayStart` should be called when gameplay begins or resumes, and `gameplayStop` when gameplay is interrupted. ```APIDOC ## Gameplay Start/Stop ### Description Functions to track when users start playing or pause their game. `gameplayStart` should be called when gameplay begins or resumes, and `gameplayStop` when gameplay is interrupted. ### Methods - `gameplayStart()`: Call when gameplay begins or resumes. - `gameplayStop()`: Call when gameplay is interrupted (e.g., entering a menu, pausing). ### Usage Examples **HTML5/Unity/GameMaker/Construct/Godot/Cocos:** ```javascript window.CrazyGames.SDK.game.gameplayStart(); window.CrazyGames.SDK.game.gameplayStop(); ``` **C# (Unity):** ```csharp CrazySDK.Game.GameplayStart(); CrazySDK.Game.GameplayStop(); ``` **C++ (Construct):** ```cpp crazy_game_gameplay_start(); crazy_game_gameplay_stop(); ``` **JavaScript (Construct):** ```javascript window.ConstructCrazySDK.game.gameplayStart(); window.ConstructCrazySDK.game.gameplayStop(); ``` **GDScript (Godot 3.x/4.x):** ```gdscript CrazyGames.Game.gameplay_start() CrazyGames.Game.gameplay_stop() ``` **C# (Godot 3.x/4.x):** ```csharp CrazyGames.Game.gameplay_start() CrazyGames.Game.gameplay_stop() ``` **JavaScript (General SDK):** ```javascript CrazySDK.game.gameplayStart(); CrazySDK.game.gameplayStop(); ``` ``` -------------------------------- ### Get System Info - Unity Source: https://docs.crazygames.com/sdk/user Retrieve system information in Unity games using the CrazySDK. This provides environmental data for the user. ```csharp var systemInfo = CrazySDK.User.SystemInfo; ``` -------------------------------- ### Submit Score with Callback Source: https://docs.crazygames.com/other/game-challenge This example demonstrates how to submit a score using the `addScore` method with a callback function to handle potential errors. ```APIDOC ## Submit Score with Callback ### Description Submits a score to the CrazyGames backend. The backend saves the score only if it's higher than the previous one. This method can be called frequently. ### Method `window.CrazyGames.SDK.user.addScore(score, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **score** (number) - Required - The score to submit. Can be an integer or a decimal. An error will occur if the score is not a valid number. - **callback** (function) - Required - A function that will be called upon completion. It receives an error object if an error occurred. ### Request Example ```javascript const callback = (error) => { if (error) { console.log("Error:", error); } }; window.CrazyGames.SDK.user.addScore(100, callback); ``` ### Response #### Success Response None (The score is processed asynchronously). #### Response Example None ``` -------------------------------- ### Submit Single Score Example Source: https://docs.crazygames.com/sdk/leaderboard-api Demonstrates how to submit a single user score to the leaderboard. Includes basic error handling for API requests. ```javascript // usage const api = new CrazyGamesScoreAPI('api-key'); // submit single score try { const result = await api.submitSingleScore('user123', 1500); console.log('Score submitted:', result); } catch (error) { console.error('Failed to submit score:', error.message); } ``` -------------------------------- ### Submit Score with Promise Source: https://docs.crazygames.com/other/game-challenge This example demonstrates submitting a score using async/await with a try-catch block for error handling. This is an alternative to the callback method. ```javascript try { await window.CrazyGames.SDK.user.addScore(100, callback); } catch (e) { console.log("Error:", e); } ``` -------------------------------- ### Initialize SDK and Check Instant Multiplayer (JavaScript) Source: https://docs.crazygames.com/sdk/game Demonstrates initializing the SDK and then checking the `isInstantMultiplayer` flag. This is the recommended approach for integrating the SDK and handling instant multiplayer logic. ```javascript const sdkElem = document.createElement("script"); sdkElem.type = "text/javascript"; sdkElem.src = "https://sdk.crazygames.com/Construct3CrazySDK-v3.js"; document.body.appendChild(sdkElem); sdkElem.onload = function () { window.ConstructCrazySDK.init().then(() => { const instantMultiplayer = window.CrazyGames.SDK.game.isInstantMultiplayer; console.log("Instant multiplayer:", instantMultiplayer); if (instantMultiplayer) { // should instantly create a new room/lobby } else { runtime.goToLayout("NextLayout"); } }); }; ``` -------------------------------- ### Initialize SDK Asynchronously (HTML5) Source: https://docs.crazygames.com/sdk/intro Manually initialize the v3 SDK using await. It's crucial to wait for initialization as the SDK is unusable until this process completes. Recommended to do this before the game starts, e.g., on the loading screen. ```javascript await window.CrazyGames.SDK.init(); ``` -------------------------------- ### Get Current User (GDScript - Not Supported) Source: https://docs.crazygames.com/sdk/user Examples for retrieving user data in Godot 3.x and 4.x, marked as not supported. ```gdscript var user = yield(CrazyGames.User.get_user_async(), "completed") ``` ```gdscript var user = await CrazyGames.User.get_user_async() ``` -------------------------------- ### SDK Initialization with Invite Link Detection Source: https://docs.crazygames.com/sdk/game Demonstrates how to initialize the SDK and immediately detect and process invite link parameters upon game load. ```APIDOC ## SDK Initialization with Invite Link Detection (Construct) ### Description Initializes the SDK and checks for invite link parameters during the initialization process. If parameters are found, the game navigates to a specific layout. ### Method `window.ConstructCrazySDK.init()` ### Event Handler `sdkElem.onload` ### Request Example ```javascript const sdkElem = document.createElement("script"); sdkElem.type = "text/javascript"; sdkElem.src = "https://sdk.crazygames.com/Construct3CrazySDK-v3.js"; document.body.appendChild(sdkElem); sdkElem.onload = function () { window.ConstructCrazySDK.init().then(() => { const roomName = window.ConstructCrazySDK.game.getInviteParam("roomName"); console.log("Room id:", roomName); if (roomName) { runtime.globalVars.roomName = roomName; runtime.goToLayout("RoomLayout"); } else { runtime.goToLayout("NextLayout"); } }); }; ``` ``` -------------------------------- ### Data Module Usage (Godot 4.x) Source: https://docs.crazygames.com/sdk/data Example of using the data module in Godot 4.x to set and get item values. ```gdscript CrazyGames.Data.data_set_item("gold", "100") var gold := 0 if CrazyGames.Data.data_has_key("gold"): gold = int(CrazyGames.Data.data_get_item("gold")) ``` -------------------------------- ### Initialize SDK and Handle Invite Link - Construct 3 Source: https://docs.crazygames.com/sdk/game Initializes the Construct 3 SDK and checks for invite link parameters upon loading. Redirects the player based on whether an invite link was used. ```javascript const sdkElem = document.createElement("script"); sdkElem.type = "text/javascript"; sdkElem.src = "https://sdk.crazygames.com/Construct3CrazySDK-v3.js"; document.body.appendChild(sdkElem); sdkElem.onload = function () { window.ConstructCrazySDK.init().then(() => { const roomName = window.ConstructCrazySDK.game.getInviteParam("roomName"); console.log("Room id:", roomName); if (roomName) { runtime.globalVars.roomName = roomName; runtime.goToLayout("RoomLayout"); } else { runtime.goToLayout("NextLayout"); } }); }; ``` -------------------------------- ### Data Module Usage (Godot 3.x) Source: https://docs.crazygames.com/sdk/data Example of using the data module in Godot 3.x to set and get item values. ```gdscript CrazyGames.Data.data_set_item("gold", "100") var gold = 0 if CrazyGames.Data.data_has_key("gold"): gold = int(CrazyGames.Data.data_get_item("gold")) ``` -------------------------------- ### Initialize SDK with Callback (Unity) Source: https://docs.crazygames.com/sdk/intro Manually initialize the Unity SDK. Do not call SDK methods until the provided callback is executed, as initialization is asynchronous. Avoid using RuntimeInitializeOnLoadMethod attributes for initialization. ```csharp CrazySDK.Init(() => { /** initialization finished callback */ }); ``` -------------------------------- ### Initialize SDK (Construct) Source: https://docs.crazygames.com/sdk/data Initialize the CrazyGames SDK for Construct. Ensure this is done before accessing SDK functionalities. ```javascript await window.ConstructCrazySDK.init(); ``` -------------------------------- ### GameMaker Initialize and Ad Handling (GML) Source: https://docs.crazygames.com/sdk/gamemaker/example This GML code initializes the SDK, sets up global variables for ad states, and handles user input to trigger different SDK functions like ad breaks, banner ads, invite links, and retrieving invite parameters. It also includes basic domain checking to prevent running outside of supported environments. ```gml /// CREATE EVENT domain = url_get_domain(); if ( !debug_mode && string_pos( ".crazygames.", domain ) == 0 && string_pos( ".1001juegos.com", domain ) == 0 ){ game_end(); } crazy_init(); global.ad_is_playing = false; global.rewarded_requested = false; global.show_banner_ads = false; global.ad_blocker_detected = false; if ( !variable_global_exists("user_info") ) { global.user_info = noone; } audio_play_sound( bgm_main, 0, true ); ``` ```gml /// STEP EVENT if ( !global.ad_is_playing ) { if ( keyboard_check_pressed( vk_enter ) ) { crazy_break("midgame"); } else if ( keyboard_check_pressed( vk_space ) ) { global.reward_requested = true; crazy_break("rewarded"); } else if ( keyboard_check_pressed( vk_escape ) ) { if ( global.show_banner_ads ) { global.show_banner_ads = false; crazy_hide_all_banners(); } else { global.show_banner_ads = true; args = [ { containerId: "crazy_banner_1", size: "320x50", }, { containerId: "crazy_banner_2", size: "300x250", }, ]; args_json = json_stringify( args ); crazy_request_banner( args_json ); crazy_show_banner("crazy_banner_1"); crazy_show_banner("crazy_banner_2"); } } else if ( keyboard_check_pressed( ord("P") ) ) { args = { room_id: 12345, game_mode:"pvp", duration: 60, }; args_json = json_stringify( args ); invite_link = crazy_invite_link( args_json ); show_message( "Invite link:\n" + string(invite_link) ); } else if ( keyboard_check_pressed( ord("L") ) ) { room_id = crazy_get_invite_param( "room_id" ); show_message( room_id ); } else if ( keyboard_check_pressed( ord("U") ) ) { show_message( "global.user_info:\n" + string(global.user_info) ); } } ``` -------------------------------- ### JavaScript Join Room Listener Source: https://docs.crazygames.com/sdk/game Adds and removes a listener for room join events in JavaScript. The listener is triggered when a user attempts to join a room, for example, through an invite link or friend list. It also covers checking `inviteParams` on game start if the game was launched from an invite. ```APIDOC ## addJoinRoomListener ### Description Adds a callback function to listen for room join events. This is useful when a user is invited to join a game room. ### Method `window.CrazyGames.SDK.game.addJoinRoomListener(listener)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **listener** (function) - Required - The callback function to execute when a room join event occurs. This function receives `inviteParams` as an argument. ### Request Example ```javascript function listener(inviteParams) { // send the user to the multiplayer room } window.CrazyGames.SDK.game.addJoinRoomListener(listener); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ## removeJoinRoomListener ### Description Removes a previously added room join listener. ### Method `window.CrazyGames.SDK.game.removeJoinRoomListener(listener)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **listener** (function) - Required - The callback function to remove. ### Request Example ```javascript window.CrazyGames.SDK.game.removeJoinRoomListener(listener); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ## inviteParams ### Description An object containing parameters passed when the game is launched via an invite link. This should be checked on game start to redirect the player to the correct room if the game was already running. ### Method `window.CrazyGames.SDK.game.inviteParams` ### Parameters None ### Request Example ```javascript // don't forget to check window.CrazyGames.SDK.game.inviteParams on game start // if it is not null, your game was already started from an invite link, and you should send the player to the correct room ``` ### Response #### Success Response (200) * **inviteParams** (object) - Contains invite details if the game was launched from an invite link, otherwise null. #### Response Example ```json { "inviteParams": { "key": "value" } } ``` ``` -------------------------------- ### Leaderboard Configuration Example Source: https://docs.crazygames.com/sdk/leaderboards This JSON object demonstrates the configuration parameters for a leaderboard, including encryption keys, score type, sorting, and validation thresholds. It is used for setting up leaderboards in your game. ```json { "encryptionKey": "dGhpcyBpcyBhIDMyLWJ5dGUga2V5IGZvciB0ZXN0aW4=", "apiKey": "sGrZXWMMtYZBoGHjD+YKJLg/9tlAso7R5iT3A2MOA24=", "scoreLabel": "POINTS", "scoreSorting": "DESC", "minValue": 0.0, "maxValue": 500000.0, "cooldownSeconds": 10, "isIncremental": false } ``` -------------------------------- ### Initialize SDK (GameMaker) Source: https://docs.crazygames.com/sdk/intro Initialize the CrazyGames SDK in GameMaker Studio. Provide success and error callback functions to handle the asynchronous initialization process. ```gml crazy_init( function() { show_debug_message("CrazyGames SDK initialized successfully!"); }, function(error) { show_debug_message("Failed to initialize CrazyGames SDK: " + string(error)); } ); ``` -------------------------------- ### Error Object Example Source: https://docs.crazygames.com/sdk/data Example of an error object that might be thrown by the data module, indicating a data limit was exceeded. ```json { "code": "dataLimitExcedeed", "message": "Game data when converted to a JSON string cannot exceed 1048576 bytes. Data was not saved" } ``` -------------------------------- ### Get Invite Link Parameter - C# Source: https://docs.crazygames.com/sdk/game Retrieves a specific parameter from an invite link. Use this to get data like room IDs when a player joins. ```csharp var roomName = CrazySDK.Game.GetInviteLinkParameter("roomName"); ``` -------------------------------- ### Get Invite Link Parameter - Godot Source: https://docs.crazygames.com/sdk/game Retrieves a specific parameter from an invite link in Godot. Use this to get data like room IDs when a player joins. ```gdscript var room_id = CrazyGames.Game.get_invite_link_param("roomId") ``` -------------------------------- ### Fetch User Inventory Items (JavaScript) Source: https://docs.crazygames.com/sdk/in-game-purchases Example of how to fetch a player's inventory items from Xsolla using the retrieved user token. Requires your Xsolla Project ID. ```javascript // obtain player's inventory example // xsollaProjectId will be provided by us const resp = await fetch( `https://store.xsolla.com/api/v2/project/${xsollaProjectId}/user/inventory/items`, { method: "GET", headers: { Authorization: `Bearer ${token}`, }, } ); ``` -------------------------------- ### Initialize CrazyGames SDK in Construct Source: https://docs.crazygames.com/sdk/intro Use this script in your Construct project's 'On start of layout' event to load and initialize the CrazyGames SDK. Ensure the next layout name is correctly set. ```javascript // don't forget to set the name of the next layout // that should be loaded after initialization const nextLayoutName = "CrazySDKDemo"; const sdkElem = document.createElement("script"); sdkElem.type = "text/javascript"; sdkElem.src = "https://sdk.crazygames.com/Construct3CrazySDK-v3.js"; document.body.appendChild(sdkElem); sdkElem.onload = function () { window.ConstructCrazySDK.init() .then(() => { runtime.goToLayout(nextLayoutName); }) .catch((e) => console.log("Failed to init CrazySDK", e)); }; sdkElem.onerror = function () { console.error("Failed to load Construct3CrazySDK script."); }; ``` -------------------------------- ### Get SDK Environment Source: https://docs.crazygames.com/sdk/intro Retrieve the current environment of the CrazyGames SDK. This is useful for conditional logic. ```javascript window.CrazyGames.SDK.environment; ``` -------------------------------- ### Fetch Player Inventory using Xsolla API Source: https://docs.crazygames.com/sdk/in-game-purchases This example shows how to fetch a player's inventory items from the Xsolla store API using a provided token and project ID. Ensure you have the correct authorization headers. ```javascript // obtain player's inventory example // xsollaProjectId will be provided by us const resp = await fetch( `https://store.xsolla.com/api/v2/project/${xsollaProjectId}/user/inventory/items`, { method: "GET", headers: { Authorization: `Bearer ${token}`, }, } ); ``` -------------------------------- ### Error Response Example: Unauthorized Source: https://docs.crazygames.com/sdk/leaderboard-api A 401 Unauthorized response indicating missing or invalid API key. ```json {"error": "Unauthorized"} ``` -------------------------------- ### Initialize Xsolla Token (C#) Source: https://docs.crazygames.com/sdk/in-game-purchases Initialize the Xsolla token for use with the Xsolla SDK in Unity. ```csharp XsollaToken.Create(token); ``` -------------------------------- ### Get Current User Source: https://docs.crazygames.com/sdk/user-linking/user-linking-unity Retrieves the currently logged-in user on CrazyGames. Returns null if the user is not logged in. ```APIDOC ## Get current user ### Description Fetches the details of the user currently logged into CrazyGames. If no user is logged in, it returns null. ### Method `GetUser(Action callback)` ### Endpoint N/A (SDK Method) ### Parameters #### Callback - **user** (PortalUser) - The user object if logged in, otherwise null. ### Code Example ```csharp CrazySDK.User.GetUser(user => { if (user != null) { Debug.Log("Get user result: " + user.username); } else { Debug.Log("User is not logged in"); } }); ``` ### Response #### Success Response (Callback) - **PortalUser** (object) - Contains user information if logged in. - **username** (string) - The username of the logged-in user. - **profilePictureUrl** (string) - The URL for the user's profile picture. ### Note If the user is not logged in, the `user` parameter in the callback will be `null`. ``` -------------------------------- ### Clear Data Example (JavaScript - Generic) Source: https://docs.crazygames.com/sdk/data Function to clear all data stored by the data module. This action is irreversible. ```javascript crazy_data_clear() ``` -------------------------------- ### Show Account Link Prompt (GML) Source: https://docs.crazygames.com/sdk/user Initiate the account linking process using GML. The callback function receives the response or an error object. ```gml crazy_user_show_account_link_prompt( function(resp) { show_debug_message("Account linked: " + json_stringify(resp)); }, function(err) { show_debug_message("Link failed: " + json_stringify(err)); } ); ``` -------------------------------- ### Get Current User (JavaScript - Alternative) Source: https://docs.crazygames.com/sdk/user An alternative JavaScript method to retrieve the current user's data. ```javascript const user = await CrazySDK.user.getUser(); ``` -------------------------------- ### Get Current User Source: https://docs.crazygames.com/sdk/user-linking/user-linking-html5-v3 Retrieve the currently logged-in user on CrazyGames. If the user is not logged in, the returned value will be null. ```javascript const user = await window.CrazyGames.SDK.user.getUser(); console.log("Get user result", user); ``` ```json { "username": "SingingCheese.TLNU", "profilePictureUrl": "https://images.crazygames.com/userportal/avatars/4.png" } ``` -------------------------------- ### Update Room Data (Unsupported - JavaScript) Source: https://docs.crazygames.com/sdk/game This example demonstrates a syntax for updating room data that is explicitly marked as not supported. ```javascript CrazySDK.game.updateRoom({ roomId: "123eu" }); ``` ```javascript CrazySDK.game.updateRoom({ isJoinable: true, inviteParams: { roomName: "123", region: "eu" }}); ``` ```javascript CrazySDK.game.updateRoom({ isJoinable: false}); ``` ```javascript CrazySDK.game.leftRoom(); ``` ```javascript CrazySDK.game.updateRoom({ roomId: "123eu", isJoinable: true, inviteParams: { roomName: "123", region: "eu" }}); ``` -------------------------------- ### Check Godot SDK Initialization (Godot 3.x) Source: https://docs.crazygames.com/sdk/intro Before calling any SDK functionality in Godot 3.x, ensure the SDK is initialized by awaiting `CrazyGames.is_initialised_async()`. ```gdscript yield(CrazyGames.is_initialised_async(), "completed") ``` -------------------------------- ### Leaderboard API Batch Success Response Source: https://docs.crazygames.com/sdk/leaderboard-api Example of a successful batch score submission where all scores were processed without errors. ```json { "success": true, "total": 3, "successCount": 3, "failureCount": 0, "errors": [] } ``` -------------------------------- ### Show Invite Button (C#) Source: https://docs.crazygames.com/sdk/game This C# snippet demonstrates how to show the invite button using a Dictionary for parameters. The returned link is similar to the one from the InviteLink method. Remember to hide the button when the room is no longer joinable. ```csharp var parameters = new Dictionary(); parameters.Add("roomName", "1234"); // the returned link looks the same as the link // returned by the InviteLink method var inviteLink = CrazySDK.Game.ShowInviteButton(parameters); ``` -------------------------------- ### Error Response Example: Empty Scores Array Source: https://docs.crazygames.com/sdk/leaderboard-api A 400 Bad Request response indicating that the 'scores' array cannot be empty. ```json {"error": "Scores must be a non-empty array"} ``` -------------------------------- ### Godot: Download and Mount External Resource Packs Source: https://docs.crazygames.com/resources/getting-to-the-first-frame In Godot, export content as .pck files, host them externally, and download them at runtime. This allows for modular loading of game content. The downloaded pack is then mounted using ProjectSettings. ```gdscript var http_request = HTTPRequest.new() add_child(http_request) http_request.connect("request_completed", self, "_on_pck_downloaded") http_request.request("https://mygame.com/level_2.pck") ``` ```gdscript ProjectSettings.load_resource_pack("user://level_2.pck") ``` -------------------------------- ### Get System Info - GameMaker Source: https://docs.crazygames.com/sdk/user Call the system info function in GameMaker. This function retrieves user environmental data. ```gml crazy_user_get_user_system_info() ``` -------------------------------- ### Track Gameplay Start/Stop (HTML5/Unity/GameMaker/Construct/Godot/Cocos) Source: https://docs.crazygames.com/sdk/game Call `gameplayStart` when the player begins or resumes playing. Call `gameplayStop` when the player enters a break state like a menu or ends a level. These are essential for resource management. ```javascript window.CrazyGames.SDK.game.gameplayStart(); window.CrazyGames.SDK.game.gameplayStop(); ``` ```csharp CrazySDK.Game.GameplayStart(); CrazySDK.Game.GameplayStop(); ``` ```c crazy_game_gameplay_start() crazy_game_gameplay_stop() ``` ```javascript window.ConstructCrazySDK.game.gameplayStart(); window.ConstructCrazySDK.game.gameplayStop(); ``` -------------------------------- ### Get Invite Parameter - JavaScript Source: https://docs.crazygames.com/sdk/game Retrieves a specific parameter passed through an invite link. Returns null if the parameter is not found. ```javascript // returns either a string or null if the parameter is missing window.CrazyGames.SDK.game.getInviteParam("roomName"); ``` -------------------------------- ### Error Response Example: Internal Server Error Source: https://docs.crazygames.com/sdk/leaderboard-api A 500 Internal Server Error response indicating an unexpected server error. ```json {"error": "Internal Server Error"} ``` -------------------------------- ### Handle Xsolla Events and Open Paystation Source: https://docs.crazygames.com/sdk/in-game-purchases This code demonstrates how to handle different Xsolla event statuses (DELIVERING, DONE, CLOSE, ERROR) and how to open the Xsolla paystation with a provided token and options. The callback function processes the event payload. ```javascript var cb = function(evt) { switch (evt.status) { case CRAZY_XSOLLA_EVENT_STATUS_DELIVERING: show_debug_message("IAP delivering: " + json_stringify(evt.payload)); break; case CRAZY_XSOLLA_EVENT_STATUS_DONE: show_debug_message("IAP done: " + json_stringify(evt.payload)); // Optionally track the order with CrazyGames analytics: // var orderData = { order_id: evt.payload?.order_id, status: "done" }; // crazy_analytics_track_order(json_stringify(orderData)); break; case CRAZY_XSOLLA_EVENT_CLOSE: show_debug_message("IAP close"); break; case CRAZY_XSOLLA_EVENT_ERROR: show_debug_message("IAP error: " + json_stringify(evt.payload)); break; } }; var options = { sandbox: true }; crazy_xsolla_open_paystation(global.xsolla_token, cb, json_stringify(options)); ``` -------------------------------- ### Show Account Link Prompt (C#) Source: https://docs.crazygames.com/sdk/user This C# implementation shows the account link prompt. It supports both callback-based and async/await patterns for handling the user's response. ```csharp CrazySDK.User.ShowAccountLinkPrompt((error, answer) => { if (error != null) { Debug.LogError("Show account link prompt error: " + error); return; } Debug.Log("Account link answer: " + answer); }); ``` ```csharp var answer = await CrazySDK.User.ShowAccountLinkPromptAsync(); ``` -------------------------------- ### Error Response Example: Scores Field Not an Array Source: https://docs.crazygames.com/sdk/leaderboard-api A 400 Bad Request response indicating that the 'scores' field must be an array. ```json {"error": "Scores must be an array"} ``` -------------------------------- ### Responsive Banner Error Example Source: https://docs.crazygames.com/sdk/banners This JSON object represents an error that can occur when requesting a banner, such as when a banner has been recently requested for the same container. ```json { "code": "bannerCooldown", "message": "A banner has already been requested for container banner-container-crazygames-inner less than 30 seconds ago, please wait.", "containerId": "banner-container-crazygames-inner" } ``` -------------------------------- ### Initialize SDK (JavaScript) Source: https://docs.crazygames.com/sdk/data Initialize the CrazyGames SDK before using any of its modules. This should be done during the game's loading screen as it preloads game data. ```javascript await window.CrazyGames.SDK.init(); ``` -------------------------------- ### Submit Score with Promise Source: https://docs.crazygames.com/other/game-challenge This example shows how to submit a score using the `addScore` method with async/await and a try-catch block for error handling. ```APIDOC ## Submit Score with Promise ### Description Submits a score using the `addScore` method, leveraging Promises for asynchronous operations and a try-catch block for error handling. ### Method `await window.CrazyGames.SDK.user.addScore(score, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **score** (number) - Required - The score to submit. Can be an integer or a decimal. An error will occur if the score is not a valid number. - **callback** (function) - Required - A function that will be called upon completion. It receives an error object if an error occurred. ### Request Example ```javascript try { await window.CrazyGames.SDK.user.addScore(100, callback); } catch (e) { console.log("Error:", e); } ``` ### Response #### Success Response None (The score is processed asynchronously). #### Response Example None ```