Как установить в код игры яндекс sdk

YaGames is the Yandex.Games extension for the Defold game engine. Yandex.Games is a collection of browser games for smartphones and computers. The games are available in Yandex Browser and the Yandex app. Games from the catalog are displayed in Yandex recommendation systems, which have a total audience of more than 50 million users per month.
You can check here the size of Yandex.Games audience. The platform is constantly growing.
You can use it in your own project by adding this project as a Defold library dependency. Open your game.project file and in the dependencies field add a link to the ZIP file of a specific release.
Note: Use version 0.2.0 for the old Defold 1.2.177 or lower.
- Tutorial: «Releasing HTML5 games on Yandex.Games» — How to add the Yandex.Games SDK to a Defold game and how to submit your game to the Yandex.Games catalog. . where you can talk with representatives from Yandex. Feel free to ask questions in English! for Russian-speaking users. about the YaGames extension.
Checklist For Releasing Game
-
.
- Translate your game to the Russian language. English and Turkish are optional (more info).
- Prepare assets for the catalogue:
- Icon 512 x 512 px.
- Cover 800 x 470 px.
- Screenshots.
- (Optional) Videos and GIF.
- Add the extension as a Defold library dependency to your project. You can publish your game on Yandex.Games from this moment. It fully meets the requirements.
- Enable monetization and earn revenue from placing ad blocks in your game. Ad blocks are available in the following formats:
- Interstitial blocks: ad blocks that completely cover the app background and show up at certain points (for example, when accessing the next game level). Important: Mute sounds before showing the ad.
- Rewarded videos: blocks with video ads that the user can choose to view and earn a reward or in-game currency. Important: Mute sounds before showing the ad.
- RTB ad blocks (banners): display both contextual (content-based) ads and media ads.
- In-game purchases: earn revenue by providing paid services to your users.
- (Optional) Enable Native Cache support.
- Set the path to the file yandex-manifest.json in the game.project settings.
- Copy the yagames/manifests/web/yandex-manifest.json file to the root directory of your release build.
- Edit the list of all game files inside your yandex-manifest.json , and update the path to the icon. Omit sw.js and yandex-manifest.json .
- Set the path to the file sw.js in the game.project settings.
- Copy the yagames/manifests/web/sw.js file to the root directory of your release build.
- Edit the list of all game files inside your sw.js . Omit sw.js and yandex-manifest.json .
- You should increment the version inside sw.js on every update of your game on Yandex.Games.
- The YaGames extension imitates a real API on non-HTML5 platforms. The idea is to allow to you quickly implement API on your favourite platform (macOS, Windows, Linux) and don’t spend time on slowly rebuilding/uploading the game to the Yandex.
- The code from yagames/manifests/web/engine_template.html is always added to your HTML5 template. This behaviour can’t be disabled. Tip: use Git-branching for every platform and do not mix platform-specific code between them.
Take a look at the demo project inside example directory. It has quite a few buttons to test all APIs. You can use it in your game as a debug screen or simply download/upload a pre-built .zip archive to make sure that you implemented SDK in the right way.

