GitHubGet started

package achievements

import "github.com/nsgo-dev/game/pkg/achievements"

Overview

Package achievements declares a game's achievements once, in a versioned YAML file, tracks each player's progress toward them, and reports that progress through NSGo's platform game services: Game Center on macOS, iOS and tvOS, and Google Play Games Services on Android.

Definitions

A Set is the parsed form of an achievements file such as achievements.yaml. Each Definition has a game-wide ID that game code uses, an optional title and description for the game's own UI, a step count (1 for a one-shot achievement, more for one that fills up, such as "clear 500 gems"), and the ID each platform service knows it by. Game Center IDs are chosen by the developer in App Store Connect, Play Games IDs are generated by Play Console, so each service's ID is written out explicitly; an achievement without an ID for a service is not reported to that service.

Parse refuses unknown fields, unsupported versions, duplicate IDs and malformed platform IDs. Encode writes deterministic 2-space YAML, and a file Encode wrote parses and encodes back to the same bytes.

Progress

A Tracker holds the steps the player has made toward each achievement. Progress only moves forward: SetSteps ignores a lower count, Add saturates at the achievement's step count, and Unlock completes it. OnUnlock is called once when an achievement completes.

The Tracker remembers, per service, the steps the service last acknowledged, so progress made offline or before sign-in is reported once a service is connected, and progress a service already has is not sent again. Progress and EncodeProgress give that state as a versioned YAML document; Persist keeps it in core.Storage (or any Store) and rewrites it after every change.

Game services

SignIn picks the service for the running platform with ServiceFor, signs the player in with gameservices.Authenticate and, once signed in, connects the Tracker to a Reporter backed by gameservices.ReportAchievement, which reports everything pending. Where the platform has no game service (Windows, Linux, the web, watchOS) SignIn answers gameservices.ErrUnsupported and the Tracker keeps counting locally. Call gameservices.ShowAchievements to open the platform's own achievements screen.

Index

Constants

const CurrentVersion = 1

CurrentVersion is the schema version of both the achievements file (Set) and the progress document (Progress) this package reads and writes.

const MaxSteps = math.MaxInt32

MaxSteps is the largest step count a Definition may declare.

Variables

var (
	// ErrUnknownAchievement reports an ID that the Tracker's Set does not declare.
	ErrUnknownAchievement = errors.New("achievements: unknown achievement")
	// ErrSave reports that progress was recorded in memory but could not be written to the Store given to Persist; the next successful write saves it.
	ErrSave = errors.New("achievements: saving progress failed")
)

Functions

func Encode(set *Set) ([]byte, error)

Encode validates set and writes it as deterministic 2-space YAML that Parse reads back unchanged.

func EncodeProgress(p *Progress) ([]byte, error)

EncodeProgress validates p and writes it as deterministic 2-space YAML with records sorted by ID and services in name order, so ParseProgress reads it back unchanged.

func SignIn(cx *core.Scope, t *Tracker, done func(gameservices.Player, error))

SignIn signs the local player into the running platform's game service with gameservices.Authenticate and, once the player is signed in, connects t to that service through GameServices(cx), which reports all pending progress. Disposing cx, or letting its current owner run again as a view body does, disconnects t, unless t has been connected again since, so call SignIn from an event handler, an effect or a scope that lives as long as the game; progress made after that is reported by the next SignIn. done, which may be nil, receives the player or the error on cx's engine goroutine: gameservices.ErrUnsupported where the platform has no game service, and gameservices.ErrUnauthenticated when the service answers without a signed-in player. On failure t keeps recording progress, and a later SignIn reports it.

func Validate(set *Set) error

Validate checks that set follows the version 1 schema: known version, valid unique IDs, step counts in range, and well-formed platform IDs that no two achievements share on the same service.

func ValidateProgress(p *Progress) error

ValidateProgress checks that p follows the version 1 schema: known version, valid unique IDs, non-negative steps, and acknowledged steps for known services between 0 and the record's steps.

Types

