Documentation
¶
Overview ¶
Package progression is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package progression provides deterministic level-pack unlock rules.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/progression"
)
func main() {
pack, err := progression.Parse([]byte(`version: 1
levels:
- {id: meadow, stars: 3}
- {id: cave, stars: 3, unlockAt: 2}
- {id: summit, stars: 3, unlockAt: 5}
`))
if err != nil {
fmt.Println(err)
return
}
// A player with three stars in total has opened the first two levels.
for _, l := range pack.Levels {
fmt.Println(l.ID, pack.Unlocked(l.ID, 3))
}
fmt.Println("unknown", pack.Unlocked("secret", 99))
// Encode writes the canonical form, which parses back to the same pack.
data, err := progression.Encode(pack)
if err != nil {
fmt.Println(err)
return
}
again, err := progression.Parse(data)
fmt.Println(len(again.Levels), err)
}
Output: meadow true cave true summit false unknown false 3 <nil>
Index ¶
- Constants
- func Encode(p Pack) ([]byte, error)
- func EncodeManifest(m Manifest) ([]byte, error)
- func Metric(v float64) *float64
- func SaveProgress(store *save.Store, slot string, p Progress) error
- type BestResult
- type Level
- type LevelPack
- type LevelSpec
- type Manifest
- func (m Manifest) AllLevels() []LevelSpec
- func (m Manifest) Clone() Manifest
- func (m Manifest) EvaluateStars(levelID string, value float64) (int, bool)
- func (m Manifest) Level(id string) (LevelPack, LevelSpec, bool)
- func (m Manifest) Pack(id string) (LevelPack, bool)
- func (m Manifest) Validate() error
- type MetricDirection
- type Pack
- type PackTotals
- type Progress
- func (p Progress) Best(levelID string) (BestResult, bool)
- func (p *Progress) Bind(m Manifest)
- func (p Progress) Clone() Progress
- func (p Progress) MarshalJSON() ([]byte, error)
- func (p *Progress) Merge(other Progress) bool
- func (p Progress) Next(ctx UnlockContext) (LevelSpec, bool)
- func (p Progress) NextWith(m Manifest, ctx UnlockContext) (LevelSpec, bool)
- func (p Progress) PackTotals(packID string) (PackTotals, bool)
- func (p Progress) PackTotalsFor(m Manifest, packID string) (PackTotals, bool)
- func (p *Progress) Record(levelID string, res Result) bool
- func (p *Progress) RecordWith(m Manifest, levelID string, res Result) bool
- func (p Progress) Stars(levelID string) int
- func (p Progress) TotalStars() int
- func (p Progress) TotalStarsFor(m Manifest) int
- func (p Progress) Unlocked(id string, ctx UnlockContext) bool
- func (p Progress) UnlockedWith(m Manifest, id string, ctx UnlockContext) bool
- func (p *Progress) UnmarshalJSON(data []byte) error
- func (p Progress) Validate() error
- type Result
- type StarThresholds
- type UnlockContext
- type UnlockRule
Examples ¶
Constants ¶
const ( // ManifestVersion is the current multi-pack level manifest YAML schema version. ManifestVersion = 1 // SchemaURL is where the JSON Schema of the version 1 level-pack manifest is published. SchemaURL = "https://nsgo.games/schemas/progression.v1.json" // SchemaComment is the leading YAML comment that points editors at SchemaURL. SchemaComment = "# yaml-language-server: $schema=" + SchemaURL // PackSchemaURL is where the JSON Schema of the single-pack format (Pack) is published. PackSchemaURL = "https://nsgo.games/schemas/progression-pack.v1.json" )
const FormatVersion = 1
FormatVersion is the current level-pack YAML schema version.
const ProgressVersion = 1
ProgressVersion is the schema version of Progress JSON saves.
Variables ¶
This section is empty.
Functions ¶
func EncodeManifest ¶
EncodeManifest validates m and writes its deterministic 2-space YAML representation.
Types ¶
type BestResult ¶
type BestResult struct {
// Stars is the highest star count earned on the level (0 to 3).
Stars int `json:"stars"`
// Value is the best metric value achieved, if recorded.
Value *float64 `json:"value,omitempty"`
// Direction records the metric comparison direction when Value was recorded, so cloud merges remain accurate even if the level is temporarily absent from a manifest.
Direction MetricDirection `json:"direction,omitempty"`
}
BestResult holds the best stars and best metric value recorded for one level.
type Level ¶
type Level struct {
ID string `yaml:"id"`
Stars int `yaml:"stars"`
UnlockAt int `yaml:"unlockAt,omitempty"`
}
Level describes a level's star target and unlock threshold.
type LevelPack ¶
type LevelPack struct {
// ID uniquely identifies the pack within the Manifest.
ID string `yaml:"id" json:"id" schema:"required"`
// Name maps locale codes (such as "en", "zh") to localized pack titles.
Name map[string]string `yaml:"name,omitempty" json:"name,omitempty"`
// NameKey optionally names a localization catalog key when pack titles live in l10n tables.
NameKey string `yaml:"nameKey,omitempty" json:"nameKey,omitempty"`
// Unlock optionally restricts when the pack and all levels inside it can be played.
Unlock *UnlockRule `yaml:"unlock,omitempty" json:"unlock,omitempty"`
// Levels lists the pack's levels in display/play order.
Levels []LevelSpec `yaml:"levels" json:"levels" schema:"required,minItems=1"`
}
LevelPack groups an ordered sequence of levels with pack-level localization and unlock rules.
func (LevelPack) LocalizedName ¶
LocalizedName picks the best display title for locale from Name, falling back to base language tag, "en", the first sorted locale key, NameKey, and finally ID.
type LevelSpec ¶
type LevelSpec struct {
// ID uniquely identifies the level across the entire Manifest and keys saved progress.
ID string `yaml:"id" json:"id" schema:"required"`
// Name maps locale codes (such as "en", "zh") to localized display titles.
Name map[string]string `yaml:"name,omitempty" json:"name,omitempty"`
// NameKey optionally names a localization catalog key when titles live in l10n tables.
NameKey string `yaml:"nameKey,omitempty" json:"nameKey,omitempty"`
// File optionally points to the level's data or scene file.
File string `yaml:"file,omitempty" json:"file,omitempty"`
// Stars optionally defines named-metric thresholds for awarding 0–3 stars.
Stars *StarThresholds `yaml:"stars,omitempty" json:"stars,omitempty"`
// Unlock optionally restricts when the level can be played.
Unlock *UnlockRule `yaml:"unlock,omitempty" json:"unlock,omitempty"`
}
LevelSpec describes one level in a LevelPack.
func (LevelSpec) LocalizedName ¶
LocalizedName picks the best display title for locale from Name, falling back to base language tag, "en", the first sorted locale key, NameKey, and finally ID.
type Manifest ¶
type Manifest struct {
// Version is the schema version; it must equal ManifestVersion (1).
Version int `yaml:"version" json:"version" schema:"required"`
// Packs lists the game's level packs in display order.
Packs []LevelPack `yaml:"packs" json:"packs" schema:"required,minItems=1"`
}
Manifest is a versioned YAML catalog of level packs, star thresholds, and unlock rules.
func ParseManifest ¶
ParseManifest decodes and validates a version 1 progression manifest YAML document. Unknown fields, trailing YAML documents, duplicate keys, invalid thresholds, unknown After references, and dependency cycles are refused with a *loaderr.Error.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/progression"
)
func main() {
manifest, err := progression.ParseManifest([]byte(`version: 1
packs:
- id: meadow
name:
en: Meadow
levels:
- id: meadow-1
stars:
metric: moves
direction: lower
two: 5
three: 3
- id: meadow-2
unlock:
after: [meadow-1]
`))
if err != nil {
fmt.Println(err)
return
}
progress := progression.NewProgress(manifest)
progress.Record("meadow-1", progression.Result{Value: progression.Metric(3)})
next, ok := progress.Next(progression.UnlockContext{})
fmt.Println(progress.Stars("meadow-1"), progress.Unlocked("meadow-2", progression.UnlockContext{}), ok, next.ID)
}
Output: 3 true true meadow-2
func (Manifest) EvaluateStars ¶
EvaluateStars computes the stars (0 to 3) for value on levelID, returning false if levelID is unknown.
type MetricDirection ¶
type MetricDirection string
MetricDirection selects whether higher or lower metric values earn more stars.
const ( // HigherIsBetter awards more stars for larger metric values (for example score or moves left). HigherIsBetter MetricDirection = "higher" // LowerIsBetter awards more stars for smaller metric values (for example moves taken or time elapsed). LowerIsBetter MetricDirection = "lower" )
func (MetricDirection) Valid ¶
func (d MetricDirection) Valid() bool
Valid reports whether d is empty (defaults to HigherIsBetter), HigherIsBetter, or LowerIsBetter.
type Pack ¶
Pack is a versioned collection of level unlock records.
func Parse ¶
Parse decodes and validates one level-pack YAML document. It refuses unknown fields and a second YAML document, and returns a *loaderr.Error.
Example (Invalid) ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/loaderr"
"github.com/nsgo-dev/game/pkg/progression"
)
func main() {
_, err := progression.Parse([]byte("version: 1\nlevels:\n - {id: meadow, stars: 4}\n"))
// The error names the field to fix.
if le, ok := loaderr.As(err); ok {
fmt.Println(le.Field)
}
}
Output: levels[0].stars
type PackTotals ¶
type PackTotals struct {
PackID string
EarnedStars int
MaxStars int
CompletedLevels int
TotalLevels int
}
PackTotals summarizes a player's progress within one LevelPack.
type Progress ¶
type Progress struct {
// Version is ProgressVersion (1).
Version int `json:"version"`
// Levels maps each level ID to its best recorded result.
Levels map[string]BestResult `json:"levels,omitempty"`
// contains filtered or unexported fields
}
Progress stores per-level best results keyed by stable level ID. Unknown level IDs loaded from a save or merged from the cloud are preserved across saves and merges, while manifest queries (TotalStars, PackTotals, Next) ignore them until a manifest declares them again.
func LoadProgress ¶
LoadProgress loads Progress from slot in store and validates it. When store returns an error (such as save.ErrNotFound, a damaged save, or save.ErrFutureVersion), LoadProgress returns an empty NewProgress() alongside the error so the game can still start.
func Merge ¶
Merge combines two Progress snapshots commutatively by taking the best stars and best metric value for every level ID in either snapshot, preserving unknown level IDs. Pass an optional Manifest so metric comparisons use each level's configured StarThresholds.Direction.
func NewProgress ¶
NewProgress returns an empty version-1 Progress, optionally bound to manifest.
func (Progress) Best ¶
func (p Progress) Best(levelID string) (BestResult, bool)
Best returns a copy of the best recorded result for levelID, if any.
func (*Progress) Bind ¶
Bind attaches a copy of m to p so Record, Unlocked, TotalStars, PackTotals, Next, and Merge use m without repeating it on every call.
func (Progress) Clone ¶
Clone returns a deep copy of p, including its bound manifest reference if any.
func (Progress) MarshalJSON ¶
MarshalJSON writes p as versioned deterministic JSON (encoding/json sorts map keys).
func (*Progress) Merge ¶
Merge combines other into p using the best-per-level conflict rule (highest stars and best metric value per level, keeping unknown level IDs from both copies), and reports whether p changed.
func (Progress) Next ¶
func (p Progress) Next(ctx UnlockContext) (LevelSpec, bool)
Next returns the first unlocked level in the bound manifest that has 0 earned stars.
func (Progress) NextWith ¶
func (p Progress) NextWith(m Manifest, ctx UnlockContext) (LevelSpec, bool)
NextWith returns the first unlocked level in m that has 0 earned stars.
func (Progress) PackTotals ¶
func (p Progress) PackTotals(packID string) (PackTotals, bool)
PackTotals returns earned/max stars and completed/total level counts for packID in the bound manifest.
func (Progress) PackTotalsFor ¶
func (p Progress) PackTotalsFor(m Manifest, packID string) (PackTotals, bool)
PackTotalsFor returns earned/max stars and completed/total level counts for packID in m.
func (*Progress) Record ¶
Record updates the best result for levelID using the manifest bound via NewProgress or Bind (if any) and reports whether p improved.
func (*Progress) RecordWith ¶
RecordWith updates the best result for levelID against m (computing stars from StarThresholds when res.Stars is 0 and res.Value is set) and reports whether p improved.
func (Progress) TotalStars ¶
TotalStars returns the sum of earned stars across the bound manifest (or across all recorded levels if no manifest is bound).
func (Progress) TotalStarsFor ¶
TotalStarsFor returns the sum of earned stars across levels declared in m, ignoring unknown level IDs kept in p.
func (Progress) Unlocked ¶
func (p Progress) Unlocked(id string, ctx UnlockContext) bool
Unlocked reports whether pack or level id is unlocked in the bound manifest under ctx. For a level, both its containing pack's Unlock rule and the level's own Unlock rule must pass.
func (Progress) UnlockedWith ¶
func (p Progress) UnlockedWith(m Manifest, id string, ctx UnlockContext) bool
UnlockedWith reports whether pack or level id is unlocked in m under ctx.
func (*Progress) UnmarshalJSON ¶
UnmarshalJSON strictly decodes versioned Progress JSON, refusing unknown fields, trailing tokens, and out-of-range values while preserving unknown level IDs.
type Result ¶
type Result struct {
// Stars is the earned star rating (0 to 3). When 0 and Value is set for a level with StarThresholds, Progress.Record computes Stars from the manifest's thresholds.
Stars int `json:"stars"`
// Value is the optional metric value achieved (such as score, moves, or time).
Value *float64 `json:"value,omitempty"`
}
Result is the outcome of one level attempt passed to Progress.Record.
type StarThresholds ¶
type StarThresholds struct {
// Metric names the score, moves, time, or other value evaluated (such as "score", "moves", or "time").
Metric string `yaml:"metric" json:"metric" schema:"required"`
// Direction is "higher" (default when omitted) or "lower".
Direction MetricDirection `yaml:"direction,omitempty" json:"direction,omitempty" schema:"enum=higher|lower"`
// One optionally sets the minimum ("higher") or maximum ("lower") value needed for 1 star. When omitted, any completed run earns at least 1 star.
One *float64 `yaml:"one,omitempty" json:"one,omitempty"`
// Two is the threshold that earns 2 stars.
Two float64 `yaml:"two" json:"two" schema:"required"`
// Three is the threshold that earns 3 stars.
Three float64 `yaml:"three" json:"three" schema:"required"`
}
StarThresholds configures how a named metric maps to 0–3 stars.
func (StarThresholds) EffectiveDirection ¶
func (s StarThresholds) EffectiveDirection() MetricDirection
EffectiveDirection returns HigherIsBetter when Direction is empty, otherwise Direction.
func (StarThresholds) Evaluate ¶
func (s StarThresholds) Evaluate(value float64) int
Evaluate returns the stars (0 to 3) earned for value under s. NaN always returns 0. When One is nil, any non-NaN value earns at least 1 star.
type UnlockContext ¶
type UnlockContext struct {
// Now is the current instant checked against UnlockRule.From. A zero Now keeps time-gated packs and levels locked.
Now time.Time
// Owned lists entitlement or purchase IDs owned by the player, checked against UnlockRule.Owned.
Owned map[string]bool
}
UnlockContext supplies external runtime state checked by UnlockRule evaluation without reading global clocks or stores.
type UnlockRule ¶
type UnlockRule struct {
// After lists level or pack IDs that must be won (at least 1 star on each level) before this entry unlocks.
After []string `yaml:"after,omitempty,flow" json:"after,omitempty"`
// Stars is the minimum total stars earned across the manifest needed to unlock.
Stars int `yaml:"stars,omitempty" json:"stars,omitempty" schema:"minimum=0"`
// Owned names an entitlement or purchase ID that must be present in UnlockContext.Owned.
Owned string `yaml:"owned,omitempty" json:"owned,omitempty"`
// From is an optional UTC date ("YYYY-MM-DD") or RFC 3339 timestamp from which this entry unlocks.
From string `yaml:"from,omitempty" json:"from,omitempty"`
}
UnlockRule defines the requirements for a pack or level to be unlocked. All specified conditions must be satisfied together.
func (UnlockRule) FromTime ¶
func (r UnlockRule) FromTime() (time.Time, bool)
FromTime parses r.From into a UTC instant, returning false when From is empty or invalid.
func (UnlockRule) IsZero ¶
func (r UnlockRule) IsZero() bool
IsZero reports whether r declares no unlock conditions.