To get started, you need to initialize the SDK using the init method.
2. Interstitial Ad
Interstitial ads are ad blocks that completely cover the app background and show up before a user gets the data requested (for example, accessing the next game level).
Note: Yandex.Games recommends that developers call the display of full-screen ads in the game as often as possible but in suitable places in the game — so that the user understands that this is not a part of the game, but an ad unit. Do this in logical pauses in the game, for example: before starting the game, when moving to the next level, after losing.For example, inserting an ad unit is appropriate after going to the next level by pressing a button, and not appropriate in the middle of a level, when an ad suddenly appears under the playerʼs finger.
- open — Called when an ad is opened successfully.
- close — Called when an ad is closed, an error occurred, or on ad failed to open due to too frequent calls. Used with the was_shown argument (type boolean ), the value of which indicates whether an ad was shown.
- offline — Called when the network connection is lost (when offline mode is enabled).
- error — Called when an error occurrs. The error object is passed to the callback function.
The close callback is called in any situation, even if there was an error.
3. Rewarded Videos
Rewarded videos are video ad blocks used to monetize games and earn a reward or in-game currency.
- open — Called when a video ad is displayed on the screen.
- rewarded — Called when a video ad impression is counted. Use this function to specify a reward for viewing the video ad.
- close — Called when a user closes a video ad or an error happens.
- error — Called when an error occurrs. The error object is passed to the callback function.
The close callback is called in any situation, even if there was an error. The rewarded callback is called before close , and you should update your in-game UI only after close .
The game.project Settings
- sdk_init_options — JavaScript Object that is passed as-is into the Yandex Games SDK initialization options for the JS YaGames.init function. Example: > .
- sdk_init_snippet — JavaScript code that is passed as-is and called when the ysdk variable becomes available. Example: console.log(ysdk); . Use with care, and don’t forget to put a semicolon ; at the end.
- service_worker_url — Relative URL to the Service Worker file. Usually it’s sw.js . Set the URL to enable Service Worker.
- manifest_url — URL to the Web App Manifest file. Set the URL to enable support of Yandex Native Cache.
Yandex.Games JavaScript SDK uses ES6 Promise for asynchronous operations. For Lua API promises were replaced with callback functions with arguments (self, err, result) , where
- self userdata — Script self reference.
- err string — Error code if something went wrong.
- result — Data if the operation should return something.
The best way to integrate SDK into your game is to read the official documentation and to use corresponding Lua API functions. The table below helps to do that:
Yandex.Games JS SDK YaGames Lua API YaGames.init(options) yagames.init(callback)
The options is a JavaScript object , and it can be set in the yagames.sdk_init_options setting.Advertisement (docs) ysdk.adv.showFullscreenAdv( >) yagames.adv_show_fullscreen_adv(callbacks) Example ysdk.adv.showRewardedVideo( >) yagames.adv_show_rewarded_video(callbacks) Example Authentication + Player (docs) ysdk.auth.openAuthDialog() yagames.auth_open_auth_dialog(callback) ysdk.getPlayer(options) yagames.player_init(options, callback)
The argument options is a Lua table .player._personalInfo yagames.player_get_personal_info()
The result is table or nil if the _personalInfo object is not available.player.signature yagames.player_get_signature()
The result is string if player’s object is initialized with options.signed = true . Otherwise, nil .player.setData(data, flush) yagames.player_set_data(data, flush, callback) player.getData(keys) yagames.player_get_data(keys, callback) player.setStats(stats) yagames.player_set_stats(stats, callback) player.incrementStats(increments) yagames.player_increment_stats(increments, callback) player.getStats(keys) yagames.player_get_stats(keys, callback) player.getID() Deprecated yagames.player_get_id() Deprecated player.getUniqueID() yagames.player_get_unique_id() player.getIDsPerGame() yagames.player_get_ids_per_game(callback) player.getMode() yagames.player_get_mode()
(more info)player.getName() yagames.player_get_name() player.getPhoto(size) yagames.player_get_photo(size) In-Game Purchases (docs) ysdk.getPayments(options) yagames.payments_init(options, callback) payments.purchase(options) yagames.payments_purchase(options, callback) payments.getPurchases() yagames.payments_get_purchases(callback)
The result has the format , signature = «. » >payments.getCatalog() yagames.payments_get_catalog(callback) payments.consumePurchase(purchaseToken) yagames.payments_consume_purchase(purchase_token, callback) Leaderboards (docs) ysdk.getLeaderboards() yagames.leaderboards_init(callback) lb.getLeaderboardDescription(leaderboardName) yagames.leaderboards_get_description(leaderboard_name, callback) lb.getLeaderboardPlayerEntry(leaderboardName) yagames.leaderboards_get_player_entry(leaderboard_name, [options], callback)
If the player doesn’t have any score, you get the error FetchError: Player is not present in leaderboard .
The argument options is an optional Lua table , where size (string) can be small , medium , large .lb.getLeaderboardEntries(leaderboardName, options) yagames.leaderboards_get_entries(leaderboard_name, [options], callback)
The argument options is an optional Lua table , where size (string) can be small , medium , large .lb.setLeaderboardScore(leaderboardName, score, extraData) yagames.leaderboards_set_score(leaderboard_name, score, [extra_data], [callback]) Feedback (docs) ysdk.feedback.canReview() yagames.feedback_can_review(callback)
The result is a tableysdk.feedback.requestReview() yagames.feedback_request_review(callback)
The result is a tableClipboard (docs) ysdk.clipboard.writeText(text) yagames.clipboard_write_text(text, [callback]) Device Info (docs) ysdk.deviceInfo.type yagames.device_info_type()
Returns «desktop» , «mobile» , «tablet» or «tv»ysdk.deviceInfo.isDesktop() yagames.device_info_is_desktop() ysdk.deviceInfo.isMobile() yagames.device_info_is_mobile() ysdk.deviceInfo.isTablet() yagames.device_info_is_tablet() ysdk.deviceInfo.isTV() yagames.device_info_is_tv() Environment (docs) ysdk.environment yagames.environment()
Returns Lua table , . >Screen (docs) ysdk.screen.fullscreen.status yagames.screen_fullscreen_status()
Returns «on» or «off»ysdk.screen.fullscreen.request() yagames.screen_fullscreen_request([callback]) ysdk.screen.fullscreen.exit() yagames.screen_fullscreen_exit([callback]) Safe Storage (docs) Note: key and value should be valid UTF-8 strings. Storing strings with zero bytes aren’t supported. ysdk.getStorage() yagames.storage_init(callback) safeStorage.getItem(key) yagames.storage_get_item(key)
Returns that key’s value or nil .safeStorage.setItem(key, value) yagames.storage_set_item(key, value)
Adds that key to the storage, or update that key’s value if it already exists.safeStorage.removeItem(key) yagames.storage_remove_item(key)
Removes that key from the storage.safeStorage.clear() yagames.storage_clear()
Empties all keys out of the storage.safeStorage.key(n) yagames.storage_key(n)
Returns the name of the nth key in the storage or nil . Note: the n index is zero-based.safeStorage.length yagames.storage_length()
Returns the number of data items stored in the storage.Banner Ads (docs) yagames.banner_init(callback) yagames.banner_create(rtb_id, options, [callback]) yagames.banner_destroy(rtb_id) yagames.banner_refresh(rtb_id, [callback]) yagames.banner_set(rtb_id, property, value) Sitelock (docs) sitelock.add_domain(domain) sitelock.verify_domain() sitelock.get_current_domain() sitelock.is_release_build() You can additionally monetize your game using Yandex Advertising Network Real-Time Bidding ad blocks. RTB block is rendered into HTML div block and placed over your game canvas.
The official documentation:
Creating RTB blocks
Create an RTB block in the Yandex Advertising Network interface and copy RTB id of the block:

