save

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 19 Imported by: 5 modules, 4 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 save stores a game's save slots as versioned JSON in either the app's key-value storage (core.Storage) or files in a directory such as cx.DataDir.

Each slot holds a {"version": N, "data": ...} envelope; an envelope with any other field, or with a field given twice, is corrupt. When a Store loads a save written by an older version, it runs its registered migrations one version at a time (v to v+1) before unmarshaling into the caller's value; a save from a newer version is refused with ErrFutureVersion rather than read into an older shape.

Writes keep the previous valid save as a backup before replacing the primary copy (with a write, sync and rename on disk, or a backup key in core.Storage), so a failed write leaves the last good save intact and a corrupted primary falls back to the backup on Load.

Player settings (audio, bindings, display, locale, accessibility and custom preferences) are persisted separately via SettingsStore and DefaultSettingsStore outside the save-slot namespace, so deleting or clearing save slots never touches player settings, and LoadAndApply wires loaded settings to game subsystems on startup.

Index

Examples

Constants

View Source
const (

	// MinCaptionScale is the minimum allowed AccessibilitySettings.CaptionScale multiplier.
	MinCaptionScale = 0.5
	// MaxCaptionScale is the maximum allowed AccessibilitySettings.CaptionScale multiplier.
	MaxCaptionScale = 3.0
	// MinGameSpeed is the slowest allowed AccessibilitySettings.GameSpeed multiplier.
	MinGameSpeed = 0.25
	// MaxGameSpeed is the fastest allowed AccessibilitySettings.GameSpeed multiplier.
	MaxGameSpeed = 2.0
	// MaxMinPressMs is the maximum allowed InputAssistSettings.MinPressMs in milliseconds.
	MaxMinPressMs = 2000
	// MaxAcceptDelayMs is the maximum allowed InputAssistSettings.AcceptDelayMs in milliseconds.
	MaxAcceptDelayMs = 2000
)

Variables

View Source
var (
	// ErrNotFound reports that no save exists in the named slot.
	ErrNotFound = errors.New("save: slot not found")
	// ErrInvalidSlot reports that a slot name is empty or unsafe for storage keys or file paths.
	ErrInvalidSlot = errors.New("save: invalid slot name")
	// ErrFutureVersion reports that a save was written by a newer schema version than the store supports.
	ErrFutureVersion = errors.New("save: version newer than supported")
	// ErrMissingMigration reports that a store lacks a migration step needed to bring a save up to its current version.
	ErrMissingMigration = errors.New("save: missing migration")
	// ErrCorrupt reports that a save's stored payload is not a valid save envelope.
	ErrCorrupt = errors.New("save: corrupt data")
)

Functions

func Apply

func Apply(s Settings, targets SettingsTargets) error

Apply validates a copy of s and dispatches its sections to every non-nil target in targets. All non-nil targets are invoked even if an earlier target returns an error; errors are combined with errors.Join.

func EnvelopeVersion

func EnvelopeVersion(payload []byte) (int, bool)

EnvelopeVersion returns the schema version recorded in a save envelope payload, or (0, false) when payload does not carry a positive integer "version" field.

Like Store.Load, it reads a JSON object carrying unknown fields so a save written by a newer build with extra envelope fields still reports its version.

func NormalizeColorBlindMode

func NormalizeColorBlindMode(mode string) string

NormalizeColorBlindMode returns the canonical color-vision mode name for mode, accepting both "none" and "normal" (and empty string) as "none", and normalizing "high-contrast", "highcontrast", and "high_contrast" to "high-contrast". Known names are lowercased; unknown non-empty names are trimmed and preserved.

func ValidateSlot

func ValidateSlot(slot string) error

ValidateSlot reports whether slot is a name a Store accepts, returning an error wrapping ErrInvalidSlot when it is not. Code that takes slot names from outside the game, such as a cloud listing, checks them with it before handing them to a Backend.

Types

type AccessibilitySettings