type Definition struct {
	// ID is the game-wide identifier game code passes to Tracker: 1 to 128 ASCII letters, digits, '.', '_' or '-'.
	ID string `yaml:"id"`
	// Title is an optional display name for the game's own UI; the platform services show the name configured in their consoles.
	Title string `yaml:"title,omitempty"`
	// Description is an optional explanation for the game's own UI.
	Description string `yaml:"description,omitempty"`
	// Hidden marks an achievement the game's own UI should not reveal before it is unlocked.
	Hidden bool `yaml:"hidden,omitempty"`
	// Steps is the number of steps that complete the achievement, 1 to MaxSteps; 0 (omitted) means 1, a one-shot achievement.
	Steps int `yaml:"steps,omitempty"`
	// Platforms holds the ID each platform service knows the achievement by.
	Platforms Platforms `yaml:"platforms,omitempty"`
}

Definition declares one achievement.

func (d Definition) TotalSteps() int

TotalSteps returns the steps that complete d: Steps, or 1 when Steps is 0.

type Platforms struct {
	// GameCenter is the achievement ID configured in App Store Connect.
	GameCenter string `yaml:"gameCenter,omitempty"`
	// PlayGames is the achievement ID Play Console generated.
	PlayGames string `yaml:"playGames,omitempty"`
}

Platforms holds an achievement's ID on each platform service. An empty ID means the achievement is not reported to that service.

func (p Platforms) ID(s Service) string

ID returns the achievement's ID on service s, or "" when it has none there or s is unknown.

type Progress struct {
	// Version is the schema version; it must equal CurrentVersion (1).
	Version int `yaml:"version"`
	// Achievements holds one record per achievement with progress, sorted by ID.
	Achievements []Record `yaml:"achievements,omitempty"`
}

Progress is the root of a versioned YAML progress document: the steps a player has made and what each service has acknowledged.

func ParseProgress(data []byte) (*Progress, error)

ParseProgress decodes a YAML progress document and validates it. Unknown fields and trailing YAML documents are refused.

type Record struct {
	// ID is the achievement's Definition.ID.
	ID string `yaml:"id"`
	// Steps is the number of steps the player has made, 0 to the definition's TotalSteps.
	Steps int `yaml:"steps"`
	// Reported holds, per service, the steps that service last acknowledged; never more than Steps.
	Reported map[Service]int `yaml:"reported,omitempty"`
}

Record is one achievement's progress.

type Reporter interface {
	ReportAchievement(id string, percent float64, done func(error))
}

Reporter sends achievement progress to one platform service. ReportAchievement receives the achievement's ID on that service and its completion in percent (0 to 100, where 100 unlocks it) and must call done exactly once, from any goroutine, with nil once the service has accepted the update.

func GameServices(cx *core.Scope) Reporter

GameServices returns a Reporter that reports through gameservices.ReportAchievement on cx, so its answers arrive on cx's engine goroutine. Answers stop once cx is disposed, so a report still awaiting one when that happens would hold its achievement back for the rest of the connection: pass a scope that lives as long as the connection, such as the app's root scope, or call Tracker.Disconnect when cx is disposed. SignIn does the latter.

type ReporterFunc func(id string, percent float64, done func(error))

ReporterFunc adapts a function to the Reporter interface.

func (f ReporterFunc) ReportAchievement(id string, percent float64, done func(error))

ReportAchievement calls f(id, percent, done).

type Service string

Service names a platform game service an achievement is reported to.

const (
	// GameCenter is Apple's Game Center, reached through GameKit on macOS, iOS and tvOS.
	GameCenter Service = "gameCenter"
	// PlayGames is Google Play Games Services on Android.
	PlayGames Service = "playGames"
)
func ServiceFor(os core.OS) Service

ServiceFor returns the platform game service NSGo's gameservices package reaches on os: GameCenter on macOS and iOS (which includes tvOS), PlayGames on Android, and "" elsewhere.

func (s Service) Valid() bool

Valid reports whether s is a known Service.

type Set struct {
	// Version is the schema version; it must equal CurrentVersion (1).
	Version int `yaml:"version"`
	// Achievements lists the game's achievements in the order the game presents them.
	Achievements []Definition `yaml:"achievements,omitempty"`
}