The ad block will be displayed within 30 minutes after saving the code and placing it on the game page.
Styling RTB blocks
Usually, developers put banners to the sides of a page. You can apply any CSS styles to the div block that will contain RTB ad via the yagames.banner_create ‘s options argument.
The following examples require to set width and height to 100% for the <body> . You should append these CSS styles to your Defold’s HTML template or CSS file:
Left vertical banner. Width is 350px:
Right vertical banner (screenshot). Width is 350px:
Horizontal banner at the top. Height is 250px:
Horizontal banner at the bottom (screenshot). Height is 250px:
Note: background: #d2d2d2; — it’s the background color for visual debugging. For production, you should remove it.
Banner Ads Lua API
Loads Yandex Advertising Network SDK and calls the callback.
- callback function — Function to call when the Yandex Advertising Network SDK has initialized.
The callback function is expected to accept the following values:
- self userdata — Script self reference.
- error string — Error code if something went wrong.
yagames.banner_create(rtb_id, options, [callback])
Creates a DOM element ( <div></div> ) with style=»position: absolute» , adds it to the end of the <body> (or to the end of the element specified by append_to_id ), applies your CSS styles on it and renders an advertisement into the element.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- options table — The table with key-value pairs.
- callback function — The callback function that is invoked after ad rendering.
The options table can have these key-value pairs:
- stat_id integer — The sample ID. A number between 1 and 1000000000. This will allow you to view group statistics for that block.
- css_styles string — Sets inline CSS styles of the <div></div> element.
- css_class string — Sets the value of the class attribute of the <div></div> element.
- display string — The display property allows to show or hide the element. If you set display = none , it hides the entire element. Use block to show it back.
- append_to_id string — The parent element ID if you want to add the div to the list of children of a specific parent node.
The callback function allows you to obtain information about whether the ad has been rendered (whether the ad was successfully selected when requested from the RTB system) and which particular ad was shown. The callback function is expected to accept the following values:
- self userdata — Script self reference.
- error string — Error code if something went wrong.
- data table — The function obtains the data.product parameter with one of two values: direct — Yandex.Direct ads were shown in an RTB ad block, rtb — A media ad was shown in an RTB ad block.
If there were no suitable product listings at the auction to show your ad next to, then you can show your ad in the block. In this situation the callback function returns the error No ads available. .
Removes the DOM element.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
Requests SDK to render new advertisement.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- callback function — The callback function that is invoked after ad rendering.
The callback function is described in the yagames.banner_create section above.
yagames.banner_set(rtb_id, property, value)
Sets a named property of the specified banner.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- property string — Name of the property to set.
- value string — The value to set.
- stat_id integer — The sample ID. A number between 1 and 1000000000. This will allow you to view group statistics for that block.
- css_styles string — Sets inline CSS styles of the <div></div> element.
- css_class string — Sets the value of the class attribute of the <div></div> element.
- display string — The display property allows to show or hide the element. If you set display = none , it hides the entire element. Use block to show it back.
It’s a good idea to protect your HTML5 game from simple copy-pasting to another website. YaGames has Sitelock API for that purpose. It’s simple, but it’s better than nothing.
By default, it checks hostnames yandex.net (CDN of the Yandex.Games) and localhost (for local debugging).
Artsiom Trubchyk (@aglitchman) is the current YaGames owner within Indiesoft and is responsible for the open source repository.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md