type AccessibilitySettings struct {
	Captions bool `json:"captions"`
	// SFXCaptions enables captions for non-speech sound effects (footsteps, explosions, directional cues).
	SFXCaptions bool `json:"sfx_captions,omitempty"`
	// CaptionScale is the subtitle/UI text scale factor in [MinCaptionScale, MaxCaptionScale] (1.0 by default).
	// When CaptionScaleSet is false and CaptionScale is 0 or 1.0, EffectiveCaptionScale follows core.Env.FontScale.
	CaptionScale float64 `json:"caption_scale"`
	// CaptionScaleSet reports whether CaptionScale was chosen explicitly (including 1.0) rather than following core.Env.FontScale.
	CaptionScaleSet bool `json:"caption_scale_set,omitempty"`
	// ColorBlindMode is the canonical color-vision mode ("none", "protanopia", "deuteranopia", "tritanopia", or "high-contrast").
	// "normal" is accepted on load and normalized to "none".
	ColorBlindMode string `json:"color_blind_mode,omitempty"`
	ReduceMotion   bool   `json:"reduce_motion"`
	// ReduceMotionSet reports whether ReduceMotion was chosen explicitly (including false) rather than following core.Env.ReduceMotion.
	ReduceMotionSet bool `json:"reduce_motion_set,omitempty"`
	HighContrast    bool `json:"high_contrast"`
	// HighContrastSet reports whether HighContrast was chosen explicitly (including false) rather than following core.Env.IncreaseContrast.
	HighContrastSet bool `json:"high_contrast_set,omitempty"`
	// ReduceFlashes disables full-screen flash effects independently of ReduceMotion.
	ReduceFlashes bool `json:"reduce_flashes,omitempty"`
	// ScreenShake is the camera shake intensity in [0, 1] (1.0 by default, 0 disables shake).
	ScreenShake float64 `json:"screen_shake"`
	// GameSpeed is the gameplay speed multiplier in [MinGameSpeed, MaxGameSpeed] (1.0 by default).
	GameSpeed float64 `json:"game_speed"`
	// Invincibility disables player damage when supported by the game.
	Invincibility bool `json:"invincibility,omitempty"`
	// AutoAim enables aim assistance when supported by the game.
	AutoAim bool `json:"auto_aim,omitempty"`
	// HoldToToggle turns held inputs into toggles when supported by the game.
	HoldToToggle bool `json:"hold_to_toggle,omitempty"`
}

AccessibilitySettings holds player accessibility and gameplay-assist preferences.

func (*AccessibilitySettings) ClearCaptionScale

func (a *AccessibilitySettings) ClearCaptionScale()

ClearCaptionScale clears the explicit scale override so EffectiveCaptionScale follows core.Env.FontScale again.

func (*AccessibilitySettings) ClearHighContrast

func (a *AccessibilitySettings) ClearHighContrast()

ClearHighContrast clears the explicit high-contrast override so EffectiveHighContrast follows the platform setting again.

func (*AccessibilitySettings) ClearReduceMotion

func (a *AccessibilitySettings) ClearReduceMotion()

ClearReduceMotion clears the explicit reduced-motion override so EffectiveReduceMotion follows the platform setting again.

func (AccessibilitySettings) EffectiveCaptionScale

func (a AccessibilitySettings) EffectiveCaptionScale(env *core.Env) float64

EffectiveCaptionScale returns the active text/caption scale factor in [MinCaptionScale, MaxCaptionScale]. When CaptionScaleSet is false and CaptionScale is 0 or 1.0, it adopts env.FontScale (clamped to the valid range) when env is non-nil and reports a positive scale.

func (AccessibilitySettings) EffectiveHighContrast

func (a AccessibilitySettings) EffectiveHighContrast(env *core.Env) bool

EffectiveHighContrast reports whether high contrast is active, using the player's explicit choice when HighContrast or HighContrastSet is true and otherwise falling back to env.IncreaseContrast when env is non-nil.

func (AccessibilitySettings) EffectiveReduceMotion

func (a AccessibilitySettings) EffectiveReduceMotion(env *core.Env) bool

EffectiveReduceMotion reports whether reduced motion is active, using the player's explicit choice when ReduceMotion or ReduceMotionSet is true and otherwise falling back to env.ReduceMotion when env is non-nil.

func (*AccessibilitySettings) SetCaptionScale

func (a *AccessibilitySettings) SetCaptionScale(v float64)

