progression

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 12 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 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

Examples

Constants

View Source
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"
)
View Source
const FormatVersion = 1

FormatVersion is the current level-pack YAML schema version.

View Source
const ProgressVersion = 1

ProgressVersion is the schema version of Progress JSON saves.

Variables

This section is empty.

Functions

func Encode

func Encode(p Pack) ([]byte, error)

Encode validates p and writes its deterministic YAML representation.

func EncodeManifest

func EncodeManifest(m Manifest) ([]byte, error)

EncodeManifest validates m and writes its deterministic 2-space YAML representation.

func Metric

func Metric(v float64) *float64

Metric returns a pointer to v for populating Result.Value or StarThresholds.One.

func SaveProgress

func SaveProgress(store *save.Store, slot string, p Progress) error

SaveProgress validates p and saves it as versioned JSON in store under slot.

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) Level

func (p LevelPack) Level(id string) (LevelSpec, bool)

Level returns the level with the given ID in p, if present.

func (LevelPack) LocalizedName

func (p LevelPack) LocalizedName(locale string) string

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

func (l LevelSpec) LocalizedName(locale string) string

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.

func (LevelSpec) StarsFor

func (l LevelSpec) StarsFor(value float64) int

StarsFor evaluates value against Stars when defined; without thresholds it returns 1 for any completed run.

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

func ParseManifest(data []byte) (Manifest, error)

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) AllLevels

func (m Manifest) AllLevels() []LevelSpec

AllLevels returns all levels across all packs in manifest order.

func (Manifest) Clone

func (m Manifest) Clone() Manifest

Clone returns a deep copy of m.

func (Manifest) EvaluateStars

func (m Manifest) EvaluateStars(levelID string, value float64) (int, bool)

EvaluateStars computes the stars (0 to 3) for value on levelID, returning false if levelID is unknown.

func (Manifest) Level

func (m Manifest) Level(id string) (LevelPack, LevelSpec, bool)

Level returns the containing pack and level spec for id, if present.

func (Manifest) Pack

func (m Manifest) Pack(id string) (LevelPack, bool)

Pack returns the pack with the given ID, if present.

func (Manifest) Validate

func (m Manifest) Validate() error

Validate checks m against the version 1 schema and returns a *loaderr.Error naming the first offending field.

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

type Pack struct {
	Version int     `yaml:"version"`
	Levels  []Level `yaml:"levels"`
}

Pack is a versioned collection of level unlock records.

func Parse

func Parse(data []byte) (Pack, error)

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

func (Pack) Unlocked

func (p Pack) Unlocked(id string, stars int) bool

Unlocked reports whether the level id is available to a player who has collected stars stars in total: whether stars reaches its unlockAt. An unknown id is never unlocked.

func (Pack) Validate

func (p Pack) Validate() error

Validate reports a version other than FormatVersion, an empty pack, an empty, padded or repeated level ID, stars outside 1 to 3 and a negative unlockAt, as a *loaderr.Error naming the field.

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

func LoadProgress(store *save.Store, slot string) (Progress, error)

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

func Merge(a, b Progress, manifest ...Manifest) Progress

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

func NewProgress(manifest ...Manifest) Progress

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

func (p *Progress) Bind(m Manifest)

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

func (p Progress) Clone() Progress

Clone returns a deep copy of p, including its bound manifest reference if any.

func (Progress) MarshalJSON

func (p Progress) MarshalJSON() ([]byte, error)

MarshalJSON writes p as versioned deterministic JSON (encoding/json sorts map keys).

func (*Progress) Merge

func (p *Progress) Merge(other Progress) bool

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

func (p *Progress) Record(levelID string, res Result) bool

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

func (p *Progress) RecordWith(m Manifest, levelID string, res Result) bool

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) Stars

func (p Progress) Stars(levelID string) int

Stars returns the best star count recorded for levelID (0 if unplayed).

func (Progress) TotalStars

func (p Progress) TotalStars() int

TotalStars returns the sum of earned stars across the bound manifest (or across all recorded levels if no manifest is bound).

func (Progress) TotalStarsFor

func (p Progress) TotalStarsFor(m Manifest) int

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

func (p *Progress) UnmarshalJSON(data []byte) error

UnmarshalJSON strictly decodes versioned Progress JSON, refusing unknown fields, trailing tokens, and out-of-range values while preserving unknown level IDs.

func (Progress) Validate

func (p Progress) Validate() error

Validate checks that p holds a supported version, trimmed level IDs, 0–3 star counts, finite values, and valid metric directions.

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.

Jump to

Keyboard shortcuts

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