leaderboard

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

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.

A game declares its boards once in a versioned YAML Catalog that maps each board's name in the game to its ID in every game 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

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 and mini programs) they report ErrUnsupported, and Available and Supports let a view hide its leaderboard button there. A misspelt board name reports ErrUnknownLeaderboard on every platform.

Tests run against nsgotest's per-app fake game service: start the app with nsgotest.Environment(core.Environment{CanUseGameServices: true, OS: core.OSIOS}), sign a player in with App.SetGameServicesPlayer, and read App.GameServicesSubmittedScores and App.GameServicesShownLeaderboards.

Index

Examples

Constants

View Source
const (
	Global  = gameservices.Global
	Friends = gameservices.Friends
)

Player scopes for Query.Players.

View Source
const (
	AllTime = gameservices.AllTime
	Week    = gameservices.Week
	Today   = gameservices.Today
)

Time scopes for Query.Time.

View Source
const CurrentVersion = 1

CurrentVersion is the leaderboard catalog schema version this package reads and writes.

View Source
const MaxIDLength = 100

MaxIDLength is the longest platform leaderboard ID a catalog accepts, matching Game Center's limit of 100 characters.

Variables

View Source
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 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, mini programs, or a device without Game Center or Play Games).
	ErrUnsupported = gameservices.ErrUnsupported
	// ErrUnavailable means the platform's game service could not be reached or is not enabled.
	ErrUnavailable = gameservices.ErrUnavailable
	// 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

This section is empty.

Types

type Board

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"`
}

Board declares one leaderboard: the name the game's code uses and the ID it has in each platform game service. A board needs at least one ID; on a platform whose ID it lacks, Service reports ErrNoPlatformID.

func (Board) ID

func (b Board) ID(provider Provider) string

ID returns the board's ID for provider, or "" when the board declares none for it.

type Catalog

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 in every platform game service it is registered with.

version: 1
leaderboards:
  - name: high-score
    gameCenter: com.example.game.high_score
    playGames: CgkIxxxxxxxxxxEAIQAQ

func Parse

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.

Example

A Catalog maps each board's name in the game to its ID in every platform game service; Encode writes a parsed catalog back byte for byte.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/leaderboard"
)

const exampleCatalog = `version: 1
leaderboards:
  - name: high-score
    gameCenter: com.example.game.high_score
    playGames: CgkIxxxxxxxxxxEAIQAQ
  - name: daily
    playGames: CgkIxxxxxxxxxxEAIQAw
`

func main() {
	c, err := leaderboard.Parse([]byte(exampleCatalog))
	if err != nil {
		fmt.Println(err)
		return
	}
	b, _ := c.Board("high-score")
	fmt.Println(b.ID(leaderboard.ProviderGameCenter), b.ID(leaderboard.ProviderPlayGames))
	daily, _ := c.Board("daily")
	fmt.Printf("%q\n", daily.ID(leaderboard.ProviderGameCenter))
	out, _ := c.Encode()
	fmt.Println(string(out) == exampleCatalog)
	_, err = leaderboard.Parse([]byte(exampleCatalog + "sort: descending\n"))
	fmt.Println(err != nil)
}
Output:
com.example.game.high_score CgkIxxxxxxxxxxEAIQAQ
""
true
true

func (*Catalog) Board

func (c *Catalog) Board(name string) (Board, bool)

Board returns the board declared under name and whether it exists.

func (*Catalog) Encode

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 IDs left out, so Parse followed by Encode reproduces a file Encode wrote byte for byte.

func (*Catalog) Validate

func (c *Catalog) Validate() error

Validate 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 ID per board, and no two boards sharing a Game Center or Play Games ID.

type Entry

type Entry = gameservices.ScoreEntry

Entry is one ranked row of a leaderboard returned by Service.Scores. Its LeaderboardID is the platform ID, not the catalog name.

type Player

type Player = gameservices.Player

Player is the local player signed into the platform game service.

type PlayerScope

type PlayerScope = gameservices.PlayerScope

PlayerScope selects which players Service.Scores includes: Global or Friends.

type Provider

type Provider uint8

Provider names a platform game service a Board can carry an ID 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
)

func ProviderFor

func ProviderFor(os core.OS) Provider