SetCaptionScale clamps v into [MinCaptionScale, MaxCaptionScale] (defaulting NaN/Inf/0 to 1.0) and marks CaptionScaleSet so it overrides core.Env.FontScale even when set to 1.0.

func (*AccessibilitySettings) SetHighContrast

func (a *AccessibilitySettings) SetHighContrast(v bool)

SetHighContrast records an explicit high-contrast preference so it overrides the platform setting even when v is false.

func (*AccessibilitySettings) SetReduceMotion

func (a *AccessibilitySettings) SetReduceMotion(v bool)

SetReduceMotion records an explicit reduced-motion preference so it overrides the platform setting even when v is false.

func (*AccessibilitySettings) Validate

func (a *AccessibilitySettings) Validate()

Validate clamps out-of-range numeric fields and normalizes ColorBlindMode in place.

type AudioSettings

type AudioSettings struct {
	// Master is the overall volume in [0, 1] (1.0 by default).
	Master float64 `json:"master"`
	// Groups maps audio group names (such as "music", "sfx", "ui") to volumes in [0, 1].
	Groups map[string]float64 `json:"groups,omitempty"`
	// Muted silences all audio without discarding the stored Master level.
	Muted bool `json:"muted"`
	// Mono forces positional voices to play centered at pan 0. Nil (the default) follows the
	// platform's mono audio switch (nsgo-dev/nsgo#2677); a non-nil pointer overrides it explicitly.
	Mono *bool `json:"mono,omitempty"`
	// Balance shifts stereo voice panning in [-1, 1] (-1 full left, 0 centered, +1 full right)
	// when mono audio is off.
	Balance float64 `json:"balance,omitempty"`
}

AudioSettings holds player audio preferences stored independently of save slots.

func (AudioSettings) ResolveMono

func (a AudioSettings) ResolveMono(systemMono bool) bool

ResolveMono returns the effective mono setting given the platform's mono audio switch: *a.Mono when explicitly set, and systemMono when a.Mono is nil.

func (*AudioSettings) UnmarshalJSON

