Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package inventory
import "github.com/nsgo-dev/game/pkg/inventory"Обзор
Package inventory holds gameplay items: item definitions read from versioned YAML, slot-based containers of item stacks, typed equipment slots, and snapshots that round-trip through a game/save Store.
Item definitions
A Catalog is the set of ItemDef values a game knows, parsed from a version 1 YAML document with Parse (unknown fields, duplicate IDs and trailing documents are refused) or built in code with NewCatalog. Catalog.Encode writes deterministic 2-space YAML that Parse reads back unchanged. Each definition names its maximum stack size (1 when omitted), the equipment kind it fits, if any, and free-form tags and numeric stats.
Containers
A Container is a fixed number of slots, each empty or holding one Stack of a single item no larger than that item's maximum stack. Add tops up existing stacks of the item in slot order before filling empty slots in slot order, and returns what did not fit; AddAll adds everything or nothing. Remove takes items from the last matching slot backwards. MoveTo moves a whole stack into an empty slot, merges it into a stack of the same item as far as that stack has room, or swaps it with a different item; SplitTo moves part of a stack; Transfer quick-moves a stack into another container. Every operation that returns an error leaves both containers unchanged.
Equipment
Equipment is a set of named slots, each accepting items whose ItemDef.Equip equals the slot's kind (two "ring" slots can share one kind). Equip takes one item from a container slot and returns the item it replaces to the container; Unequip returns the equipped item to a container. Both are all-or-nothing.
Saving
Container.Snapshot and Equipment.Snapshot return plain JSON-tagged values to store in a save slot alongside the rest of a game's state; Restore validates a snapshot against the catalog (unknown items, oversized stacks, out-of-range slots and wrong equipment kinds are refused) before replacing anything.
Nothing in inventory reads the clock, spawns goroutines or keeps package-level state, so it is deterministic and safe to run on a headless server. A Container or Equipment is not safe for concurrent use.
Указатель
- Константы
- Переменные
- type Catalog
- type Container
- func NewContainer(catalog *Catalog, size int) (*Container, error)
- func (c *Container) Add(item string, count int) (remaining int, err error)
- func (c *Container) AddAll(item string, count int) error
- func (c *Container) Catalog() *Catalog
- func (c *Container) Clear()
- func (c *Container) Count(item string) int
- func (c *Container) IsEmpty() bool
- func (c *Container) Len() int
- func (c *Container) Move(from, to int) error
- func (c *Container) MoveTo(from int, dst *Container, to int) error
- func (c *Container) Remove(item string, count int) error
- func (c *Container) RemoveAt(i, count int) (Stack, error)
- func (c *Container) Restore(st ContainerState) error
- func (c *Container) Room(item string) int
- func (c *Container) Slot(i int) Stack
- func (c *Container) Slots() []Stack
- func (c *Container) Snapshot() ContainerState
- func (c *Container) Split(from, to, count int) error
- func (c *Container) SplitTo(from int, dst *Container, to int, count int) error
- func (c *Container) Transfer(from int, dst *Container) (moved int, err error)
- type ContainerState
- type EquipSlot
- type Equipment
- func NewEquipment(catalog *Catalog, slots ...EquipSlot) (*Equipment, error)
- func (e *Equipment) CanEquip(slot, item string) bool
- func (e *Equipment) Catalog() *Catalog
- func (e *Equipment) Clear()
- func (e *Equipment) Equip(slot string, src *Container, from int) error
- func (e *Equipment) Equipped(slot string) (string, bool)
- func (e *Equipment) Restore(st EquipmentState) error
- func (e *Equipment) Slots() []EquipSlot
- func (e *Equipment) Snapshot() EquipmentState
- func (e *Equipment) Unequip(slot string, dst *Container) error
- type EquipmentState
- type EquippedState
- type ItemDef
- type SlotState
- type Stack
Константы
const CurrentVersion = 1CurrentVersion is the item catalog schema version this package reads and writes.
const MaxContainerSize = 1 << 16MaxContainerSize is the largest number of slots a Container may have.
const MaxStackLimit = 1 << 30MaxStackLimit is the largest MaxStack an item definition may declare.
Переменные
var (
// ErrUnknownItem reports an item ID the catalog does not define.
ErrUnknownItem = errors.New("inventory: unknown item")
// ErrInvalidCount reports a non-positive count, or a count larger than a stack holds.
ErrInvalidCount = errors.New("inventory: invalid count")
// ErrSlotOutOfRange reports a container slot index outside [0, Len).
ErrSlotOutOfRange = errors.New("inventory: slot out of range")
// ErrEmptySlot reports an operation that needs an item in a slot that holds none.
ErrEmptySlot = errors.New("inventory: slot is empty")
// ErrSlotOccupied reports a destination slot holding a different item, or one without room for the items being moved.
ErrSlotOccupied = errors.New("inventory: slot is occupied")
// ErrFull reports that a container has no room for all of the items asked for.
ErrFull = errors.New("inventory: container is full")
// ErrNotEnough reports a container holding fewer of an item than asked for.
ErrNotEnough = errors.New("inventory: not enough items")
// ErrCatalogMismatch reports an operation across containers or equipment built from different catalogs.
ErrCatalogMismatch = errors.New("inventory: different catalogs")
)var (
// ErrUnknownEquipSlot reports an equipment slot name the Equipment does not have.
ErrUnknownEquipSlot = errors.New("inventory: unknown equipment slot")
// ErrNotEquippable reports an item whose equipment kind does not match the slot's kind.
ErrNotEquippable = errors.New("inventory: item does not fit equipment slot")
)Типы
type Catalog struct {
// contains filtered or unexported fields
}Catalog is an immutable, validated set of item definitions. Build one with Parse or NewCatalog.
func NewCatalog(defs ...ItemDef) (*Catalog, error)NewCatalog validates defs and returns a catalog holding copies of them in the given order.
func Parse(data []byte) (*Catalog, error)Parse decodes a version 1 YAML item catalog and validates it. Unknown fields, duplicate item IDs, invalid definitions and trailing YAML documents are refused.
func (c *Catalog) Encode() ([]byte, error)Encode writes the catalog as deterministic 2-space YAML (definitions in catalog order, stats keys sorted) that Parse reads back unchanged.
func (c *Catalog) Has(id string) boolHas reports whether the catalog defines id.
func (c *Catalog) Item(id string) (ItemDef, bool)Item returns a copy of the definition with the given ID.
func (c *Catalog) Items() []ItemDefItems returns copies of every definition in catalog order.
func (c *Catalog) Len() intLen returns the number of definitions in the catalog.
type Container struct {
// contains filtered or unexported fields
}Container is a fixed number of slots holding item stacks from one Catalog. The zero Container is not usable; create one with NewContainer.
func NewContainer(catalog *Catalog, size int) (*Container, error)NewContainer returns an empty container with size slots, in [1, MaxContainerSize], holding items from catalog.
func (c *Container) Add(item string, count int) (remaining int, err error)Add puts up to count of item into the container and returns how many did not fit. It first tops up existing stacks of item in slot order, then fills empty slots in slot order. It returns ErrUnknownItem or ErrInvalidCount, adding nothing, when item is not in the catalog or count is not positive.
func (c *Container) AddAll(item string, count int) errorAddAll puts all count of item into the container the way Add does, or returns ErrFull and adds nothing when they do not all fit.
func (c *Container) Catalog() *CatalogCatalog returns the catalog the container's items come from.
func (c *Container) Count(item string) intCount returns how many of item the container holds across all slots.
func (c *Container) IsEmpty() boolIsEmpty reports whether every slot is empty.
func (c *Container) Move(from, to int) errorMove moves the stack in slot from to slot to within the container, as MoveTo does.
func (c *Container) MoveTo(from int, dst *Container, to int) errorMoveTo moves the whole stack in slot from into slot to of dst, which may be c itself:
- into an empty slot, the stack moves there;
- onto a stack of the same item, as many as that stack has room for merge into it and the rest stay in from;
- onto a different item, the two stacks swap.
Moving a slot onto itself does nothing. It returns ErrEmptySlot when slot from is empty and ErrCatalogMismatch when dst uses a different catalog.
func (c *Container) Remove(item string, count int) errorRemove takes count of item out of the container, from the last slot holding it backwards, or returns ErrNotEnough and removes nothing when the container holds fewer.
func (c *Container) RemoveAt(i, count int) (Stack, error)RemoveAt takes count items out of slot i and returns them as a Stack. It returns ErrEmptySlot for an empty slot and ErrInvalidCount when count is not in [1, the slot's count].
func (c *Container) Restore(st ContainerState) errorRestore replaces the container's contents with st after checking every entry: the slot must be in range and listed once, the item defined by the catalog, and the count in [1, the item's maximum stack]. On error the container is left unchanged.
func (c *Container) Room(item string) intRoom returns how many more of item the container can hold: the free space in its stacks of item plus a full stack per empty slot. It returns 0 for an item the catalog does not define.
func (c *Container) Slot(i int) StackSlot returns the stack in slot i, or an empty Stack when i is out of range.
func (c *Container) Slots() []StackSlots returns a copy of every slot in order.
func (c *Container) Snapshot() ContainerStateSnapshot returns the container's non-empty slots in ascending order.
func (c *Container) Split(from, to, count int) errorSplit moves count items from slot from to slot to within the container, as SplitTo does.
func (c *Container) SplitTo(from int, dst *Container, to int, count int) errorSplitTo moves count items, in [1, the stack's count], from slot from into slot to of dst, which must be empty or hold the same item with room for all count. It returns ErrSlotOccupied, moving nothing, when slot to holds a different item or lacks the room, and does nothing when from and to are the same slot.
func (c *Container) Transfer(from int, dst *Container) (moved int, err error)Transfer quick-moves the stack in slot from into dst the way Add does (topping up dst's stacks of the item, then filling its empty slots) and returns how many moved; what does not fit stays in slot from. dst must be a different container from the same catalog.
type ContainerState struct {
// Slots lists the non-empty slots in ascending slot order.
Slots []SlotState `json:"slots"`
}ContainerState is a container's contents in a form encoding/json writes deterministically, for storing in a save slot.
type EquipSlot struct {
// Name identifies the slot, such as "head" or "ring-left"; unique within an Equipment.
Name string
// Kind is the equipment kind the slot accepts, matched against ItemDef.Equip; several slots may share a kind.
Kind string
}EquipSlot is one named equipment slot.
type Equipment struct {
// contains filtered or unexported fields
}Equipment is a set of typed slots, each holding at most one item. The zero Equipment is not usable; create one with NewEquipment.
func NewEquipment(catalog *Catalog, slots ...EquipSlot) (*Equipment, error)NewEquipment returns empty equipment with the given slots, in order, holding items from catalog. Slot names must be unique and, like kinds, non-empty without whitespace or control characters.
func (e *Equipment) CanEquip(slot, item string) boolCanEquip reports whether item is in the catalog and fits slot's kind.
func (e *Equipment) Catalog() *CatalogCatalog returns the catalog the equipment's items come from.
func (e *Equipment) Equip(slot string, src *Container, from int) errorEquip takes one item from slot from of src and puts it in the equipment slot. An item already in the slot goes back to src: into slot from when taking the item emptied it, otherwise wherever src.AddAll would put it. It returns ErrNotEquippable when the item's kind does not match the slot, ErrFull when src has no room for the replaced item, and ErrCatalogMismatch when src uses a different catalog; on any error nothing changes. Equipping the item that is already in the slot does nothing.
func (e *Equipment) Equipped(slot string) (string, bool)Equipped returns the item in slot, and false when slot is empty or unknown.
func (e *Equipment) Restore(st EquipmentState) errorRestore replaces the equipped items with st after checking every entry: the slot must exist and be listed once, and the item must be in the catalog and fit the slot's kind. On error the equipment is left unchanged.
func (e *Equipment) Slots() []EquipSlotSlots returns a copy of the equipment's slots in order.
func (e *Equipment) Snapshot() EquipmentStateSnapshot returns the occupied slots in slot order.
func (e *Equipment) Unequip(slot string, dst *Container) errorUnequip moves the item in slot into dst the way dst.AddAll does. It returns ErrEmptySlot when slot holds nothing and ErrFull, leaving the item equipped, when dst has no room.
type EquipmentState struct {
// Slots lists the occupied equipment slots in the Equipment's slot order.
Slots []EquippedState `json:"slots"`
}EquipmentState is the equipped items in a form encoding/json writes deterministically, for storing in a save slot.
type EquippedState struct {
// Slot is the equipment slot's name.
Slot string `json:"slot"`
// Item is the equipped item's ID.
Item string `json:"item"`
}EquippedState is one occupied equipment slot in an EquipmentState.
type ItemDef struct {
// ID uniquely identifies the item within its catalog and is what stacks, snapshots and saves refer to. It must be non-empty and contain no whitespace or control characters.
ID string `yaml:"id"`
// Name is the item's display name or localization key.
Name string `yaml:"name,omitempty"`
// Description is optional longer display text or a localization key.
Description string `yaml:"description,omitempty"`
// Icon is an optional asset URI for the item's icon, such as "asset:icons/potion.png".
Icon string `yaml:"icon,omitempty"`
// MaxStack is how many of the item one slot holds, in [1, MaxStackLimit]; 0 means 1 and is written by omitting the field, since Parse refuses an explicit "maxStack: 0".
MaxStack int `yaml:"maxStack,omitempty"`
// Equip is the equipment kind the item fits, matched against EquipSlot.Kind; empty means the item cannot be equipped.
Equip string `yaml:"equip,omitempty"`
// Tags are free-form labels such as "consumable" or "quest", unique within the item.
Tags []string `yaml:"tags,omitempty,flow"`
// Stats holds finite numeric values such as damage, armor, weight or price, keyed by non-empty names.
Stats map[string]float64 `yaml:"stats,omitempty"`
}ItemDef defines one kind of item.
func (d ItemDef) EffectiveMaxStack() intEffectiveMaxStack returns MaxStack, or 1 when MaxStack is 0.
func (d ItemDef) HasTag(tag string) boolHasTag reports whether the item carries tag.
type SlotState struct {
// Slot is the slot index.
Slot int `json:"slot"`
// Item is the item's ID.
Item string `json:"item"`
// Count is how many of the item the slot holds.
Count int `json:"count"`
}SlotState is one non-empty slot in a ContainerState.
type Stack struct {
// Item is the item's ID in the catalog; empty for an empty slot.
Item string
// Count is how many of the item the slot holds; 0 for an empty slot.
Count int
}Stack is a count of one item in a slot. The zero Stack is an empty slot.