package leaderboard
import "github.com/nsgo-dev/game/pkg/online/leaderboard"Overview
Package leaderboard submits scores to and shows the platform's leaderboards: Game Center on Apple platforms and Play Games Services on Android through NSGo's gameservices package, and friend rankings on WeChat and Douyin mini games through host user cloud storage and the open data context.
A game declares its boards once in a versioned YAML Catalog that maps each board's name in the game to its entry in every platform service, and its code then names boards rather than platform IDs:
version: 1
leaderboards:
- name: high-score
gameCenter: com.example.game.high_score
playGames: CgkIxxxxxxxxxxEAIQAQ
miniGame:
key: best
order: desc
catalog, err := leaderboard.Parse(data)
boards, err := leaderboard.New(cx, catalog)
boards.SignIn(nil)
boards.Submit("high-score", score, func(err error) { ... })
boards.Show("high-score")
Calls complete through callbacks on the engine goroutine. On platforms without a game service (Windows, Linux, the web, watchOS, or simulated OS builds such as --nsgo-os ios without a mini-game host) they report ErrUnsupported, and Available and Supports let a view hide its leaderboard button there. A misspelt board name reports ErrUnknownLeaderboard on every platform.
On WeChat and Douyin mini games (ProviderMiniGame), Submit writes to the host's user cloud storage only when the score improves on the player's previous best for the board's Order, Show and ShowIn present the open data context friend ranking over the game view, Hide removes it, and Scores (including Friends) reports ErrUnsupported because friend data stays inside the isolated open data context.
Tests run against nsgotest's per-app fake game service (start with nsgotest.Environment(core.Environment{CanUseGameServices: true, OS: core.OSIOS}), sign in with App.SetGameServicesPlayer, and read App.GameServicesSubmittedScores and App.GameServicesShownLeaderboards) or against a MiniGameHost supplied via WithMiniGameHost.
Index
- Constants
- Variables
- func DecodeMiniGameScore(value string) (score, updateTime int64, err error)
- func EncodeMiniGameScore(key string, score, updateTime int64) (string, error)
- type Board
- type Catalog
- type Entry
- type MiniGameBoard
- type MiniGameEntry
- type MiniGameHost
- type MiniGameRanking
- type Option
- type Order
- type Player
- type PlayerScope
- type Provider
- type Query
- type Service
- func New(cx *core.Scope, c *Catalog, opts ...Option) (*Service, error)
- func (s *Service) Available() bool
- func (s *Service) Catalog() *Catalog
- func (s *Service) Hide() error
- func (s *Service) ID(name string) (string, error)
- func (s *Service) Player() Player
- func (s *Service) Provider() Provider
- func (s *Service) Scores(name string, q Query, done func([]Entry, error))
- func (s *Service) Show(name string) error
- func (s *Service) ShowIn(name string, bounds core.Bounds) error
- func (s *Service) SignIn(done func(Player, error))
- func (s *Service) SignedIn() bool
- func (s *Service) Submit(name string, score int64, done func(error))
- func (s *Service) Supports(name string) bool
- type TimeScope
Constants
const (
Global = gameservices.Global
Friends = gameservices.Friends
)Player scopes for Query.Players.
const (
AllTime = gameservices.AllTime
Week = gameservices.Week
Today = gameservices.Today
)Time scopes for Query.Time.
const CurrentVersion = 1CurrentVersion is the leaderboard catalog schema version this package reads and writes.
const MaxIDLength = 100MaxIDLength is the longest platform leaderboard ID a catalog accepts, matching Game Center's limit of 100 characters.
const MaxMiniGameKeyLength = 128MaxMiniGameKeyLength is the longest mini-game cloud storage key in bytes, matching WeChat's 128-byte key limit.
const MaxMiniGameKeys = 128MaxMiniGameKeys is the most mini-game cloud storage keys a catalog may declare, matching WeChat's limit of 128 KV pairs per player.
const MaxMiniGameValueBytes = 1024MaxMiniGameValueBytes is the maximum byte length of one serialized key-value pair (len(key) + len(value)) in mini-game user cloud storage (1 KiB).
Variables
var (
// ErrUnknownLeaderboard means the name is not declared in the catalog. It is reported on every platform, so a misspelt name shows up while developing on a desktop without a game service.
ErrUnknownLeaderboard = errors.New("leaderboard: unknown leaderboard")
// ErrNoPlatformID means the board is declared but has no ID or storage entry for the game service of the platform the game runs on.
ErrNoPlatformID = errors.New("leaderboard: no ID for this platform's game service")
// ErrUnsupported means the platform has no game service the game can reach (Windows, Linux, the web, watchOS, simulated OS builds without a mini-game host, or a device without Game Center or Play Games), or the operation is unsupported by the current provider (such as Scores on ProviderMiniGame).
ErrUnsupported = gameservices.ErrUnsupported
// ErrUnavailable means the platform's game service could not be reached or is not enabled.
// ErrUnauthenticated means no player is signed in; call Service.SignIn first.
ErrUnauthenticated = gameservices.ErrUnauthenticated
// ErrCancelled means the player dismissed the platform's sign-in.
ErrCancelled = gameservices.ErrCancelled
)Errors a Service reports. The platform's own errors are NSGo's gameservices sentinels, repeated here so callers can test them with errors.Is without a second import.
Functions
func DecodeMiniGameScore(value string) (score, updateTime int64, err error)DecodeMiniGameScore decodes a JSON score payload produced by EncodeMiniGameScore.
func EncodeMiniGameScore(key string, score, updateTime int64) (string, error)EncodeMiniGameScore encodes score and updateTime (Unix seconds) into the JSON object format WeChat and Douyin open data contexts expect ({"wxgame":{"score":...,"update_time":...}}), verifying that len(key)+len(value) stays within MaxMiniGameValueBytes (1 KiB).
Types
type Board struct {
// Name is the game's own key for the board, such as "high-score". It is unique within the catalog.
Name string `yaml:"name"`
// GameCenter is the leaderboard ID registered in App Store Connect, used on iOS, iPadOS, tvOS and macOS.
GameCenter string `yaml:"gameCenter,omitempty"`
// PlayGames is the leaderboard ID the Google Play Console generated, used on Android.
PlayGames string `yaml:"playGames,omitempty"`
// MiniGame configures friend rankings on WeChat and Douyin mini games through the host's cloud storage and open data context.
MiniGame *MiniGameBoard `yaml:"miniGame,omitempty"`
}Board declares one leaderboard: the name the game's code uses and its ID or storage config in each platform game service. A board needs at least one platform entry; on a platform whose entry it lacks, Service reports ErrNoPlatformID.
func (b Board) ID(provider Provider) stringID returns the board's platform ID (or mini-game cloud storage key) for provider, or "" when the board declares none for it.
type Catalog struct {
// Version is the schema version; it must equal CurrentVersion.
Version int `yaml:"version"`
// Leaderboards lists the boards in the order the file declares them.
Leaderboards []Board `yaml:"leaderboards"`
}Catalog is the YAML file that declares a game's leaderboards once: each board's name in the game and its ID or storage entry in every platform game service it is registered with.
version: 1
leaderboards:
- name: high-score
gameCenter: com.example.game.high_score
playGames: CgkIxxxxxxxxxxEAIQAQ
miniGame:
key: best
order: desc
func Parse(data []byte) (*Catalog, error)Parse decodes a YAML leaderboard catalog and validates it. Unknown fields, duplicate keys and trailing YAML documents are refused.
func (c *Catalog) Board(name string) (Board, bool)Board returns a copy of the board declared under name and whether it exists.
func (c *Catalog) Encode() ([]byte, error)Encode validates c and writes it as deterministic two-space YAML: fields in schema order, boards in declaration order, and absent entries left out, so Parse followed by Encode reproduces a file Encode wrote byte for byte.
func (c *Catalog) Validate() errorValidate checks c against the version 1 schema: a supported version, at least one board, unique non-empty names without control characters or surrounding whitespace, at least one well-formed platform entry per board, no two boards sharing a Game Center, Play Games or mini-game key, and at most MaxMiniGameKeys (128) mini-game keys of at most MaxMiniGameKeyLength (128) bytes each.
type Entry = gameservices.ScoreEntryEntry is one ranked row of a leaderboard returned by Service.Scores. Its LeaderboardID is the platform ID, not the catalog name.
type MiniGameBoard struct {
// Key is the host user cloud storage key (at most MaxMiniGameKeyLength bytes, unique across boards in the catalog).
Key string `yaml:"key"`
// Order is the sort order ("desc" or "asc"); empty defaults to OrderDesc.
Order Order `yaml:"order,omitempty"`
}MiniGameBoard configures a leaderboard on WeChat and Douyin mini games through the host's user cloud storage and open data context.
func (m MiniGameBoard) EffectiveOrder() OrderEffectiveOrder returns m.Order, defaulting to OrderDesc when omitted.
type MiniGameEntry struct {
// Key is the catalog board's miniGame.key (at most MaxMiniGameKeyLength bytes).
Key string
// Value is the serialized score payload (WeChat's wxgame JSON object), bounded so len(Key)+len(Value) <= MaxMiniGameValueBytes.
Value string
}MiniGameEntry is one key-value pair written to a mini-game host's user cloud storage (such as wx.setUserCloudStorage on WeChat or tt.setUserCloudStorage on Douyin).
type MiniGameHost interface {
SetUserCloudStorage(entries []MiniGameEntry, done func(error))
ShowFriendRanking(req MiniGameRanking) error
HideFriendRanking() error
}MiniGameHost bridges Service to a mini-game host's user cloud storage and open data context (WeChat wx.* / Douyin tt.*, or an NSGo test host).
SetUserCloudStorage writes entries for the local player and invokes done with nil or an error from any goroutine; Service marshals callbacks onto the engine goroutine. ShowFriendRanking presents the open data context ranking view over req.Bounds, and HideFriendRanking removes it.
type MiniGameRanking struct {
// Key is the user cloud storage key whose friend entries to rank.
Key string
// Order is the sort order ("desc" or "asc") for ranking friend entries.
Order Order
// Bounds is the rectangle of the game view, in points, where the open data context draws the ranking.
Bounds core.Bounds
}MiniGameRanking describes a request to present the open data context friend ranking view over a rectangle of the game view.
type Option func(*serviceConfig)Option configures a Service created by New.
func WithMiniGameHost(host MiniGameHost) OptionWithMiniGameHost sets the MiniGameHost used when the service runs under ProviderMiniGame. On js/wasm mini-game targets, New uses the host's wx / tt bridge automatically when no custom host is supplied. Pass a test host here in nsgotest tests.
type Order stringOrder chooses whether higher or lower scores rank first on a mini-game board.
const (
// OrderDesc ranks higher scores first (for example, points). It is the default when MiniGameBoard.Order is omitted.
OrderDesc Order = "desc"
// OrderAsc ranks lower scores first (for example, race times).
OrderAsc Order = "asc"
)type Player = gameservices.PlayerPlayer is the local player signed into the platform game service.
type PlayerScope = gameservices.PlayerScopePlayerScope selects which players Service.Scores includes: Global or Friends.
type Provider uint8Provider names a platform game service a Board can carry an ID or storage entry for.
const (
// ProviderNone means the platform has no game service this package can use.
ProviderNone Provider = iota
// ProviderGameCenter is Apple's Game Center on iOS, iPadOS, tvOS and macOS.
ProviderGameCenter
// ProviderPlayGames is Google Play Games Services on Android.
ProviderPlayGames
// ProviderMiniGame is WeChat or Douyin mini-game friend rankings backed by host user cloud storage and the open data context.
ProviderMiniGame
)func ProviderFor(env *core.Env) ProviderProviderFor returns the leaderboard provider for env: ProviderMiniGame inside a mini program host (CanSignInMiniProgram), ProviderNone when env is nil or Simulated (such as a web build run with --nsgo-os ios), ProviderGameCenter on native macOS and iOS (which covers iPadOS and tvOS), ProviderPlayGames on native Android, and ProviderNone elsewhere.
func (p Provider) String() stringString returns the provider's catalog key: "gameCenter", "playGames", "miniGame" or "none".
type Query struct {
// Players chooses everyone (Global, the default) or the local player's friends (Friends).
Players PlayerScope
// Time chooses all-time scores (AllTime, the default), this week's (Week) or today's (Today).
Time TimeScope
// Limit is the most rows to load; 0 or less means 25, and more than 100 is clamped to 100.
Limit int
}Query selects the rows Service.Scores loads. The zero Query asks for the global all-time board with the platform's default of 25 rows.
type Service struct {
// contains filtered or unexported fields
}Service submits scores to and shows the leaderboards a Catalog declares, through NSGo's gameservices package (Game Center or Play Games) or a mini-game host's friend cloud storage and open data context (WeChat and Douyin). Every callback runs on the engine goroutine, after the call that started it has returned, so it may update signals and views directly.
func New(cx *core.Scope, c *Catalog, opts ...Option) (*Service, error)New validates c and returns a Service bound to cx, which keeps its own copy of the catalog. The service starts signed out; on Game Center and Play Games call SignIn before submitting scores. Pass Option values such as WithMiniGameHost to override the mini-game host in tests.
func (s *Service) Available() boolAvailable reports whether the platform's game service can be used here. It reads the environment reactively, so a view that calls it updates when that changes.
func (s *Service) Catalog() *CatalogCatalog returns a deep copy of the catalog the service was built from.
func (s *Service) Hide() errorHide removes the open data context friend ranking presented by Show or ShowIn on ProviderMiniGame. On platforms without an available game service it returns ErrUnsupported; on Game Center and Play Games native overlays are dismissed by the player and Hide returns nil.
func (s *Service) ID(name string) (string, error)ID returns the platform ID (or mini-game cloud storage key) of the board name, or ErrUnknownLeaderboard, ErrUnsupported or ErrNoPlatformID (checked in that order).
func (s *Service) Player() PlayerPlayer returns the signed-in player, or the zero Player while signed out. It reads a signal, so a view that calls it updates on sign-in and sign-out.
func (s *Service) Provider() ProviderProvider returns the game service of the platform the game runs on, whether or not it is reachable.
func (s *Service) Scores(name string, q Query, done func([]Entry, error))Scores loads ranked rows of the board name selected by q, for a game that draws its own board, and calls done with them or an error. done must not be nil. On ProviderMiniGame, Scores (including Friends) always answers ErrUnsupported because friend cloud storage is isolated inside the open data context and never returned to the game.
func (s *Service) Show(name string) errorShow presents the platform's own leaderboard UI for the board name. On ProviderMiniGame it presents the open data context friend ranking over the full game view; call ShowIn to place it inside a specific rectangle and Hide to remove it. It reports ErrUnknownLeaderboard, ErrUnsupported or ErrNoPlatformID instead of silently doing nothing; once it returns nil on Game Center or Play Games, what the platform shows (including its sign-in prompt) is up to the platform.
func (s *Service) ShowIn(name string, bounds core.Bounds) errorShowIn presents the leaderboard UI for name over bounds (in points relative to the game view). On ProviderMiniGame it sizes and positions the open data context friend ranking at bounds (or the full window when bounds.Size is zero). On Game Center and Play Games native sheets are full-screen, so ShowIn behaves like Show.
func (s *Service) SignIn(done func(Player, error))SignIn signs the local player into the platform game service, which may show the platform's own sign-in UI, and calls done with the player or an error such as ErrUnsupported or ErrCancelled. done may be nil.
func (s *Service) SignedIn() boolSignedIn reports whether a player is signed in, reactively like Player.
func (s *Service) Submit(name string, score int64, done func(error))Submit sends score to the board name for the signed-in player and calls done with the result; done may be nil. On Game Center and Play Games the platform keeps each player's best score by the board's own sort order; on ProviderMiniGame Service writes through host user cloud storage only when score improves on the player's previous best for the board's Order. A board the catalog does not declare, a platform without a game service or a board without an entry here fail through done without reaching the platform.
func (s *Service) Supports(name string) boolSupports reports whether the board name can be submitted to and shown here: the service is Available and the board has an entry for this platform. Like Available it reads reactively.
type TimeScope = gameservices.TimeScopeTimeScope selects the time window Service.Scores covers: AllTime, Week or Today.