YaGames — Yandex.Games for Defold
Note
This is an open-source project, and it’s not affiliated with Yandex LLC.
If you are looking for Yandex Mobile Ads SDK for mobile apps, then this extension isn’t for you.
YaGames is the Yandex.Games SDK native extension for the Defold game engine.
Yandex.Games is a collection of browser HTML5 games for smartphones, computers, tablets, and TVs. The games are available in Yandex Browser and the Yandex app. Games from the catalog are displayed in Yandex recommendation systems, which have a total audience of more than 50 million users per month.
You can check here the size of Yandex.Games audience. The platform is constantly growing.
You can use it in your own project by adding this project as a Defold library dependency. Open your game.project file and in the dependencies field add a link to the ZIP file of a specific release.
Note: Use version 0.8.1 for Defold <=1.3.7.
- Tutorial: «Releasing HTML5 games on Yandex.Games» — How to add the Yandex.Games SDK to a Defold game and how to submit your game to the Yandex.Games catalog. . where you can talk with representatives from Yandex. Feel free to ask questions in English! for Russian-speaking users. about the YaGames extension.
Checklist For Releasing Game
-
.
- Translate your game to the Russian language (tip: It’s a great idea to translate your game title into Russian too.). English and Turkish are optional (more info).
- Prepare assets for the catalogue:
- Icon 512 x 512 px.
- Cover 800 x 470 px.
- Screenshots.
- (Optional) Videos and GIF.
- Add the extension as a Defold library dependency to your project.
- Enable monetization and earn revenue from placing ad blocks in your game. Ad blocks are available in the following formats:
- Interstitial blocks: ad blocks that completely cover the app background and show up at certain points (for example, when accessing the next game level). Important: Mute sounds before showing the ad.
- Rewarded videos: blocks with video ads that the user can choose to view and earn a reward or in-game currency. Important: Mute sounds before showing the ad.
- RTB ad blocks (banners): display both contextual (content-based) ads and media ads.
- Sticky banners: the same as RTB but they’re much easier to setup.
- In-game purchases: earn revenue by providing paid services to your users.
- You can publish your game on Yandex.Games from this moment. It fully meets the requirements.
Best Practices & Tips
- The YaGames extension imitates a real API on non-HTML5 platforms. The idea is to allow to you quickly implement API on your favourite platform (macOS, Windows, Linux) and don’t spend time on slowly rebuilding/uploading the game to the Yandex.
- The code from yagames/manifests/web/engine_template.html is always added to your HTML5 template. This behaviour can’t be disabled. Tip: use Git-branching for every platform and do not mix platform-specific code between them.
- You don’t need to set up any cache-busting techniques, since Yandex.Games hosts each version of your game in separate paths.
Take a look at the demo project inside example directory. It has quite a few buttons to test all APIs. You can use it in your game as a debug screen or simply download/upload a pre-built .zip archive to make sure that you implemented SDK in the right way.