func (a *AudioSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes AudioSettings while preserving defaults for omitted fields and replacing Groups cleanly when "groups" is explicitly present in JSON.

type Backend

type Backend interface {
	// Read returns the primary payload for slot, or an error wrapping ErrNotFound if absent.
	Read(slot string) ([]byte, error)
	// ReadBackup returns the previous valid payload kept as a backup for slot, or an error wrapping ErrNotFound if absent.
	ReadBackup(slot string) ([]byte, error)
	// Write saves data as the primary payload for slot, preserving any existing valid primary as the backup first.
	Write(slot string, data []byte) error
	// Delete removes both primary and backup payloads for slot, the backup first so an interrupted Delete never leaves a backup that resurrects the slot. Deleting an absent slot returns nil.
	Delete(slot string) error
	// Exists reports whether a primary or backup payload exists for slot.
	Exists(slot string) bool
	// Slots returns the sorted names of all slots that have a primary or backup payload.
	Slots() ([]string, error)
}

Backend stores and retrieves raw save payloads and their backup copies by validated slot name.

A Backend that wraps another, such as one that records each write, can expose it with an Unwrap() Backend method. A SettingsStore built on the wrapper then keeps settings exactly where it would on the wrapped backend, without passing them through the wrapper.

func FileBackend

func FileBackend(dir string) Backend

FileBackend returns a Backend that keeps each slot as <slot>.json and its backup as <slot>.json.bak inside dir (such as cx.DataDir()).

Writes stage data into a synced temporary file in dir, preserve any existing valid primary in <slot>.json.bak, atomically rename the temporary file into place and sync the directory, reporting a failed directory sync as a write error. The first Write removes .save-*.tmp files that an interrupted write left more than an hour ago. On the web, where Scope.DataDir is empty, use StorageBackend instead.

func StorageBackend

func StorageBackend(store core.Storage, prefix string) Backend

StorageBackend returns a Backend that keeps saves in store under keys starting with prefix.

Each slot uses a primary key (<prefix>.slot.<slot>) and a backup key (<prefix>.bak.<slot>), so backup keys never collide with slot names and a failed SetItem (such as *core.StorageFullError) leaves the previous save intact.

type DefaultSettingsStore

type DefaultSettingsStore struct {
	*SettingsStore[Settings]
}

DefaultSettingsStore is a convenience SettingsStore for the standard Settings struct with startup Apply support.

func NewDefaultSettingsStore

func NewDefaultSettingsStore(backend Backend, opts ...SettingsOption) *DefaultSettingsStore

NewDefaultSettingsStore returns a DefaultSettingsStore backed by backend.

func NewFileSettingsStore

func NewFileSettingsStore(dir string, opts ...SettingsOption) *DefaultSettingsStore

NewFileSettingsStore returns a DefaultSettingsStore backed by settings.json (and settings.json.bak) inside dir.

func NewStorageSettingsStore

func NewStorageSettingsStore(store core.Storage, prefix string, opts ...SettingsOption) *DefaultSettingsStore

NewStorageSettingsStore returns a DefaultSettingsStore backed by store under <prefix>.settings (outside the slot namespace).

func (*DefaultSettingsStore) LoadAndApply

func (s *DefaultSettingsStore) LoadAndApply(targets SettingsTargets) (Settings, error)

LoadAndApply loads settings (returning DefaultSettings when absent) and applies them to targets. If Load fails, targets are not called. If Apply fails, the loaded settings are still returned alongside the error.

type DisplaySettings

type DisplaySettings struct {
	// Fullscreen puts the window in full screen on the chosen display, as the platform provides it (on macOS, native full screen in its own Space; on the web, the browser's full screen, granted only during a user gesture); false keeps it windowed.
	Fullscreen bool `json:"fullscreen"`
	// DisplayID is the ID, from core.Env.Displays, of the display full screen uses. It names a display the same way across launches and display changes, so a UI that offers displays sets it; when it is empty or the display is not connected, DisplayIndex chooses instead.
	DisplayID string `json:"display_id,omitempty"`
	// DisplayIndex is the position in core.Env.Displays of the display full screen uses when DisplayID is empty or not connected; out of range keeps the window's current display.
	DisplayIndex int    `json:"display_index"`
	ScaleMode    string `json:"scale_mode,omitempty"`
	IntegerScale bool   `json:"integer_scale"`
	// FrameCap is the most frames drawn a second, uncapped when 0.
	FrameCap int `json:"frame_cap"`
	// VSync requests vertical sync. NSGo v0.3.4 does not yet expose swap-interval control, so screen.Video does not apply this field and gameui.SettingsMenu hides the toggle by default.
	VSync bool `json:"vsync"`
	// AutoDropLowPower lowers the frame cap while the system is in low-power mode or under serious thermal pressure, and restores it once the condition clears.
	AutoDropLowPower bool `json:"auto_drop_low_power"`
	// Quality is the player's quality setting as quality.NormalizeSetting writes it: "auto" (the default) lets quality.Selector choose from the device and its frame times, and "low", "medium" or "high" holds that preset.
	Quality string `json:"quality,omitempty"`
}

DisplaySettings holds player display and presentation preferences.

type InputAssistSettings

type InputAssistSettings struct {
	// Toggle lists action names that latch on the first accepted press and release on the next.
	Toggle []string `json:"toggle,omitempty"`
	// MashToHold lists action names whose rapid-press mechanics count a single hold as repeated presses.
	MashToHold []string `json:"mash_to_hold,omitempty"`
	// MinPressMs is the minimum hold duration in milliseconds before a press counts (slow keys); 0 disables it.
	MinPressMs int `json:"min_press_ms,omitempty"`
	// AcceptDelayMs is the post-acceptance cooldown in milliseconds during which further presses of the same action are ignored (bounce keys); 0 disables it.
	AcceptDelayMs int `json:"accept_delay_ms,omitempty"`
}

InputAssistSettings holds player-chosen motor accessibility assists persisted alongside Bindings.

func (InputAssistSettings) AcceptDelay

func (a InputAssistSettings) AcceptDelay() time.Duration

AcceptDelay returns AcceptDelayMs as a time.Duration (0 when non-positive).

func (InputAssistSettings) IsZero

func (a InputAssistSettings) IsZero() bool

IsZero reports whether a enables no input motor assists.

func (InputAssistSettings) MinPress

func (a InputAssistSettings) MinPress() time.Duration

MinPress returns MinPressMs as a time.Duration (0 when non-positive).

func (*InputAssistSettings) SetAcceptDelay

func (a *InputAssistSettings) SetAcceptDelay(d time.Duration)

SetAcceptDelay stores d in AcceptDelayMs, clamped to [0, MaxAcceptDelayMs].

func (*InputAssistSettings) SetMinPress

func (a *InputAssistSettings) SetMinPress(d time.Duration)

SetMinPress stores d in MinPressMs, clamped to [0, MaxMinPressMs].

func (*InputAssistSettings) Validate

func (a *InputAssistSettings) Validate()

Validate normalizes action name lists (trimmed, unique, sorted) and clamps millisecond timings in place.

type Migration

type Migration func(data json.RawMessage) (json.RawMessage, error)

Migration converts a save's raw JSON data from one schema version to the next (v to v+1).

type Option

type Option func(*Store)

Option configures a Store returned by NewStore, NewStorageStore or NewFileStore.

func WithMigration

func WithMigration(from int, fn Migration) Option

WithMigration registers fn to migrate a save's JSON data from version from to from+1.

Example

A migration upgrades a save written by an older version of the game before it is read, one version at a time.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/nsgo-dev/game/pkg/save"
	"github.com/nsgo-dev/nsgo/core"
)

