|
@@ -1,54 +1,9 @@
|
|
|
/**
|
|
/**
|
|
|
* Game Platform SDK
|
|
* Game Platform SDK
|
|
|
*
|
|
*
|
|
|
- * When running inside the platform, window.GameSDK is injected automatically
|
|
|
|
|
- * before your bundle loads. Use it directly:
|
|
|
|
|
|
|
+ * window.GameSDK is injected by the platform before your bundle loads.
|
|
|
*
|
|
*
|
|
|
- * const result = await GameSDK.submit(score)
|
|
|
|
|
- * // result: { ok: true, rank: 3 } or { ok: false, error: '...' }
|
|
|
|
|
- *
|
|
|
|
|
- * const name = GameSDK.getPlayerName() // the current player's display name
|
|
|
|
|
- * const id = GameSDK.gameId // this game's id string
|
|
|
|
|
- *
|
|
|
|
|
- * For local development (outside the platform), load this file as a script
|
|
|
|
|
- * tag before your bundle and call GameSDK.init(gameId, apiBase):
|
|
|
|
|
- *
|
|
|
|
|
- * <script src="game-sdk.js"></script>
|
|
|
|
|
- * <script>GameSDK.init('my-game', 'http://localhost:4006')</script>
|
|
|
|
|
- * <script src="my-game.bundle.js"></script>
|
|
|
|
|
|
|
+ * GameSDK.gameId — string, this game's id
|
|
|
|
|
+ * GameSDK.getPlayerName() — string, current player's display name
|
|
|
|
|
+ * GameSDK.submit(score) — Promise<{ ok: true, rank: number } | { ok: false, error: string }>
|
|
|
*/
|
|
*/
|
|
|
-
|
|
|
|
|
-;(function () {
|
|
|
|
|
- if (window.GameSDK && window.GameSDK._platform) return // already injected by platform
|
|
|
|
|
-
|
|
|
|
|
- const NAME_KEY = 'gameName'
|
|
|
|
|
-
|
|
|
|
|
- window.GameSDK = {
|
|
|
|
|
- gameId: null,
|
|
|
|
|
- _apiBase: '',
|
|
|
|
|
-
|
|
|
|
|
- init: function (gameId, apiBase) {
|
|
|
|
|
- this.gameId = gameId
|
|
|
|
|
- this._apiBase = apiBase || ''
|
|
|
|
|
- },
|
|
|
|
|
-
|
|
|
|
|
- getPlayerName: function () {
|
|
|
|
|
- return localStorage.getItem(NAME_KEY) || 'anonymous'
|
|
|
|
|
- },
|
|
|
|
|
-
|
|
|
|
|
- submit: async function (score) {
|
|
|
|
|
- if (!this.gameId) return { ok: false, error: 'GameSDK not initialised — call GameSDK.init(gameId)' }
|
|
|
|
|
- const name = this.getPlayerName()
|
|
|
|
|
- try {
|
|
|
|
|
- const r = await fetch(`${this._apiBase}/api/games/${this.gameId}/scores`, {
|
|
|
|
|
- method: 'POST',
|
|
|
|
|
- headers: { 'Content-Type': 'application/json' },
|
|
|
|
|
- body: JSON.stringify({ name, score }),
|
|
|
|
|
- })
|
|
|
|
|
- return await r.json()
|
|
|
|
|
- } catch {
|
|
|
|
|
- return { ok: false, error: 'Network error' }
|
|
|
|
|
- }
|
|
|
|
|
- },
|
|
|
|
|
- }
|
|
|
|
|
-})()
|
|
|