To get started, you need to initialize the SDK using the init method.
2. Interstitial Ad
Interstitial ads are ad blocks that completely cover the app background and show up before a user gets the data requested (for example, accessing the next game level).
Note: Yandex.Games recommends that developers call the display of full-screen ads in the game as often as possible but in suitable places in the game — so that the user understands that this is not a part of the game, but an ad unit. Do this in logical pauses in the game, for example: before starting the game, when moving to the next level, after losing.For example, inserting an ad unit is appropriate after going to the next level by pressing a button, and not appropriate in the middle of a level, when an ad suddenly appears under the playerʼs finger.
- open — Called when an ad is opened successfully.
- close — Called when an ad is closed, an error occurred, or on ad failed to open due to too frequent calls. Used with the was_shown argument (type boolean ), the value of which indicates whether an ad was shown.
- offline — Called when the network connection is lost (when offline mode is enabled).
- error — Called when an error occurrs. The error object is passed to the callback function.
The close callback is called in any situation, even if there was an error.
3. Rewarded Videos
Rewarded videos are video ad blocks used to monetize games and earn a reward or in-game currency.
- open — Called when a video ad is displayed on the screen.
- rewarded — Called when a video ad impression is counted. Use this function to specify a reward for viewing the video ad.
- close — Called when a user closes a video ad or an error happens.
- error — Called when an error occurrs. The error object is passed to the callback function.
The close callback is called in any situation, even if there was an error. The rewarded callback is called before close , and you should update your in-game UI only after close .
Native Cache How-To
Yandex’s Native Cache lets users use games offline. Currently, it’s available only in Yandex Browser or the Yandex app on smartphones.
- Set the path to the file yandex-manifest.json in the game.project settings.
- Copy the yagames/manifests/web/yandex-manifest.json file to the root directory of your release build.
- Edit the list of all game files inside your yandex-manifest.json , and update the path to the icon. Omit sw.js and yandex-manifest.json .
Service Worker How-To
Yandex allows to integrate Service Worker into your game to be able to run both offline and online.
- Set the path to the file sw.js in the game.project settings.
- Copy the yagames/manifests/web/sw.js file to the root directory of your release build.
- Edit the list of all game files inside your sw.js . Omit sw.js and yandex-manifest.json .
- You should increment the version inside sw.js on every update of your game on Yandex.Games.
The game.project Settings (Optional!)
- sdk_init_options — JavaScript Object that is passed as-is into the Yandex Games SDK initialization options for the JS YaGames.init function. Example: < orientation: < value: "landscape", lock: true >> .
- sdk_init_snippet — JavaScript code that is passed as-is and called when the ysdk variable becomes available. Example: console.log(ysdk); . Use with care, and don’t forget to put a semicolon ; at the end.
- service_worker_url — Relative URL to the Service Worker file. Usually it’s sw.js . Set the URL to enable Service Worker.
- manifest_url — URL to the Web App Manifest file. Set the URL to enable support of Yandex Native Cache.
Yandex.Games JavaScript SDK uses ES6 Promise for asynchronous operations. For Lua API promises were replaced with callback functions with arguments (self, err, result) , where
- self userdata — Script self reference.
- err string — Error code if something went wrong.
- result — Data if the operation should return something.
The best way to integrate SDK into your game is to read the official documentation and to use corresponding Lua API functions. The table below helps to do that:
| Yandex.Games JS SDK | YaGames Lua API |
|---|---|
| YaGames.init(options) | yagames.init(callback) The options is a JavaScript object <> , and it can be set in the yagames.sdk_init_options setting. |
| Advertisement (docs) | |
| ysdk.adv.showFullscreenAdv( |
yagames.adv_show_fullscreen_adv(callbacks) Example |
| ysdk.adv.showRewardedVideo( |
yagames.adv_show_rewarded_video(callbacks) Example |
| Advertisement — Sticky Banners | |
| ysdk.adv.getBannerAdvStatus() | yagames.adv_get_banner_adv_status(callback) |
| ysdk.adv.showBannerAdv() | yagames.adv_show_banner_adv([callback]) |
| ysdk.adv.hideBannerAdv() | yagames.adv_hide_banner_adv([callback]) |
| Authentication + Player (docs) | |
| ysdk.auth.openAuthDialog() | yagames.auth_open_auth_dialog(callback) |
| ysdk.getPlayer(options) | yagames.player_init(options, callback) The argument options is a Lua table < signed = boolean, scopes = boolean >. |
| player._personalInfo | yagames.player_get_personal_info() The result is table or nil if the _personalInfo object is not available. |
| player.signature | yagames.player_get_signature() The result is string if player’s object is initialized with options.signed = true . Otherwise, nil . |
| player.setData(data, flush) | yagames.player_set_data(data, flush, callback) |
| player.getData(keys) | yagames.player_get_data(keys, callback) |
| player.setStats(stats) | yagames.player_set_stats(stats, callback) |
| player.incrementStats(increments) | yagames.player_increment_stats(increments, callback) |
| player.getStats(keys) | yagames.player_get_stats(keys, callback) |
| player.getID() Deprecated | yagames.player_get_id() Deprecated |
| player.getUniqueID() | yagames.player_get_unique_id() |
| player.getIDsPerGame() | yagames.player_get_ids_per_game(callback) |
| player.getMode() | yagames.player_get_mode() (more info) |
| player.getName() | yagames.player_get_name() |
| player.getPhoto(size) | yagames.player_get_photo(size) |
| In-Game Purchases (docs) | |
| ysdk.getPayments(options) | yagames.payments_init(options, callback) |
| payments.purchase(options) | yagames.payments_purchase(options, callback) |
| payments.getPurchases() | yagames.payments_get_purchases(callback) The result has the format < purchases = < . >, signature = «. » > |
| payments.getCatalog() | yagames.payments_get_catalog(callback) |
| payments.consumePurchase(purchaseToken) | yagames.payments_consume_purchase(purchase_token, callback) |
| Leaderboards (docs) | |
| ysdk.getLeaderboards() | yagames.leaderboards_init(callback) |
| lb.getLeaderboardDescription(leaderboardName) | yagames.leaderboards_get_description(leaderboard_name, callback) |
| lb.getLeaderboardPlayerEntry(leaderboardName) | yagames.leaderboards_get_player_entry(leaderboard_name, [options], callback) If the player doesn’t have any score, you get the error FetchError: Player is not present in leaderboard . The argument options is an optional Lua table < getAvatarSrc = "size", getAvatarSrcSet = "size" >, where size (string) can be small , medium , large . |
| lb.getLeaderboardEntries(leaderboardName, options) | yagames.leaderboards_get_entries(leaderboard_name, [options], callback) The argument options is an optional Lua table < includeUser = boolean, quantityAround = number, quantityTop = number, getAvatarSrc = "size", getAvatarSrcSet = "size" >, where size (string) can be small , medium , large . |
| lb.setLeaderboardScore(leaderboardName, score, extraData) | yagames.leaderboards_set_score(leaderboard_name, score, [extra_data], [callback]) |
| Feedback (docs) | |
| ysdk.feedback.canReview() | yagames.feedback_can_review(callback) The result is a table < value = true/false, reason = "string" > |
| ysdk.feedback.requestReview() | yagames.feedback_request_review(callback) The result is a table < feedbackSent = true/false > |
| Clipboard (docs) | |
| ysdk.clipboard.writeText(text) | yagames.clipboard_write_text(text, [callback]) |
| Device Info (docs) | |
| ysdk.deviceInfo.type | yagames.device_info_type() Returns «desktop» , «mobile» , «tablet» or «tv» |
| ysdk.deviceInfo.isDesktop() | yagames.device_info_is_desktop() |
| ysdk.deviceInfo.isMobile() | yagames.device_info_is_mobile() |
| ysdk.deviceInfo.isTablet() | yagames.device_info_is_tablet() |
| ysdk.deviceInfo.isTV() | yagames.device_info_is_tv() |
| Environment (docs) | |
| ysdk.environment | yagames.environment() Returns Lua table < app = < >, . > |
| Screen (docs) | |
| ysdk.screen.fullscreen.status | yagames.screen_fullscreen_status() Returns «on» or «off» |
| ysdk.screen.fullscreen.request() | yagames.screen_fullscreen_request([callback]) |
| ysdk.screen.fullscreen.exit() | yagames.screen_fullscreen_exit([callback]) |
| Safe Storage (docs) | Note: key and value should be valid UTF-8 strings. Storing strings with zero bytes aren’t supported. |
| ysdk.getStorage() | yagames.storage_init(callback) |
| safeStorage.getItem(key) | yagames.storage_get_item(key) Returns that key’s value or nil . |
| safeStorage.setItem(key, value) | yagames.storage_set_item(key, value) Adds that key to the storage, or update that key’s value if it already exists. |
| safeStorage.removeItem(key) | yagames.storage_remove_item(key) Removes that key from the storage. |
| safeStorage.clear() | yagames.storage_clear() Empties all keys out of the storage. |
| safeStorage.key(n) | yagames.storage_key(n) Returns the name of the nth key in the storage or nil . Note: the n index is zero-based. |
| safeStorage.length | yagames.storage_length() Returns the number of data items stored in the storage. |
| Events (docs) | |
| ysdk.onEvent(eventName, listener) | yagames.event_on(event_name, listener) |
| ysdk.dispatchEvent(eventName) | yagames.event_dispatch(event_name) |
| Banner Ads (docs) | |
| yagames.banner_init(callback) | |
| yagames.banner_create(rtb_id, options, [callback]) | |
| yagames.banner_destroy(rtb_id) | |
| yagames.banner_refresh(rtb_id, [callback]) | |
| yagames.banner_set(rtb_id, property, value) | |
| Sitelock (docs) | |
| sitelock.add_domain(domain) | |
| sitelock.verify_domain() | |
| sitelock.get_current_domain() | |
| sitelock.is_release_build() |
You can additionally monetize your game using Yandex Advertising Network Real-Time Bidding ad blocks. RTB block is rendered into HTML div block and placed over your game canvas.
The official documentation:
Creating RTB blocks
Create an RTB block in the Yandex Advertising Network interface and copy RTB id of the block:

The ad block will be displayed within 30 minutes after saving the code and placing it on the game page.
Styling RTB blocks
Usually, developers put banners to the sides of a page. You can apply any CSS styles to the div block that will contain RTB ad via the yagames.banner_create ‘s options argument.
The following examples require to set width and height to 100% for the <body> . You should append these CSS styles to your Defold’s HTML template or CSS file:
Left vertical banner. Width is 350px:
Right vertical banner (screenshot). Width is 350px:
Horizontal banner at the top. Height is 250px:
Horizontal banner at the bottom (screenshot). Height is 250px:
Note: background: #d2d2d2; — it’s the background color for visual debugging. For production, you should remove it.
Banner Ads Lua API
Loads Yandex Advertising Network SDK and calls the callback.
- callback function — Function to call when the Yandex Advertising Network SDK has initialized.
The callback function is expected to accept the following values:
- self userdata — Script self reference.
- error string — Error code if something went wrong.
yagames.banner_create(rtb_id, options, [callback])
Creates a DOM element ( <div></div> ) with style=»position: absolute» , adds it to the end of the <body> (or to the end of the element specified by append_to_id ), applies your CSS styles on it and renders an advertisement into the element.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- options table — The table with key-value pairs.
- callback function — The callback function that is invoked after ad rendering.
The options table can have these key-value pairs:
- stat_id integer — The sample ID. A number between 1 and 1000000000. This will allow you to view group statistics for that block.
- css_styles string — Sets inline CSS styles of the <div></div> element.
- css_class string — Sets the value of the class attribute of the <div></div> element.
- display string — The display property allows to show or hide the element. If you set display = none , it hides the entire element. Use block to show it back.
- append_to_id string — The parent element ID if you want to add the div to the list of children of a specific parent node.
The callback function allows you to obtain information about whether the ad has been rendered (whether the ad was successfully selected when requested from the RTB system) and which particular ad was shown. The callback function is expected to accept the following values:
- self userdata — Script self reference.
- error string — Error code if something went wrong.
- data table — The function obtains the data.product parameter with one of two values: direct — Yandex.Direct ads were shown in an RTB ad block, rtb — A media ad was shown in an RTB ad block.
If there were no suitable product listings at the auction to show your ad next to, then you can show your ad in the block. In this situation the callback function returns the error No ads available. .
Removes the DOM element.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
Requests SDK to render new advertisement.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- callback function — The callback function that is invoked after ad rendering.
The callback function is described in the yagames.banner_create section above.
yagames.banner_set(rtb_id, property, value)
Sets a named property of the specified banner.
- rtb_id string — The unique RTB block ID. The block ID consists of a product ID ( R-A ), platform ID and the block’s serial number.
- property string — Name of the property to set.
- value string — The value to set.
- stat_id integer — The sample ID. A number between 1 and 1000000000. This will allow you to view group statistics for that block.
- css_styles string — Sets inline CSS styles of the <div></div> element.
- css_class string — Sets the value of the class attribute of the <div></div> element.
- display string — The display property allows to show or hide the element. If you set display = none , it hides the entire element. Use block to show it back.
It’s a good idea to protect your HTML5 game from simple copy-pasting to another website. YaGames has Sitelock API for that purpose. It’s simple, but it’s better than nothing.
By default, it checks hostnames yandex.net (CDN of the Yandex.Games) and localhost (for local debugging).
Artsiom Trubchyk (@aglitchman) is the current YaGames owner within Indiesoft and is responsible for the open source repository.
Unity WebGL + Яндекс.Игры
Этот пакет оболочки для платформы Яндекс.Игры, поможет быстро сделать связку между самой игрой и SDK Яндекса. В наборе присутствует набор скриптов со всеми базовыми функциями, плагин для коммуникации между игрой и сдк. Дополнительно, также мы добавили свой шаблон для сборки игры, где уже вшиты необходимые JS функции. Разработчику остается только сделать нужные настройки в консоли яндекса, а всё остальное можно делать через скрипт-менеджера.
Итак, набор нашей оболочки SDK для платформы https://games.yandex.ru/
Для начала вам нужно пройти регистрацию в рекламной сети Яндекса РСЯ https://partner.yandex.ru/ заполнить все документы и заключить договор, когда всё будет оформлено, можно переходить в Яндекс.Игры и добавлять свои игры.
Чтобы открыть все разделы для игры, вам в начале нужно заполнить черновик, загрузить туда билд игры и сохранить черновик и после проверки, через некоторое время, когда появится ссылка на черновик билда, после этого можно переходить к настройкам других разделов.
Далее, можно настроить покупки, добавить товары и потом вам будет доступен секретный ключ:
Секретный ключ, понадобится добавить в настройки нашей оболочки или для создания другого способ проверки подлинности покупок.
В разделе рекламы нужно подключить реворд ролики:
И дополнительно добавить таблицу лидеров:
Тип таблицы в настройках, ставим — numeric.
В настройках проекта, вам нужно выбрать наш шаблон сборки:
В этом шаблоне есть все необходимые JS функции для коммуникации с Яндексом.
Наша оболочка + плагин, поддерживает следующие функции:
- Диалоговое окно аутентификации пользователя (опционально).
- Полноэкранные объявления.
- Реклама с вознаграждением.
- Sticky баннеры.
- Оценка игры.
- Запись / получение данных лидерборда.
- Запись / получение данных игрока.
- Внутриигровые покупки.
- Встроена своя система сохранения, аналог PlayerPrefs.
Примечание насчет аутентификации: наш плагин сделан так, что система идентифицирует пользователя в фоновом режиме, а если пользователь зашел с другого устройства и/или не находится в системе Яндекса, то будет работать реклама как обычно, но для работы всех остальных функций, нужно запросить аутентификацию, вызвав диалоговое окно Яндекса. Наш менеджер позволяет всё это делать и определять статус пользователя.
Минимальная поддерживаемая версия Unity для нашего плагина: 2020.2 and higher
Мой опыт заработка на Яндекс.Играх — разработка, размещение, статистика и результаты
В данной статья хочу рассказать о своем опыте заработка на игровом сервисе Яндекс.Игры. Впервые с сервисом я познакомился через YouTube канал «BL’Games». Там автор рассказывал, как он с помощью Яндекс.Игр имеет стабильный доход, который дает ему заниматься любимым делом.
Я тоже давно мечтал делать мобильные игры, но для серьёзных проектов у меня не хватало времени. Поэтому я решил тоже попробовать залить свои простенькие игры на сервис.
И вот что получилось.
Что такое Яндекс.Игры
Яндекс.Игры — это каталог браузерных игр, на которых можно играть на компьютере и на телефоне. Главное отличие от других игровых сервисов в том, что Яндекс сам льет трафик в игры через другие свои сервисы.
Согласно сервису Яндекс.Радар, месячная посещаемость Яндекс Игр составляет 8 639 365 человек. Ежедневная аудитория — 1 138 728 человек. Каждый месяц в поиске Яндекса Яндекс.Игры ищут около 2 млн раз.
Выбор жанра
Первым делом нужно было выбрать жанр игры. Изучив каталог Яндекс Игр, я решил, что самым простым будет создание квиза. Квиз — это тест-викторина, где нужно отвечать на разные вопросы.
Темой вопросов выбрал фильмы. Игроку должно было по очереди показываться сцены из фильмов и сериалов и он должен был выбрать из 4 названий правильный. По такой схеме создавались очень много игр для этого сервиса и было видно, что аудитории такой формат нравится. Хотя квизы трудно назвать полноценной игрой. Это скорее тестирование на знание некоторых фактов и проверка на память.
Выбор движка для игры
Сразу решил, что буду использовать движок, а не конструктор. Во-первых, игровые движки дают возможность более гибко реализовывать задумку.Во-вторых, хотелось сразу изучить язык программирования для последующих проектов.
Сначала начинал разработку на Unity3d, но из-за проблем с ноутбуком пришлось искать менее требовательную программу. И так я познакомился с игровым движком Godot.
Godot Engine — открытый кроссплатформенный 2D и 3D игровой движок под лицензией MIT, который разрабатывается сообществом Godot Engine Community. Разрабатывать игры можно через Linux, Windows, MacOS и даже браузер.
Разработка
Сам процесс разработки не буду рассказывать, это будет темой другой статьи. Сначала изучил официальную документацию движка на https://docs.godotengine.org/ru/stable/community/contributing/index.html . Просмотрел пару роликов на YouTube. После этого приступил к разработке. По сути, для простого квиза нет никаких сложностей. Нужно показывать сцены из фильмов и 4 кнопки с возможными вариантами ответа. После нажатия на кнопку, определяется правильность и выводится результат. Далее происходит переход на новый вопрос. Вопросы разбиты по уровням сложности.
Регистрация в консоли разработчика Яндекс.Игр
С регистрацией в консоли разработчика Яндекс.Игр проблем не возникло. Для этого нужно перейти на страницу https://yandex.ru/dev/games/ и нажать «Консоль разработчика Яндекс.Игр». 
Нужно придумать имя аккаунта разработчика. Она будет видна на странице ваших игр.
Чтобы создать новую игру, нажимаем «Добавить приложение», соглашаемся с лицензионным соглашением и нажимаем «Добавить».
Подробнее о заполнении карточки вашей игры можно прочитать в официальной документации.


Добавление рекламы и публикация
Чтобы пройти модерацию игры и начать зарабатывать, нужно подключить SDK Яндекс Игр.
SDK Яндекс Игр — это библиотека, позволяющая быстро интегрировать игры, созданные сторонними разработчиками, в платформу Яндекс Игр.
Без подключенного SDK ваша игра не сможет разместиться в каталоге Яндекс Игр. Подробное руководство по настройке и подключения SDK описана в документации.
Пример добавления SDK в игру:
Также нужно подключить монетизацию в рекламной сети яндекса (РСЯ). Для этого нужно нажать «Подключить монетизацию», заполнить достоверную информацию о вас и нажать «Зарегистрироваться». После регистрации потребуется указать ваш счет в банке, для получения оплаты. Рекомендую это сделать сразу после регистрации в консоли разработчика.

Когда на 100% уверены, что игра готова и выполнены все требования к игре, можно отправлять на модерацию.

Статистика
За первую неделю (с 12.03.2021 по 19.03.2021) игра принесла 924,13 ₽.
За месяц (с 12.03.2021 по 12.04.2021) 1 528,00 ₽.

За все время (с 12.03.2021 по 22.08.2022) игра заработала 3 315,99 ₽.

Для простого квиза сделанного за 2 вечера это не очень много. Но у учел свои ошибки и решил создать еще один квиз. В этот раз создавать все с 0 не пришлось. Поэтому все сделал за 1 вечер.
В этот раз игра уже показала более высокие результаты и за все время принесла 7 310 рублей.
Всего за 3 месяца я разместил 9 игр. Среди них были нормальные игры на которые у меня ушли гораздо больше времени. Но наибольшую прибыль принесли квизы. Скорее всего, это связано с аудиторией сервиса. Детские игры меньше монетизируются, а в квизы играют (или проходят) в основном взрослая аудитория.
Всего за все время я заработал 39 144 рублей. Из этой суммы заплатил 13% налога — 5 088 рублей. Последнюю игру я разместил в мае 2021 года. Но прибыль я полуя до сих пор. Каждый второй месяц набирается минимальная сумма для вывода(3 000 рублей).
Я согласен, что качество этих игр(и квизов) не очень хорошее. Но в процессе разработки я научился создавать браузерные и мобильные игры на Godot. И использовал эти навыки для других своих проектов.
Если вы начинающий разработчик инди игр, то Яндекс Игры это отличная платформа для монетизации ваших игр и получения обратной связи. А также вы можете увеличить монетизацию, разместив ваши игры на другой платформе — Игры Вконтакте.