type progress struct {
	Level int `json:"level"`
	Coins int `json:"coins"`
}

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	// Version 1 of the game stored only the level.
	old := save.NewStorageStore(root.Storage(), "saves")
	old.Save("slot1", map[string]int{"level": 2})

	// Version 2 adds coins and gives old saves a starting amount.
	store := save.NewStorageStore(root.Storage(), "saves",
		save.WithVersion(2),
		save.WithMigration(1, func(data json.RawMessage) (json.RawMessage, error) {
			var v map[string]any
			if err := json.Unmarshal(data, &v); err != nil {
				return nil, err
			}
			v["coins"] = 50
			return json.Marshal(v)
		}),
	)
	var p progress
	fmt.Println(store.Load("slot1", &p), p)
}
Output:
<nil> {2 50}

func WithMigrations

func WithMigrations(m map[int]Migration) Option

WithMigrations registers each migration in m, keyed by its starting version (from to from+1).

func WithVersion

func WithVersion(v int) Option

WithVersion sets the store's current save schema version. Versions below 1 are treated as 1.

type Settings

type Settings struct {
	Audio         AudioSettings              `json:"audio"`
	Bindings      map[string][]string        `json:"bindings,omitempty"`
	InputAssists  InputAssistSettings        `json:"input_assists,omitzero"`
	Display       DisplaySettings            `json:"display"`
	Locale        string                     `json:"locale,omitempty"`
	Accessibility AccessibilitySettings      `json:"accessibility"`
	Custom        map[string]json.RawMessage `json:"custom,omitempty"`
}

Settings holds typed, versioned player preferences kept completely separate from save slots.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns a Settings populated with sane defaults.

func (*Settings) Validate

func (s *Settings) Validate()

Validate clamps out-of-range numeric fields and normalizes empty/whitespace strings in place.

type SettingsOption

type SettingsOption func(*settingsConfig)

SettingsOption configures a SettingsStore or DefaultSettingsStore.

func WithSettingsMigration

func WithSettingsMigration(from int, fn Migration) SettingsOption

WithSettingsMigration registers fn to migrate settings JSON data from version from to from+1.

func WithSettingsMigrations

func WithSettingsMigrations(m map[int]Migration) SettingsOption

WithSettingsMigrations registers each migration in m, keyed by its starting version (from to from+1).

func WithSettingsSchema

func WithSettingsSchema(schema SettingsSchema) SettingsOption

WithSettingsSchema applies schema's Version and Migrations to a settings store.

func WithSettingsVersion

func WithSettingsVersion(v int) SettingsOption

WithSettingsVersion sets the settings store's current schema version. Versions below 1 are treated as 1.

type SettingsSchema

type SettingsSchema struct {
	// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
	Migrations map[int]Migration
}

SettingsSchema describes the version and step-by-step migrations for a SettingsStore.

type SettingsStore

type SettingsStore[T any] struct {
	// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
	Migrations map[int]Migration
	// contains filtered or unexported fields
}

