game-sdk.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * Game Platform SDK
  3. *
  4. * When running inside the platform, window.GameSDK is injected automatically
  5. * before your bundle loads. Use it directly:
  6. *
  7. * const result = await GameSDK.submit(score)
  8. * // result: { ok: true, rank: 3 } or { ok: false, error: '...' }
  9. *
  10. * const name = GameSDK.getPlayerName() // the current player's display name
  11. * const id = GameSDK.gameId // this game's id string
  12. *
  13. * For local development (outside the platform), load this file as a script
  14. * tag before your bundle and call GameSDK.init(gameId, apiBase):
  15. *
  16. * <script src="game-sdk.js"></script>
  17. * <script>GameSDK.init('my-game', 'http://localhost:4006')</script>
  18. * <script src="my-game.bundle.js"></script>
  19. */
  20. ;(function () {
  21. if (window.GameSDK && window.GameSDK._platform) return // already injected by platform
  22. const NAME_KEY = 'gameName'
  23. window.GameSDK = {
  24. gameId: null,
  25. _apiBase: '',
  26. init: function (gameId, apiBase) {
  27. this.gameId = gameId
  28. this._apiBase = apiBase || ''
  29. },
  30. getPlayerName: function () {
  31. return localStorage.getItem(NAME_KEY) || 'anonymous'
  32. },
  33. submit: async function (score) {
  34. if (!this.gameId) return { ok: false, error: 'GameSDK not initialised — call GameSDK.init(gameId)' }
  35. const name = this.getPlayerName()
  36. try {
  37. const r = await fetch(`${this._apiBase}/api/games/${this.gameId}/scores`, {
  38. method: 'POST',
  39. headers: { 'Content-Type': 'application/json' },
  40. body: JSON.stringify({ name, score }),
  41. })
  42. return await r.json()
  43. } catch {
  44. return { ok: false, error: 'Network error' }
  45. }
  46. },
  47. }
  48. })()