Set is the root of a versioned YAML achievements file.

func Parse(data []byte) (*Set, error)

Parse decodes a YAML achievements file and validates it. Unknown fields and trailing YAML documents are refused.

func (s *Set) Clone() *Set

Clone returns a deep copy of s.

func (s *Set) Lookup(id string) (Definition, bool)

Lookup returns the definition whose ID is id.

type Store interface {
	GetItem(key string) (string, bool)
	SetItem(key, value string) error
}

Store is the key-value storage Persist keeps progress in; core.Storage satisfies it.

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

Tracker records a player's progress toward the achievements of a Set and reports it to a connected platform service. Its methods are safe for concurrent use; callbacks run without the Tracker's lock held, so they may call back into it.

func NewTracker(set *Set) (*Tracker, error)

NewTracker returns a Tracker for a copy of set, with no progress and no service connected. It returns the error Validate reports for an invalid set.

func (t *Tracker) Add(id string, n int) error

Add adds n steps to achievement id's progress, saturating at its step count. It returns an error for a negative n and does nothing for 0; otherwise it saves and reports as SetSteps does.

func (t *Tracker) Connect(service Service, r Reporter) error

Connect makes r the Reporter for service and reports every achievement whose progress service has not acknowledged. It replaces any earlier connection.

func (t *Tracker) Definitions() []Definition

Definitions returns a copy of the tracked achievements in their declared order.

func (t *Tracker) Disconnect()

Disconnect detaches the connected service. Progress keeps being recorded, and saved when Persist set a Store, and is reported on the next Connect.

func (t *Tracker) Flush()

Flush reports every achievement whose progress the connected service has not acknowledged and that is not already being reported. It does nothing without a connected service.

func (t *Tracker) Lookup(id string) (Definition, bool)

Lookup returns the definition whose ID is id.

func (t *Tracker) OnError(fn func(Definition, error))

OnError sets fn to be called with a failed report's achievement and error, or with a save failure wrapped in ErrSave; nil clears it. Failed reports stay pending and are retried by the next change, Flush or Connect.

func (t *Tracker) OnUnlock(fn func(Definition))

OnUnlock sets fn to be called once each time an achievement reaches its step count through SetSteps, Add or Unlock; nil clears it. Restore never calls it.

func (t *Tracker) Pending(service Service) []string

Pending returns, in declared order, the IDs of achievements with an ID on service whose progress service has not acknowledged.

func (t *Tracker) Percent(id string) float64

Percent returns achievement id's completion from 0 to 100, 0 for an unknown ID.

func (t *Tracker) Persist(store Store, key string) error

Persist loads the progress stored under key in store, if any, and then writes the progress back there as YAML after every change. When the stored progress cannot be parsed, Persist returns the error and leaves the Tracker and store untouched, so the caller decides whether to discard it.

func (t *Tracker) Progress() *Progress

Progress returns the current progress as a document EncodeProgress can write: one record per achievement with steps made or acknowledged, sorted by ID.

func (t *Tracker) Restore(p *Progress) error

Restore replaces the Tracker's progress with p. Records for achievements the Set no longer declares are dropped, and steps beyond an achievement's step count are capped. It does not call OnUnlock or save, and reports whatever is pending when a service is connected.

func (t *Tracker) Service() Service

Service returns the connected service, "" when none.

func (t *Tracker) SetSteps(id string, steps int) error

SetSteps raises achievement id's progress to steps, capped at its step count. Progress never goes back, so a count at or below the current one does nothing. The new progress is saved when Persist set a Store, and reported when a service is connected; a save failure is returned wrapped in ErrSave after the progress is recorded.

func (t *Tracker) Steps(id string) int

Steps returns the steps made toward achievement id, 0 for an unknown ID.

func (t *Tracker) Unlock(id string) error

Unlock completes achievement id. Unlocking an achievement that is already complete does nothing.

func (t *Tracker) Unlocked(id string) bool

Unlocked reports whether achievement id has reached its step count.