ProviderFor returns the game service NSGo's gameservices package talks to on os: Game Center on macOS and iOS (which covers iPadOS and tvOS), Play Games on Android, and ProviderNone elsewhere.

Example

ProviderFor names the game service a platform's leaderboards go through.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/leaderboard"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	for _, os := range []core.OS{core.OSIOS, core.OSMacOS, core.OSAndroid, core.OSWindows} {
		fmt.Println(leaderboard.ProviderFor(os))
	}
}
Output:
gameCenter
gameCenter
playGames
none

func (Provider) String

func (p Provider) String() string

String returns the provider's catalog key: "gameCenter", "playGames" or "none".

type Query

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

type Service struct {
	// contains filtered or unexported fields
}

Service submits scores to and shows the leaderboards a Catalog declares, through NSGo's gameservices package and so through Game Center or Play Games. Every callback runs on the engine goroutine, after the call that started it has returned, so it may update signals and views directly.

Example

A Service names boards by their catalog names; a misspelt name is refused on every platform before the platform is reached.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/leaderboard"
	"github.com/nsgo-dev/nsgo/core"
)

const exampleCatalog = `version: 1
leaderboards:
  - name: high-score
    gameCenter: com.example.game.high_score
    playGames: CgkIxxxxxxxxxxEAIQAQ
  - name: daily
    playGames: CgkIxxxxxxxxxxEAIQAw
`

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()
	c, _ := leaderboard.Parse([]byte(exampleCatalog))
	boards, err := leaderboard.New(root, c)
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = boards.ID("high-scores")
	fmt.Println(err)
	fmt.Println(boards.Show("high-scores"))
	fmt.Println(boards.SignedIn(), len(boards.Catalog().Leaderboards))
}
Output:
leaderboard: unknown leaderboard "high-scores"
leaderboard: unknown leaderboard "high-scores"
false 2

func New

func New(cx *core.Scope, c *Catalog) (*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; call SignIn before submitting scores.

func (*Service) Available

func (s *Service) Available() bool

Available 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 (*Service) Catalog

func (s *Service) Catalog() *Catalog

Catalog returns a copy of the catalog the service was built from.

func (*Service) ID

func (s *Service) ID(name string) (string, error)

ID returns the platform ID of the board name, or ErrUnknownLeaderboard, ErrUnsupported or ErrNoPlatformID (checked in that order).

func (*Service) Player

func (s *Service) Player() Player

Player 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 (*Service) Provider

func (s *Service) Provider() Provider

Provider returns the game service of the platform the game runs on, whether or not it is reachable.

func (*Service) Scores

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.

func (*Service) Show

func (s *Service) Show(name string) error

Show presents the platform's own leaderboard UI for the board name. It reports ErrUnknownLeaderboard, ErrUnsupported or ErrNoPlatformID instead of silently doing nothing; once it returns nil, what the platform shows (including its sign-in prompt) is up to the platform.

func (*Service) SignIn

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 (*Service) SignedIn

func (s *Service) SignedIn() bool

SignedIn reports whether a player is signed in, reactively like Player.

func (*Service) Submit

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. The platform keeps each player's best score by the board's own sort order, so a game can submit every finished run. A board the catalog does not declare, a platform without a game service or a board without an ID here fail through done without reaching the platform.

func (*Service) Supports

func (s *Service) Supports(name string) bool

Supports reports whether the board name can be submitted to and shown here: the service is Available and the board has an ID for this platform. Like Available it reads reactively.

type TimeScope

type TimeScope = gameservices.TimeScope

TimeScope selects the time window Service.Scores covers: AllTime, Week or Today.

Directories

Path Synopsis
Package selfhost is a self-hostable leaderboard service, for cross-platform games and games on platforms without a game service: one board ranks the scores a player's devices submit from every platform, keyed by the account the accounts package signs in.
Package selfhost is a self-hostable leaderboard service, for cross-platform games and games on platforms without a game service: one board ranks the scores a player's devices submit from every platform, keyed by the account the accounts package signs in.
cmd/leaderboardd command
Command leaderboardd runs the self-hosted leaderboard service as a standalone HTTP server, with its scores in a directory of JSON Lines files.
Command leaderboardd runs the self-hosted leaderboard service as a standalone HTTP server, with its scores in a directory of JSON Lines files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL