La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package quest
import "github.com/nsgo-dev/game/pkg/quest"Vue d’ensemble
Package quest runs quests with objectives (collect, reach, defeat, talk), quest states and rewards, defined in a versioned YAML Book and advanced by game events.
A Book is the text file a designer writes: each Quest lists its objectives, the quests it requires, whether its objectives run in order, and the rewards it grants. Parse refuses unknown fields and checks references and prerequisite cycles; Encode writes deterministic YAML that parses back to the same Book.
A Log tracks one player's progress through a Book. Events (Collected, Reached, Defeated, Talked, or a plain Event) advance the objectives of active quests whose kind and target match; Attach wires a Log to a flow.Bus so those events can be published from anywhere in a game, and every change is reported as an Update. Snapshot and Restore turn a Log's progress into a JSON-friendly value that round-trips through save.Store.
Nothing in quest reads the wall clock, spawns goroutines or keeps package-level state, so a Log stays deterministic under nsgotest and replays.
Index
- Constantes
- Variables
- func Encode(b *Book) ([]byte, error)
- func Validate(b *Book) error
- type Book
- type Collected
- type Defeated
- type Event
- type Kind
- type Log
- func NewLog(book *Book) (*Log, error)
- func (l *Log) Abandon(id string) error
- func (l *Log) Attach(bus *flow.Bus) (detach func())
- func (l *Log) Book() *Book
- func (l *Log) CanStart(id string) bool
- func (l *Log) Fail(id string) error
- func (l *Log) Handle(e Event) bool
- func (l *Log) Objective(questID, objectiveID string) (status ObjectiveStatus, ok bool)
- func (l *Log) Objectives(id string) []ObjectiveStatus
- func (l *Log) Quests(s State) []string
- func (l *Log) Restore(s Snapshot) error
- func (l *Log) SetProgress(questID, objectiveID string, n int) error
- func (l *Log) Snapshot() Snapshot
- func (l *Log) Start(id string) error
- func (l *Log) StartReady() int
- func (l *Log) State(id string) State
- type Objective
- type ObjectiveState
- type ObjectiveStatus
- type Quest
- type QuestRecord
- type Reached
- type Reward
- type Snapshot
- type State
- type Talked
- type Update
- type UpdateKind
Constantes
const FormatVersion = 1FormatVersion is the quest book schema version this package reads and writes.
const SnapshotVersion = 1SnapshotVersion is the Snapshot schema version this package writes and reads.
Variables
var (
// ErrUnknownQuest reports a quest ID the Log's book does not define.
ErrUnknownQuest = errors.New("quest: unknown quest")
// ErrUnknownObjective reports an objective ID the quest does not define.
ErrUnknownObjective = errors.New("quest: unknown objective")
// ErrNotStartable reports that a quest cannot start: its prerequisites are incomplete, it is already active, or it completed and is not repeatable.
ErrNotStartable = errors.New("quest: quest cannot start")
// ErrNotActive reports an operation that needs an active quest (or an active objective) on one that is not.
ErrNotActive = errors.New("quest: quest is not active")
)var ErrInvalidBook = errors.New("quest: invalid book")ErrInvalidBook reports that a quest book breaks the schema: a wrong version, a missing or duplicate ID, an unknown objective kind or reference, a negative count, or a prerequisite cycle.
var ErrInvalidSnapshot = errors.New("quest: invalid snapshot")ErrInvalidSnapshot reports a Snapshot that Restore refuses: a wrong version, an unknown or duplicate quest or objective, progress outside an objective's range, or a combination of states and progress that a Log cannot reach.
Fonctions
func Encode(b *Book) ([]byte, error)Encode validates b and writes it in canonical form: deterministic YAML with 2-space indentation, fields in declaration order, `requires` in flow style and everything else in block style, empty lists and zero values omitted, and no generated values. Parse(Encode(b)) equals b for a book from Parse, and Encode(Parse(f)) gives back f byte for byte when f is already canonical. A file that is not canonical comes back in canonical form, and YAML comments are not kept.
func Validate(b *Book) errorValidate checks b against the schema: the version, unique non-empty IDs, known objective kinds with targets, non-negative counts and amounts, prerequisites that name other quests in the book, and no prerequisite cycles. Errors wrap ErrInvalidBook.
Types
type Book struct {
// Version is the schema version; it must equal FormatVersion.
Version int `yaml:"version"`
// Quests lists the book's quests; Log reports them in this order.
Quests []Quest `yaml:"quests,omitempty"`
}Book is the root of a versioned YAML quest file.
func LoadFS(fsys fs.FS, name string) (*Book, error)LoadFS reads and parses the quest book at name in fsys.
func Parse(data []byte) (*Book, error)Parse decodes a YAML quest book and validates it. Unknown fields and trailing YAML documents are refused. An empty list, such as `requires: []`, decodes the same as an omitted one (nil), so a parsed book equals Parse(Encode(book)).
func (b *Book) Quest(id string) *QuestQuest returns the quest with the given ID, or nil when b has none.
type Collected struct {
Item string
Amount int
}Collected reports that the player picked up Amount of Item (below 1 counts as 1). It advances collect objectives whose target is Item.
type Defeated struct {
Enemy string
Amount int
}Defeated reports that the player defeated Amount of Enemy (below 1 counts as 1). It advances defeat objectives whose target is Enemy.
type Event struct {
Kind Kind
Target string
Amount int
}Event is a game event an objective can count: Kind and Target must match the objective's, and Amount below 1 counts as 1. Collected, Reached, Defeated and Talked are typed shorthands for it.
type Kind stringKind is what an objective asks the player to do.
const (
// KindCollect counts items picked up, matched by item ID (Collected events).
KindCollect Kind = "collect"
// KindReach completes when the player arrives at a place, matched by place ID (Reached events).
KindReach Kind = "reach"
// KindDefeat counts enemies defeated, matched by enemy ID (Defeated events).
KindDefeat Kind = "defeat"
// KindTalk completes when the player talks to a character, matched by character ID (Talked events).
KindTalk Kind = "talk"
)func (k Kind) Valid() boolValid reports whether k is one of KindCollect, KindReach, KindDefeat or KindTalk.
type Log struct {
// OnUpdate, when set, receives every Update in the order the changes happened.
OnUpdate func(Update)
// contains filtered or unexported fields
}Log tracks one player's progress through a Book. Create it with NewLog.
A Log is not safe for concurrent use; drive it from the game loop. Its methods may be called from OnUpdate and bus handlers: updates raised by such nested calls are delivered after the current ones, in order.
func NewLog(book *Book) (*Log, error)NewLog validates book and returns a Log with every quest Inactive. The Log keeps its own copy of book, so later changes to book do not affect it.
func (l *Log) Abandon(id string) errorAbandon marks an active quest Abandoned and drops its progress. An abandoned quest stays abandoned, through StartReady and through a save, until Start begins it again.
func (l *Log) Attach(bus *flow.Bus) (detach func())Attach subscribes l to Event, Collected, Reached, Defeated and Talked events published on bus, and publishes every Update on bus as well as delivering it to OnUpdate. Attaching again replaces the previous bus. The returned function detaches l and is idempotent.
func (l *Log) CanStart(id string) boolCanStart reports whether Start(id) would succeed.
func (l *Log) Fail(id string) errorFail marks an active quest Failed, keeping its progress for display until it starts again.
func (l *Log) Handle(e Event) boolHandle advances every active objective whose kind and target match e by e.Amount (below 1 counts as 1), completing objectives and quests that reach their counts, and reports whether anything changed. In an ordered quest, an event that completes one objective does not also count toward the next.
func (l *Log) Objective(questID, objectiveID string) (status ObjectiveStatus, ok bool)Objective returns the status of one objective; ok is false when the quest or objective is unknown.
func (l *Log) Objectives(id string) []ObjectiveStatusObjectives returns the status of each of the quest's objectives in definition order, or nil for an unknown ID.
func (l *Log) Quests(s State) []stringQuests returns the IDs of the quests in state s, in book order.
func (l *Log) Restore(s Snapshot) errorRestore replaces l's progress with s, which must come from a Log running the same book. It checks s first and leaves l unchanged when s is invalid (errors wrap ErrInvalidSnapshot). Restore delivers no updates and starts no quests; call StartReady afterwards if the book has auto-start quests.
Besides IDs and ranges, Restore refuses progress a Log cannot reach: a recorded quest whose prerequisite is unrecorded, or is not Completed when it is not Repeatable (a completed prerequisite stays completed unless it repeats); an abandoned quest with progress; progress on an objective of an ordered quest while an earlier required objective is incomplete; and an active quest whose required objectives are all complete.
The zero Snapshot (version 0 and no quests) means no progress: Restore resets every quest to Inactive. That is what a save slot written before the game tracked quests decodes to.
A snapshot written before a content change that removes a quest or objective, lowers a count, adds a prerequisite, or turns objectives optional so an active quest would already be complete is refused; migrate it with a save.Migration.
func (l *Log) SetProgress(questID, objectiveID string, n int) errorSetProgress sets an active objective's progress to n, clamped to [0, Required], completing it and its quest when n reaches the count. Use it to mirror a value the game already tracks, such as how many of an item the inventory holds. It fails with ErrNotActive when the quest is not active or the objective is locked or already completed.
func (l *Log) Snapshot() SnapshotSnapshot returns l's progress. It shares no memory with l.
func (l *Log) Start(id string) errorStart makes the quest active with no progress. It fails with ErrNotStartable while a prerequisite is incomplete, while the quest is active, or after it completed unless it is Repeatable; a failed or abandoned quest can start again.
func (l *Log) StartReady() intStartReady starts every AutoStart quest that is Inactive (never started, so not Failed or Abandoned) and whose prerequisites are complete, in book order, and returns how many started. A Log calls it after every quest completion; call it yourself once after NewLog or Restore so quests with no prerequisites begin.
func (l *Log) State(id string) StateState returns the quest's state; an unknown ID reports Inactive.
type Objective struct {
// ID uniquely identifies the objective within its quest and in saves.
ID string `yaml:"id"`
// Kind is what the objective asks for.
Kind Kind `yaml:"kind"`
// Target is the item, place, enemy or character ID that events must name to advance the objective.
Target string `yaml:"target"`
// Count is how many matching events (or how much collected) complete the objective; 0 means 1.
Count int `yaml:"count,omitempty"`
// Optional objectives never block the quest's completion or, in an ordered quest, later objectives.
Optional bool `yaml:"optional,omitempty"`
// Text is the objective's journal line or a localization key; the package does not interpret it.
Text string `yaml:"text,omitempty"`
}Objective is one goal of a quest.
func (o Objective) Required() intRequired returns how many units complete o: Count, or 1 when Count is 0.
type ObjectiveState uint8ObjectiveState is where an objective stands within its quest.
const (
// ObjectiveLocked objectives ignore events: their quest is not active, or in an ordered quest an earlier required objective is incomplete.
ObjectiveLocked ObjectiveState = iota
// ObjectiveActive objectives accept matching events.
ObjectiveActive
// ObjectiveDone objectives reached their required count.
ObjectiveDone
)func (s ObjectiveState) String() stringString returns the objective state's lowercase name, such as "locked".
type ObjectiveStatus struct {
// ID, Kind, Target, Optional and Text repeat the objective's definition.
ID string
Kind Kind
Target string
Optional bool
Text string
// Progress is how many units have been counted, from 0 to Required.
Progress int
// Required is how many units complete the objective.
Required int
// State is whether the objective is locked, active or done.
State ObjectiveState
}ObjectiveStatus is a read-only view of one objective's progress.
type Quest struct {
// ID uniquely identifies the quest within the book and in saves.
ID string `yaml:"id"`
// Title is the quest's display name or a localization key; the package does not interpret it.
Title string `yaml:"title,omitempty"`
// Description is the quest's journal text or a localization key; the package does not interpret it.
Description string `yaml:"description,omitempty"`
// Requires lists the IDs of quests that must be completed before this one can start.
Requires []string `yaml:"requires,omitempty,flow"`
// AutoStart starts the quest as soon as its prerequisites are complete, on Log.StartReady and after every quest completion.
AutoStart bool `yaml:"autoStart,omitempty"`
// Repeatable lets Log.Start begin the quest again after it completed.
Repeatable bool `yaml:"repeatable,omitempty"`
// Ordered makes objectives advance one at a time in list order: an objective accepts events only once every required objective before it is complete.
Ordered bool `yaml:"ordered,omitempty"`
// Objectives are the quest's goals; the quest completes when every non-optional one is complete. At least one is required.
Objectives []Objective `yaml:"objectives"`
// Rewards are reported in the QuestCompleted update for the game to grant.
Rewards []Reward `yaml:"rewards,omitempty"`
}Quest is one quest: its objectives, prerequisites and rewards.
type QuestRecord struct {
// ID is the quest's ID.
ID string `json:"id" yaml:"id"`
// State is Active, Completed, Failed or Abandoned.
State State `json:"state" yaml:"state"`
// Progress maps objective IDs to their progress; objectives with no progress are left out.
Progress map[string]int `json:"progress,omitempty" yaml:"progress,omitempty"`
}QuestRecord is one quest's state and objective progress in a Snapshot.
type Reached struct {
Place string
}Reached reports that the player arrived at Place. It advances reach objectives whose target is Place.
type Reward struct {
// Kind optionally groups rewards for the game, such as "item", "xp" or "gold"; the package does not interpret it.
Kind string `yaml:"kind,omitempty"`
// ID names the rewarded thing.
ID string `yaml:"id"`
// Amount is how many are granted; 0 means 1.
Amount int `yaml:"amount,omitempty"`
}Reward is something a completed quest grants. The package reports rewards and never grants them, so they can name inventory items, stats, currency or anything else a game defines.
func (r Reward) Quantity() intQuantity returns how many r grants: Amount, or 1 when Amount is 0.
type Snapshot struct {
// Version is SnapshotVersion.
Version int `json:"version" yaml:"version"`
// Quests holds every quest that is not Inactive, in book order.
Quests []QuestRecord `json:"quests,omitempty" yaml:"quests,omitempty"`
}Snapshot is a Log's progress as plain data that encodes to stable JSON or YAML, for storing in a save slot with save.Store.
type State uint8State is where a quest stands in a Log.
const (
// Inactive quests have not started.
Inactive State = iota
// Active quests accept events for their objectives.
Active
// Completed quests finished every required objective.
Completed
// Failed quests were failed by the game with Log.Fail; Start can retry them.
Failed
// Abandoned quests were dropped by the player with Log.Abandon. Auto-start never restarts them; Start can.
Abandoned
)func (s State) MarshalText() ([]byte, error)MarshalText encodes s as its name, so saves read "active" rather than a number.
func (s State) String() stringString returns the state's lowercase name, such as "active".
func (s *State) UnmarshalText(text []byte) errorUnmarshalText decodes a state name written by MarshalText.
type Talked struct {
Character string
}Talked reports that the player talked to Character. It advances talk objectives whose target is Character.
type Update struct {
// Kind says what changed.
Kind UpdateKind
// Quest is the quest's ID.
Quest string
// Objective is the objective's ID for ObjectiveProgressed and ObjectiveCompleted, and empty otherwise.
Objective string
// Progress and Required are the objective's progress after the change, for ObjectiveProgressed and ObjectiveCompleted.
Progress int
Required int
// Rewards is a copy of the quest's rewards for QuestCompleted, and nil otherwise.
Rewards []Reward
}Update reports one change in a Log. A Log delivers updates to OnUpdate and, while attached, publishes them on its flow.Bus.
type UpdateKind uint8UpdateKind says what changed in an Update.
const (
// QuestStarted reports that a quest became active, from Start or an auto-start.
QuestStarted UpdateKind = iota + 1
// ObjectiveProgressed reports that an objective's progress changed.
ObjectiveProgressed
// ObjectiveCompleted reports that an objective reached its required count.
ObjectiveCompleted
// QuestCompleted reports that a quest completed; Update.Rewards holds what the game should grant.
QuestCompleted
// QuestFailed reports that a quest failed through Log.Fail.
QuestFailed
// QuestAbandoned reports that an active quest became Abandoned through Log.Abandon.
QuestAbandoned
)func (k UpdateKind) String() stringString returns the update kind's name, such as "questCompleted".