Documentation
¶
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
- Variables
- func Encode(set *Set) ([]byte, error)
- func EncodeProgress(p *Progress) ([]byte, error)
- func SignIn(cx *core.Scope, t *Tracker, done func(gameservices.Player, error))
- func Validate(set *Set) error
- func ValidateProgress(p *Progress) error
- type Definition
- type Platforms
- type Progress
- type Record
- type Reporter
- type ReporterFunc
- type Service
- type Set
- type Store
- type Tracker
- func (t *Tracker) Add(id string, n int) error
- func (t *Tracker) Connect(service Service, r Reporter) error
- func (t *Tracker) Definitions() []Definition
- func (t *Tracker) Disconnect()
- func (t *Tracker) Flush()
- func (t *Tracker) Lookup(id string) (Definition, bool)
- func (t *Tracker) OnError(fn func(Definition, error))
- func (t *Tracker) OnUnlock(fn func(Definition))
- func (t *Tracker) Pending(service Service) []string
- func (t *Tracker) Percent(id string) float64
- func (t *Tracker) Persist(store Store, key string) error
- func (t *Tracker) Progress() *Progress
- func (t *Tracker) Restore(p *Progress) error
- func (t *Tracker) Service() Service
- func (t *Tracker) SetSteps(id string, steps int) error
- func (t *Tracker) Steps(id string) int
- func (t *Tracker) Unlock(id string) error
- func (t *Tracker) Unlocked(id string) bool
Examples ¶
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 ¶
Encode validates set and writes it as deterministic 2-space YAML that Parse reads back unchanged.
func EncodeProgress ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (Definition) TotalSteps ¶
func (d Definition) TotalSteps() int
TotalSteps returns the steps that complete d: Steps, or 1 when Steps is 0.
type Platforms ¶
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.
type Progress ¶
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 ¶
ParseProgress decodes a YAML progress document and validates it. Unknown fields and trailing YAML documents are refused.
type Record ¶
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 ¶
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 ¶
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 ¶
ReporterFunc adapts a function to the Reporter interface.
func (ReporterFunc) ReportAchievement ¶
func (f ReporterFunc) ReportAchievement(id string, percent float64, done func(error))
ReportAchievement calls f(id, percent, done).
type Service ¶
type Service string
Service names a platform game service an achievement is reported to.
func ServiceFor ¶
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.
Example ¶
ServiceFor names the game service a platform reports achievements to.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/achievements"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
fmt.Printf("%q %q %q\n", achievements.ServiceFor(core.OSIOS), achievements.ServiceFor(core.OSAndroid), achievements.ServiceFor(core.OSLinux))
}
Output: "gameCenter" "playGames" ""
type Set ¶
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 ¶
Parse decodes a YAML achievements file and validates it. Unknown fields and trailing YAML documents are refused.
Example ¶
Parse refuses unknown fields; Encode writes the file back byte for byte.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/achievements"
)
const exampleAchievements = `version: 1
achievements:
- id: first-match
title: First match
platforms:
gameCenter: com.example.first_match
playGames: CgkIxxxxEAIQAQ
- id: gem-collector
title: Gem collector
steps: 4
platforms:
gameCenter: com.example.gems
playGames: CgkIxxxxEAIQAg
`
func main() {
set, err := achievements.Parse([]byte(exampleAchievements))
if err != nil {
fmt.Println(err)
return
}
for _, d := range set.Achievements {
fmt.Println(d.ID, d.TotalSteps(), d.Platforms.GameCenter)
}
out, _ := achievements.Encode(set)
fmt.Println(string(out) == exampleAchievements)
_, err = achievements.Parse([]byte(exampleAchievements + "points: 10\n"))
fmt.Println(err != nil)
}
Output: first-match 1 com.example.first_match gem-collector 4 com.example.gems true true
type Tracker ¶
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.
Example ¶
A Tracker records progress toward a Set's achievements, calls OnUnlock once when one completes, and reports progress to the connected service under that service's own ID.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/achievements"
)
const exampleAchievements = `version: 1
achievements:
- id: first-match
title: First match
platforms:
gameCenter: com.example.first_match
playGames: CgkIxxxxEAIQAQ
- id: gem-collector
title: Gem collector
steps: 4
platforms:
gameCenter: com.example.gems
playGames: CgkIxxxxEAIQAg
`
func main() {
set, err := achievements.Parse([]byte(exampleAchievements))
if err != nil {
fmt.Println(err)
return
}
tr, err := achievements.NewTracker(set)
if err != nil {
fmt.Println(err)
return
}
tr.OnUnlock(func(d achievements.Definition) { fmt.Println("unlocked:", d.Title) })
// Progress made before sign-in is kept and reported once a service connects.
_ = tr.Add("gem-collector", 3)
fmt.Println(tr.Pending(achievements.GameCenter))
_ = tr.Connect(achievements.GameCenter, achievements.ReporterFunc(func(id string, percent float64, done func(error)) {
fmt.Printf("report %s %g%%\n", id, percent)
done(nil)
}))
_ = tr.Add("gem-collector", 5)
_ = tr.Unlock("first-match")
fmt.Println(tr.Percent("gem-collector"), len(tr.Pending(achievements.GameCenter)))
}
Output: [gem-collector] report com.example.gems 75% unlocked: Gem collector report com.example.gems 100% unlocked: First match report com.example.first_match 100% 100 0
func NewTracker ¶
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 (*Tracker) Add ¶
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 (*Tracker) Connect ¶
Connect makes r the Reporter for service and reports every achievement whose progress service has not acknowledged. It replaces any earlier connection.
func (*Tracker) Definitions ¶
func (t *Tracker) Definitions() []Definition
Definitions returns a copy of the tracked achievements in their declared order.
func (*Tracker) Disconnect ¶
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 (*Tracker) Flush ¶
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 (*Tracker) Lookup ¶
func (t *Tracker) Lookup(id string) (Definition, bool)
Lookup returns the definition whose ID is id.
func (*Tracker) OnError ¶
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 (*Tracker) OnUnlock ¶
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 (*Tracker) Pending ¶
Pending returns, in declared order, the IDs of achievements with an ID on service whose progress service has not acknowledged.
func (*Tracker) Percent ¶
Percent returns achievement id's completion from 0 to 100, 0 for an unknown ID.
func (*Tracker) Persist ¶
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.
Example ¶
Persist keeps the Tracker's progress in a Store, such as core.Storage, so a new session picks up where the last left off.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/achievements"
)
const exampleAchievements = `version: 1
achievements:
- id: first-match
title: First match
platforms:
gameCenter: com.example.first_match
playGames: CgkIxxxxEAIQAQ
- id: gem-collector
title: Gem collector
steps: 4
platforms:
gameCenter: com.example.gems
playGames: CgkIxxxxEAIQAg
`
// memoryStore is a Store in a map; a game passes core.Storage instead.
type memoryStore map[string]string
func (m memoryStore) GetItem(key string) (string, bool) { v, ok := m[key]; return v, ok }
func (m memoryStore) SetItem(key, value string) error { m[key] = value; return nil }
func main() {
set, _ := achievements.Parse([]byte(exampleAchievements))
store := memoryStore{}
first, _ := achievements.NewTracker(set)
_ = first.Persist(store, "achievements")
_ = first.Add("gem-collector", 2)
second, _ := achievements.NewTracker(set)
err := second.Persist(store, "achievements")
fmt.Println(err, second.Steps("gem-collector"), second.Percent("gem-collector"))
}
Output: <nil> 2 50
func (*Tracker) 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 (*Tracker) Restore ¶
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 (*Tracker) SetSteps ¶
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.