SettingsStore persists a versioned settings value of type T in a dedicated settings file or storage key, completely separate from save slots.

Example

A SettingsStore keeps player settings apart from save slots and fills in defaults when none were saved.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/save"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	settings := save.NewStorageSettingsStore(root.Storage(), "settings")
	s, err := settings.Load()
	fmt.Println(err, s.Audio.Master, s.Audio.Muted)
	s.Audio.Master = 0.4
	s.Locale = "ja"
	if err := settings.Save(s); err != nil {
		fmt.Println(err)
		return
	}
	again, _ := settings.Load()
	fmt.Println(again.Audio.Master, again.Locale)
}
Output:
<nil> 1 false
0.4 ja

func NewSettingsStore

func NewSettingsStore[T any](backend Backend, defaults func() T, opts ...SettingsOption) *SettingsStore[T]

NewSettingsStore returns a SettingsStore for T backed by backend.

defaults supplies the baseline value returned when no settings exist yet, used as the base when unmarshaling partial JSON, and written on Reset. When defaults is nil, DefaultSettings() is used if T is Settings, otherwise the zero value of T.

func (*SettingsStore[T]) Delete

func (s *SettingsStore[T]) Delete() error

Delete removes the stored settings and its backup copy. Deleting absent settings returns nil.

func (*SettingsStore[T]) Exists

func (s *SettingsStore[T]) Exists() bool

Exists reports whether a primary or backup settings payload exists.

func (*SettingsStore[T]) Load

func (s *SettingsStore[T]) Load() (T, error)

Load reads settings, migrating older versions up to s.Version one step at a time and validating the result.

If no settings have been saved yet, Load returns the store's default value and a nil error. If the primary copy is missing, unreadable or corrupted, Load recovers from the backup copy. Settings from a newer schema version return ErrFutureVersion without falling back to an older backup.

func (*SettingsStore[T]) RegisterMigration

func (s *SettingsStore[T]) RegisterMigration(from int, fn Migration)

RegisterMigration registers fn to upgrade settings JSON data from version from to from+1.

func (*SettingsStore[T]) Reset

func (s *SettingsStore[T]) Reset() error

Reset restores and saves the store's default settings.

func (*SettingsStore[T]) Save

func (s *SettingsStore[T]) Save(value T) error

Save validates value (if T implements Validate()), encodes it into a versioned JSON envelope, and writes it atomically while keeping the previous valid copy as a backup.

func (*SettingsStore[T]) Subscribe

func (s *SettingsStore[T]) Subscribe(fn func()) func()

Subscribe registers fn to run whenever Save, Reset, or Delete succeeds on s. Call the returned function to remove the subscription. A nil fn is a no-op.

type SettingsTargets

type SettingsTargets struct {
	// Sound receives master volume, group volumes, mono mode, and left/right balance from Settings.Audio.
	// When Settings.Audio.Muted is true, the mixer's master volume is set to 0.
	Sound *sound.Mixer

	// SetMasterVolume receives the effective master volume (0 when Muted is true) in [0, 1].
	SetMasterVolume func(volume float64)

	// SetGroupVolume receives each audio group name and volume from Settings.Audio.Groups in sorted key order.
	SetGroupVolume func(group string, volume float64)

	// ApplyAudio receives the validated AudioSettings.
	ApplyAudio func(AudioSettings) error

	// ApplyBindings receives a cloned map of action bindings.
	ApplyBindings func(map[string][]string) error

	// ApplyInputAssists receives the validated InputAssistSettings.
	ApplyInputAssists func(InputAssistSettings) error

	// ApplyDisplay receives the validated DisplaySettings.
	ApplyDisplay func(DisplaySettings) error

	// ApplyLocale receives the validated Locale string.
	ApplyLocale func(locale string) error

	// ApplyAccessibility receives the validated AccessibilitySettings.
	ApplyAccessibility func(AccessibilitySettings) error
}

SettingsTargets wires subsystems to receive loaded player settings at startup or when settings change. Every field is optional; nil targets are skipped.

type Store

type Store struct {
	// Version is the current save schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades a save's JSON data from v to v+1.
	Migrations map[int]Migration
	// contains filtered or unexported fields
}

