inventory

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 11 Imported by: 2 modules, 1 package

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 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.

Index

Examples

Constants

View Source
const CurrentVersion = 1

CurrentVersion is the item catalog schema version this package reads and writes.

View Source
const MaxContainerSize = 1 << 16

MaxContainerSize is the largest number of slots a Container may have.

View Source
const MaxStackLimit = 1 << 30

MaxStackLimit is the largest MaxStack an item definition may declare.

Variables

View Source
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")
)
View Source
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")
)

Functions

This section is empty.

Types

type Catalog

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

func NewCatalog(defs ...ItemDef) (*Catalog, error)

NewCatalog validates defs and returns a catalog holding copies of them in the given order.

func Parse

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 (*Catalog) Encode

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 (*Catalog) Has

func (c *Catalog) Has(id string) bool

Has reports whether the catalog defines id.

func (*Catalog) Item

func (c *Catalog) Item(id string) (ItemDef, bool)

Item returns a copy of the definition with the given ID.

func (*Catalog) Items

func (c *Catalog) Items() []ItemDef

Items returns copies of every definition in catalog order.

func (*Catalog) Len

func (c *Catalog) Len() int

Len returns the number of definitions in the catalog.

type Container

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

func NewContainer(catalog *Catalog, size int) (*Container, error)

NewContainer returns an empty container with size slots, in [1, MaxContainerSize], holding items from catalog.

func (*Container) Add

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.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/inventory"
)

func main() {
	cat, _ := inventory.Parse([]byte("version: 1\nitems:\n  - id: arrow\n    maxStack: 99\n"))
	quiver, _ := inventory.NewContainer(cat, 2)
	left, _ := quiver.Add("arrow", 250)
	fmt.Println(quiver.Slots(), left)
}
Output:
[{arrow 99} {arrow 99}] 52

func (*Container) AddAll

func (c *Container) AddAll(item string, count int) error

AddAll 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 (*Container) Catalog

func (c *Container) Catalog() *Catalog

Catalog returns the catalog the container's items come from.

func (*Container) Clear

func (c *Container) Clear()

Clear empties every slot.

func (*Container) Count

func (c *Container) Count(item string) int

Count returns how many of item the container holds across all slots.

func (*Container) IsEmpty

func (c *Container) IsEmpty() bool

IsEmpty reports whether every slot is empty.

func (*Container) Len

func (c *Container) Len() int

Len returns the number of slots.

func (*Container) Move

func (c *Container) Move(from, to int) error

Move moves the stack in slot from to slot to within the container, as MoveTo does.

func (*Container) MoveTo

func (c *Container) MoveTo(from int, dst *Container, to int) error

MoveTo 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 (*Container) Remove

func (c *Container) Remove(item string, count int) error

Remove 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 (*Container) RemoveAt

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 (*Container) Restore

func (c *Container) Restore(st ContainerState) error

Restore 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 (*Container) Room

func (c *Container) Room(item string) int

Room 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 (*Container) Slot

func (c *Container) Slot(i int) Stack

Slot returns the stack in slot i, or an empty Stack when i is out of range.

func (*Container) Slots

func (c *Container) Slots() []Stack

Slots returns a copy of every slot in order.

func (*Container) Snapshot

func (c *Container) Snapshot() ContainerState

Snapshot returns the container's non-empty slots in ascending order.

func (*Container) Split

func (c *Container) Split(from, to, count int) error

Split moves count items from slot from to slot to within the container, as SplitTo does.

func (*Container) SplitTo

func (c *Container) SplitTo(from int, dst *Container, to int, count int) error

SplitTo 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 (*Container) Transfer

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

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

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

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

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 (*Equipment) CanEquip

func (e *Equipment) CanEquip(slot, item string) bool

CanEquip reports whether item is in the catalog and fits slot's kind.

func (*Equipment) Catalog

func (e *Equipment) Catalog() *Catalog

Catalog returns the catalog the equipment's items come from.

func (*Equipment) Clear

func (e *Equipment) Clear()

Clear empties every equipment slot.

func (*Equipment) Equip

func (e *Equipment) Equip(slot string, src *Container, from int) error

Equip 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 (*Equipment) Equipped

func (e *Equipment) Equipped(slot string) (string, bool)

Equipped returns the item in slot, and false when slot is empty or unknown.

func (*Equipment) Restore

func (e *Equipment) Restore(st EquipmentState) error

Restore 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 (*Equipment) Slots

func (e *Equipment) Slots() []EquipSlot

Slots returns a copy of the equipment's slots in order.

func (*Equipment) Snapshot

func (e *Equipment) Snapshot() EquipmentState

Snapshot returns the occupied slots in slot order.

func (*Equipment) Unequip

func (e *Equipment) Unequip(slot string, dst *Container) error

Unequip 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

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

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

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 (ItemDef) EffectiveMaxStack

func (d ItemDef) EffectiveMaxStack() int

EffectiveMaxStack returns MaxStack, or 1 when MaxStack is 0.

func (ItemDef) HasTag

func (d ItemDef) HasTag(tag string) bool

HasTag reports whether the item carries tag.

type SlotState

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

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.

func (Stack) Empty

func (s Stack) Empty() bool

Empty reports whether the stack holds nothing.

Jump to

Keyboard shortcuts

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