Эта страница ещё не переведена на русский язык, поэтому ниже показан английский оригинал.
Мультиплеер и модыAchievements
import "github.com/nsgo-dev/game/pkg/achievements"
achievements declares a game's achievements once, in a versioned YAML file, tracks the player's progress toward them, and reports that progress through NSGo's gameservices package: Game Center on macOS, iOS and tvOS, and Google Play Games Services on Android. It uses only Go's standard library, NSGo's public API and the YAML library the module already depends on.
The achievements file
Each achievement has a game-wide id that game code uses, and the ID each platform service knows it by. Game Center IDs are chosen by the developer in App Store Connect and Play Games IDs are generated by Play Console, so each is written out; an achievement without an ID for a service is not reported to that service.
version: 1
achievements:
- id: first-match
title: First Match
description: Clear your first line of gems.
platforms:
gameCenter: com.example.mygame.first_match
playGames: CgkIxxxxxxxxxxEAIQAQ
- id: gem-collector
title: Gem Collector
description: Clear 300 gems.
steps: 300
platforms:
gameCenter: com.example.mygame.gem_collector
playGames: CgkIxxxxxxxxxxEAIQAg
- id: high-roller
title: High Roller
hidden: true
platforms:
gameCenter: com.example.mygame.high_roller
| Field | Meaning |
|---|---|
version |
Schema version, 1 |
id |
1 to 128 ASCII letters, digits, ., _ or -, unique in the file |
title, description |
Optional text for the game's own UI; the platform screens show what their consoles hold |
hidden |
The game's own UI should not reveal the achievement before it is unlocked |
steps |
Steps that complete the achievement, 1 to MaxSteps; omitted means 1, a one-shot achievement |
platforms.gameCenter, platforms.playGames |
The achievement's ID on each service: no whitespace or control characters, at most 255 bytes, and not shared by two achievements on the same service |
Parse refuses unknown fields, a version other than 1, trailing YAML documents, duplicate IDs and malformed platform IDs. Encode writes deterministic 2-space YAML in the order above, and a file Encode wrote parses and encodes back to the same bytes, so a test can keep the file canonical:
//go:embed achievements.yaml
var achievementsYAML []byte
set, err := achievements.Parse(achievementsYAML)
out, err := achievements.Encode(set) // equal to achievementsYAML when the file is canonical
Tracking progress
A Tracker holds the steps the player has made toward each achievement of a Set. Progress only moves forward.
Unlock(id)completes an achievement; unlocking a completed one does nothing.Add(id, n)adds steps and saturates at the achievement's step count;SetSteps(id, n)raises progress tonand ignores a lower count.Steps,Percent,UnlockedandLookupread the state;Definitionslists the achievements in declared order.OnUnlock(fn)is called once when an achievement completes throughUnlock,AddorSetSteps, never when progress is restored.- An ID the set does not declare returns an error wrapping
ErrUnknownAchievement.
tracker, err := achievements.NewTracker(set)
tracker.OnUnlock(func(d achievements.Definition) {
status.Set("Achievement unlocked: " + d.Title)
})
tracker.Unlock("first-match")
tracker.Add("gem-collector", cleared)
The Tracker's methods are safe for concurrent use, and its callbacks run without its lock held, so they may call back into it.
Saving progress
Persist(store, key) loads the progress stored under key, if any, and from then on writes it back after every change. core.Storage is a Store, as is any type with GetItem and SetItem. When the stored progress cannot be parsed, Persist returns the error and changes nothing, so the game decides whether to discard it:
store := cx.Storage()
if err := tracker.Persist(store, "mygame.achievements"); err != nil {
store.RemoveItem("mygame.achievements")
err = tracker.Persist(store, "mygame.achievements")
}
The stored progress is a versioned YAML document, sorted by ID, holding the steps made and, per service, the steps that service last acknowledged:
version: 1
achievements:
- id: first-match
steps: 1
reported:
gameCenter: 1
- id: gem-collector
steps: 42
Progress and Restore give and replace the same state in memory, and ParseProgress and EncodeProgress read and write it with the same rules as the achievements file. Restoring drops records for achievements the set no longer declares and caps steps at an achievement's step count. A failed save keeps the progress in memory and returns an error wrapping ErrSave; the next successful write saves it.
Reporting to Game Center and Play Games
SignIn(cx, tracker, done) picks the service for the running platform with ServiceFor, signs the player in with gameservices.Authenticate and, once the player is signed in, connects the Tracker to that service, which reports everything the service has not acknowledged. done runs on the engine goroutine with the player or the error:
gameservices.ErrUnsupportedwhere the platform has no game service (Windows, Linux, the web, watchOS) orcx.Env().CanUseGameServices()is false.gameservices.ErrUnauthenticatedwhen the service answers without a signed-in player, andgameservices.ErrCancelledwhen the player dismisses sign-in.
On failure the Tracker keeps counting, and a later SignIn reports what was made in the meantime. Answers from the service arrive through cx, so disposing cx or letting its current owner run again, as a view body does on every render, disconnects the Tracker; sign in from an event handler or an effect, or with a scope that lives as long as the game, such as the root scope, or call SignIn again from the next screen. gameservices.ShowAchievements(cx) opens the platform's own achievements screen.
signedIn := core.NewSignal(cx, false)
achievements.SignIn(cx, tracker, func(_ gameservices.Player, err error) {
signedIn.Set(err == nil)
})
core.Show{
When: signedIn.Get,
Then: func(*core.Scope) core.Node {
return ui.Button{Text: "Achievements", OnPress: func() { gameservices.ShowAchievements(cx) }}
},
}
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 the service already has is not sent again. While a report is waiting for an answer, further progress on that achievement is held back and sent as one follow-up report, so a run of Add calls does not flood the service. A failed report stays pending: OnError receives it, and the next change, Flush or Connect sends it again. Pending(service) lists what a service has not acknowledged.
Progress goes to the service as a percentage: a 300-step achievement with 42 steps is reported as 14%. Configure it in Play Console as a standard achievement, not an incremental one, since gameservices reports percentages.
Connect(service, reporter) and Disconnect attach and detach a service directly, for a game that signs in by other means; GameServices(cx) is the Reporter backed by gameservices.ReportAchievement, and any type with a ReportAchievement(id, percent, done) method is a Reporter. A Reporter must answer every report exactly once; GameServices(cx) stops answering once cx is disposed, so call Disconnect then.
Platform setup
- Game Center: enable Game Center for the app's ID and create each achievement in App Store Connect, using the IDs in
platforms.gameCenter. NSGo does not yet add the Game Center entitlement to the app it builds. - Play Games: create each achievement in Play Console and copy its generated ID into
platforms.playGames. NSGo'sgameserviceshas its Android side in place, but the Java runtime hook that reaches Play Games Services is not in NSGo's runtime yet, soCanUseGameServicesis false on Android today andSignInanswersErrUnsupportedthere; progress is still kept and is reported once that hook ships.
Testing
NSGo's nsgotest gives each test app an in-memory game services fake. Enable it with nsgotest.Environment(core.Environment{OS: core.OSAndroid, CanUseGameServices: true}), sign a player in with App.SetGameServicesPlayer, and read what was reported with App.GameServicesAchievements:
app := nsgotest.Start(t, root, nsgotest.Environment(core.Environment{OS: core.OSMacOS, CanUseGameServices: true}))
app.SetGameServicesPlayer(gameservices.Player{ID: "p1", DisplayName: "Ada"})
// ... play until the achievement unlocks ...
app.Settle()
got := app.GameServicesAchievements() // [{ID: "com.example.mygame.first_match", PercentComplete: 100, Unlocked: true}]
App.SetGameServicesError and App.SetGameServicesAuthError simulate an outage or a cancelled sign-in. The SlideGem example unlocks its first achievement on Game Center and on Play Games this way.