Store saves and loads versioned JSON game state across named slots backed by a Backend.

Example

A Store saves values in named slots as versioned JSON; here in the app's key-value storage, as a web or mobile build does.

package main

import (
	"errors"
	"fmt"

	"github.com/nsgo-dev/game/pkg/save"
	"github.com/nsgo-dev/nsgo/core"
)

type progress struct {
	Level int `json:"level"`
	Coins int `json:"coins"`
}

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	store := save.NewStorageStore(root.Storage(), "saves")
	if err := store.Save("slot1", progress{Level: 3, Coins: 120}); err != nil {
		fmt.Println(err)
		return
	}
	var p progress
	fmt.Println(store.Load("slot1", &p), p)
	slots, _ := store.Slots()
	fmt.Println(slots, errors.Is(store.Load("slot2", &p), save.ErrNotFound))
}
Output:
<nil> {3 120}
[slot1] true

func NewFileStore

func NewFileStore(dir string, opts ...Option) *Store

NewFileStore returns a Store backed by JSON files inside dir (such as cx.DataDir()).

func NewStorageStore

func NewStorageStore(store core.Storage, prefix string, opts ...Option) *Store

NewStorageStore returns a Store backed by store under keys starting with prefix.

func NewStore

func NewStore(backend Backend, opts ...Option) *Store

NewStore returns a Store backed by backend, defaulting to Version 1 before applying opts.

func (*Store) Delete

func (s *Store) Delete(slot string) error

Delete removes slot and its backup copy. Deleting a slot that does not exist returns nil. The backup goes first, so an interrupted Delete leaves either the whole slot or nothing that Load could resurrect.

func (*Store) DeleteAll

func (s *Store) DeleteAll() error

DeleteAll removes every save slot and its backup copy. Player settings stored alongside save slots are never touched.

func (*Store) Exists

func (s *Store) Exists(slot string) bool

Exists reports whether slot has a stored save or backup copy.

func (*Store) Load

func (s *Store) Load(slot string, dst any) error

Load reads slot, migrates older save versions up to s.Version one step at a time, and unmarshals the data into dst.

If the primary copy is missing, unreadable or corrupted, Load automatically recovers from the slot's backup copy. It rewrites the primary from that backup only when the primary is missing or is not a JSON object at all (empty, truncated or garbage); a primary that failed to read for another reason, or that is a JSON object Load cannot use, is left as it is, because it may be newer than the backup. A save whose version exceeds s.Version returns an error wrapping ErrFutureVersion without falling back to an older backup, even when its envelope has fields this build does not know.

Load never writes a migrated save back: migrations run in memory on every Load until the slot is saved again, so each Migration must be a pure function of its input that gives the same result every time it runs.

An error about a copy's contents is a *loaderr.Error that names the copy, the line in the stored JSON and a fix. FileBackend names it by its file path (<dir>/<slot>.json, or <dir>/<slot>.json.bak for the backup) and StorageBackend by its storage key; another Backend by the slot, with " (backup)" for its backup copy.

func (*Store) LoadChecked

func (s *Store) LoadChecked(slot string, dst any, check func() error) error

LoadChecked is Load with a check of the decoded value: after a copy decodes into dst, LoadChecked calls check, and a copy check refuses is treated as corrupted, so the backup is tried as it would be for one that does not decode.

Before the backup is decoded, and when LoadChecked returns an error, dst is put back to the value it had when LoadChecked was called, so nothing of a refused copy is left in it.

When check returns a *loaderr.Error whose Field is a path in dst's JSON, the error LoadChecked returns gives that field's line in the stored copy, under "data". A nil check checks nothing.

func (*Store) RegisterMigration

func (s *Store) RegisterMigration(from int, fn Migration)

RegisterMigration registers fn to upgrade a save's JSON data from version from to from+1.

func (*Store) Save

func (s *Store) Save(slot string, value any) error

Save encodes value into a versioned JSON envelope and writes it to slot.

Marshaling happens before the backend is touched, so an encoding error leaves any previous save in slot untouched.

func (*Store) Slots

func (s *Store) Slots() ([]string, error)

Slots returns the sorted names of all slots stored in the backend.

Jump to

Keyboard shortcuts

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