destiny

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: BSD-3-Clause Imports: 14 Imported by: ? 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.

README

destiny

Why

github.com/rm4n0s/errors lets a test check that an error happened along a specific execution path. This package does the same for things that are not errors.

A game has few errors but many outcomes: an enemy fled, a chest dropped a rare item, a quest advanced, a door opened. Each one is reached through a chain of decisions in the code. destiny records those outcomes together with the path that led to each one. One run grows many of them, and because their paths share their beginnings, together they form a tree:

World.Step
├── Orc.think
│   └── Root
│       ├── Flee
│       │   └── IsHurt
│       │       └── [Failed] x421
│       └── Chase
│           └── Approach
│               └── [Succeeded] x132
└── Player.act
    └── Player.swingSword
        └── Orc.hurt
            ├── [Damaged] x6
            └── Orc.die
                ├── [Died] x3
                └── Quest.onKill
                    ├── [Advanced] x2
                    ├── [Completed] kills=3
                    └── Door.onQuestCompleted
                        └── Door.update
                            └── [Opened]

A test then asks whether the tree grew a given path, or compares the whole shape of the tree with what it expects. That lets you design a game by writing down, for each situation, the paths it should take.

Usage

AI coding assistants: read AI_GUIDE.md before using this package.

go get github.com/rm4n0s/destiny
Grow a leaf where something happens
func (w *World) Step(in Input) {
    fate := w.fate.Here() // routes start here, whoever calls Step
    w.player.act(fate, w, in)
    for _, o := range w.orcs {
        o.think(fate, w)
    }
    w.fate.Tick() // the end of a frame
}

func (o *Orc) hurt(fate *destiny.Tree, w *World, damage int) {
    o.hp -= damage
    fate.Grow("Damaged", "orc", o.id, "hp", o.hp)
    if o.hp <= 0 {
        o.die(fate, w)
    }
}

Grow takes a tag and key-value pairs. It remembers the call stack of the line it is on. The tree is passed down as an argument, like a context.Context.

Test which paths a game took
func TestASwingThatKillsStartsAChain(t *testing.T) {
    tree := destiny.NewTree()
    w, _ := NewWorld(levelOne, tree, seed)
    w.orcs[0].hp = swordDamage
    putPlayer(w, w.orcs[0], 1.5)

    w.Step(Input{Attack: true})

    // One path:
    if !tree.HasRoute("Player.swingSword->Orc.hurt->Orc.die->Quest.onKill.Advanced") {
        t.Errorf("unexpected tree:\n%s", tree)
    }
    // Or everything the swing caused, and nothing else:
    want := []string{
        "World.Step->Player.act->Player.swingSword->Orc.hurt.Damaged",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die.Died",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Loot.drop.CommonDrop",
        "World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Quest.onKill.Advanced",
    }
    if got := tree.Only("Player.swingSword").Routes(); !slices.Equal(got, want) {
        t.Errorf("got %q", got)
    }
}

A route is the functions from the root of the tree to the leaf, joined by ->, then . and the tag. HasRoute accepts a part of a route, as long as it does not cut a name in two. Routes lists each different route once, in the order it first grew, so comparing it checks both what happened and that nothing else did. Only(route) and During(firstTick, lastTick) give a part of the tree; Find(route) gives the leaves, with their metadata and the tick they grew in.

Name the parts that the call stack cannot tell apart

A scene graph or a behaviour tree is walked by one function that calls itself, so every route would read run->run->run. Branch gives the calling function a name in the routes below it:

func run(fate *destiny.Tree, n *node, o *Orc, w *World) bool {
    fate = fate.Branch(n.name)
    // ... run the children with fate ...
    fate.Grow("Succeeded", "orc", o.id)
}
// World.Step->Orc.think->Root->Fight->Strike.Succeeded

The same works for the states of a state machine: fate.Branch(w.phase.String()).

Every function between the frame function and Grow is in the route, also one that only organizes code. Moving code into a new function changes the routes below it, so a test names the shortest part of a route that tells the cause apart: Orc.hurt->Orc.die.Died does not mind what is above Orc.hurt. (Inline, which left a function out in v0.2.0 and v0.3.0, was removed in v0.4.0.)

Count what happened

Counts says how often a leaf grew along each route, TagCounts how often each tag grew:

rec.TagCounts()                        // map[Damaged:6 Died:3 Escaped:1 Opened:1 ...]
rec.Only("Orc.think").Counts()         // by route: what the orcs decided, and how often

Counted over the games of a bot, they find what no assertion asks about: a door that was opened and closed three hundred times in games that all ended well.

Ask why

A count says what happened too often. The metadata and the order of the leaves say why. Filters cut a tree to a part, and they combine:

rec.Only("Elephant.startle.Startled").CountsBy("by") // map[ostrich:79 tiger:86]: who startled them
rec.Where("animal", 8).Leaves()                      // everything that tiger 8 did and that was done to it, in order
rec.Tagged("Latched", "Unlatched", "Escaped")        // the story of the gates
rec.Around("Fence.smash.Broken", 60, 0)              // the second before each fence broke
rec.Without("Idle").Last(20)                         // how the game ended
rec.Filter(func(l *destiny.Leaf) bool { ... })       // anything else

Where compares values as JSON, so a recording answers as the game that wrote it did: 8 matches the 8.0 that a loaded tree holds.

Carry a path to a goroutine, or to a later frame

A goroutine's stack does not contain the function that started it, and an event that is handled later does not contain the function that sent it. Fork keeps the path:

go p.search(fate.Fork(), grid)                     // a goroutine: Fork runs in the parent

w.events = append(w.events, event{fate: fate.Fork()}) // an event: handled in a later step

func (d *Door) onQuestCompleted(e event) {
    e.fate.Here().Grow("Unlocking")
}
// World.Step->Player.act->Player.swingSword->Orc.hurt->Orc.die->Quest.onKill->Door.onQuestCompleted.Unlocking

The route of the door says what caused it, even though it opened in another frame.

Record a real game without running out of memory

A nil *destiny.Tree does nothing, so a game that does not record leaves its tree nil. A game that records writes its tree out from time to time:

if w.steps%60 == 0 {
    if err := tree.Dump(file); err != nil { // one line of JSON; the tree forgets what it wrote
        slog.Error("the tree was not written", "err", err)
    }
}

destiny.Load(file) reads the file back into a tree, which a test queries like any other. A tree also logs itself through log/slog, and ToJson/FromJson turn it into JSON and back.

Go back to any moment of a recording

A recording says what happened, not what the player did. A game with deterministic rules also puts what it was given on the tape: how it started, and the input of every tick.

fate.Start(Begin{Level: level, Seed: seed}) // where the world is made

func (w *World) Step(in Input) {
    fate := w.fate.Here()
    fate.Input(in) // once a tick, before the rules
    // ...
}

Dump writes the tape with the leaves. A test that has only the file plays the game again, and stops where it wants:

rec, _ := destiny.Load(file)
died := rec.Find("Orc.die.Died")[0]
take := rec.TakeAt(died.Tick)

var begin Begin
take.ReadStart(&begin)
w, tree := newWorld(begin.Level, begin.Seed)
for tick := take.First; tick < died.Tick-60; tick++ { // to a second before the orc died
    var in Input
    take.ReadInput(tick, &in)
    w.Step(in)
}
if d := take.Diverged(tree); d != nil {
    t.Fatalf("the replay left the recording in tick %d: %v %v", d.Tick, d.Missing, d.Extra)
}

A session in which somebody met a bug becomes a test case. Diverged is the check that the replay is that session: the same routes, in the same ticks. It works for rules that are deterministic, and for as long as they do not change: a tape reproduces a bug in the code that recorded it.

Read a recording without writing code
go run github.com/rm4n0s/destiny/cmd/destiny session.destiny Orc.die             # every such leaf: tick, route, metadata
go run github.com/rm4n0s/destiny/cmd/destiny -counts session.destiny             # how often each route grew
go run github.com/rm4n0s/destiny/cmd/destiny -by weapon session.destiny Died     # what they died of, and how often
go run github.com/rm4n0s/destiny/cmd/destiny -where orc=3 session.destiny        # the story of orc 3
go run github.com/rm4n0s/destiny/cmd/destiny -around Died -before 60 session.destiny

It has a flag for each filter (-where, -tag, -without, -during, -around with -before and -after, -first, -last; run it without arguments for the list), and reads a file that was packed with gzip.

The tick of a leaf is where a replay goes to.

Print the tree

fmt.Println(tree) draws the tree shown at the top. A failing test should print it: t.Errorf("unexpected tree:\n%s", tree).

Cost

Measured on an AMD Ryzen 9 6900HX with Go 1.27 (go test -bench .):

Call Time Memory
Grow without metadata, ten calls deep 1.3 µs 48 B, 1 allocation
Grow with one key-value pair 1.5 µs 392 B, 4 allocations
Branch, Fork or Here at a place the tree has seen 0.3–0.7 µs none
Input of two gamepads, once a tick 1.2–1.4 µs 190–380 B, 3 allocations
Grow on a nil tree a nil check none; 8 B when a number is passed as metadata

Here, Branch and Fork walk the call stack whether a leaf grows afterwards or not: make a handle after the check that returns early, not for every tile in every frame.

A recording of the example game crypt takes 68 bytes a leaf on disk, and 85 bytes a tick for the tape of a player who moves all the time, or 26 when the direction is rounded to two decimals. gzip makes it 17 times smaller.

Examples

examples holds two small 3D games made with Glutter, in a module of their own so that this package depends on nothing but rm4n0s/errors:

  • examples/crypt: a dungeon. A behaviour tree (Branch), a chain of consequences from one sword swing, an event that opens a door a second later (Fork), three orcs through the same code, recording and replay.
  • examples/bastion: a tower defence. A state machine (Branch), path-finding on another goroutine (Fork), recording and replay.

Each has tests of its rules and tests of its real page on Glutter's test harness.

More

SPEC.md describes every rule in detail: where a route starts, how names are matched, what Branch, Fork and Here do to a path, the tape, and the format of a dump.

Documentation

Overview

Package destiny records what a program did as a tree of execution paths, so that tests can check not only that something happened but along which path.

It is github.com/rm4n0s/errors for things that are not errors. A game has few errors, but it has many outcomes: an enemy fled, a chest dropped a rare item, a quest advanced. Each call to Tree.Grow adds a leaf that remembers the path that led to it. One run grows many leaves, and their paths together form a tree:

Game.Tick
├── EnemyAI.decide
│   └── EnemyAI.flee
│       └── [LowHealth] hp=12
└── Loot.roll
    └── [RareDrop] item=sword

A route is one path of that tree, written from the root to the leaf:

Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth

Tree.HasRoute reports whether the tree grew a given path.

A path is made of the functions on the call stack: every function between the root and the line that grows a leaf is in its route. Three methods change what the call stack alone would give:

  • Tree.Here starts the routes at the calling function, whatever an engine or a test has on the stack above it.
  • Tree.Branch gives a part of the tree a name where the call stack says nothing useful: a scene graph or a behaviour tree walked by one function that calls itself.
  • Tree.Fork carries a path to another goroutine or to a later moment: an event queue, a timer.

A tree also holds a tape: what a game started from (Tree.Start) and what it was given in every tick (Tree.Input). Tree.Dump writes it with the leaves. A game with deterministic rules plays a recording again from its tape, up to any tick (Take.ReadStart, Take.ReadInput), and Take.Diverged checks that the replay took the paths of the recording.

Index

Constants

View Source
const (
	// TagDumpEncodeFailed is the tag of the error of Dump when the leaves
	// could not be turned into JSON.
	TagDumpEncodeFailed = "DumpEncodeFailed"
	// TagDumpWriteFailed is the tag of the error of Dump when the writer
	// failed. Its OriginalErr is the error of the writer.
	TagDumpWriteFailed = "DumpWriteFailed"
	// TagLoadDecodeFailed is the tag of the error of Load when the reader
	// failed or what it read is not a dump. Its metadata has the number of
	// the line under "line".
	TagLoadDecodeFailed = "LoadDecodeFailed"
)

The tags of the errors of this package.

View Source
const (
	// TagTapeEncodeFailed is the tag of the error of a start value or an input
	// that JSON cannot hold. Dump returns it once, and Take.ReadStart and
	// Take.ReadInput return it for that take or tick. Its metadata has the
	// tick under "tick".
	TagTapeEncodeFailed = "TapeEncodeFailed"
	// TagTapeDecodeFailed is the tag of the error of Take.ReadStart and
	// Take.ReadInput when the value on the tape does not fit what it is read
	// into. Its metadata has the tick under "tick".
	TagTapeDecodeFailed = "TapeDecodeFailed"
)

The tags of the errors of the tape.

Variables

This section is empty.

Functions

This section is empty.

Types

type Divergence added in v0.3.0

type Divergence struct {
	// Tick is the tick of the recording. The replay is at tick Tick-First of
	// the take.
	Tick int
	// Missing are the routes that the recording has in that tick and the
	// replay does not, and Extra those that the replay has and the recording
	// does not, both sorted. A route that grew more often on one side is
	// there once for every time.
	Missing, Extra []string
}

Divergence is the first tick in which a replay did something else than the recording.

type InputJson added in v0.3.0

type InputJson struct {
	Tick   int `json:",omitempty"`
	Repeat int `json:",omitempty"`
	Value  json.RawMessage
}

InputJson is the input of a tick (Tree.Input) in a form that can be marshaled. Repeat is how many ticks after Tick have the same input.

type Leaf

type Leaf struct {
	Tag      string
	Metadata map[string]any
	// Tick is how many times Tree.Tick had been called when the leaf grew.
	Tick int
	// contains filtered or unexported fields
}

Leaf is one outcome grown on a Tree: a tag, optional metadata, the tick it grew in and the path that led to it.

func (*Leaf) HasRoute

func (l *Leaf) HasRoute(route string) bool

HasRoute reports whether the route of the leaf contains the given route. The given route may leave out the start or the end of the path, but not part of a name: "EnemyAI.flee.LowHealth", "decide->EnemyAI.flee" and "LowHealth" all match "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth", while "flee.Low" and "Tick->Enemy" do not. An empty route matches nothing.

func (*Leaf) Route

func (l *Leaf) Route() string

Route returns the path of the leaf from the root of its tree, followed by its tag: "Game.Tick->EnemyAI.decide->EnemyAI.flee.LowHealth".

func (*Leaf) StackFrames

func (l *Leaf) StackFrames() []StackFrame

StackFrames returns the steps on the path of the leaf, from the root of the tree to the function that grew the leaf.

type LeafJson

type LeafJson struct {
	Tag      string
	Path     int            // an index into TreeJson.Paths
	Tick     int            `json:",omitempty"`
	Metadata map[string]any `json:",omitempty"`
}

LeafJson is a Leaf in a form that can be marshaled.

type PathJson

type PathJson struct {
	// Route is the steps as text, for whoever reads the log. FromJson and
	// Load ignore it and use StackFrames.
	Route       string       `json:",omitempty"`
	StackFrames []StackFrame // from the root of the tree to the leaf
}

PathJson is one path of a tree: the steps that several leaves share.

type StackFrame

type StackFrame struct {
	FuncName    string
	StructName  string `json:",omitempty"`
	PackageName string `json:",omitempty"`
}

StackFrame is one step of a route: a function on the call stack, or a name given by Tree.Branch, which has only a FuncName.

type StartJson added in v0.3.0

type StartJson struct {
	Tick  int             `json:",omitempty"`
	Value json.RawMessage `json:",omitempty"`
}

StartJson is the beginning of a take (Tree.Start) in a form that can be marshaled. A take without a start value has no Value.

type Take added in v0.3.0

type Take struct {
	// First is the tick in which the take began. Last is the last tick of it
	// that has an input: First-1 when it has none. The tree counts the ticks
	// of the whole session, so a game that counts its steps from 0 in every
	// take is at step tick-First.
	First, Last int
	// contains filtered or unexported fields
}

Take is a part of a session that started from nothing: a start value, and the inputs and the leaves of its ticks. It is a copy: what the tree records or forgets afterwards does not change it.

Every method works on a nil *Take: the reads return false and Diverged returns nil.

func (*Take) Diverged added in v0.3.0

func (k *Take) Diverged(replay *Tree) *Divergence

Diverged compares the take with the tree of a game that played it again, and returns the first tick in which they differ, or nil when they do not.

The replay is a tree that started with the take: its tick 0 is the tick First of the recording. Tick by tick, the routes of the leaves that grew in the recording are compared with those of the replay, for the ticks that the replay has ended (Tree.Tick) and the take covers. Within a tick the order of the leaves does not count; how often a route grew does. Metadata is not compared.

It is the check that a replay is the session that was recorded: a game whose rules are not deterministic, or have changed since, learns in which tick it left the recording.

func (*Take) ReadInput added in v0.3.0

func (k *Take) ReadInput(tick int, into any) (bool, error)

ReadInput fills into with the input of a tick of the take, as json.Unmarshal does. It returns false when the tick has no input or is not a tick of the take.

Read into a new variable for every tick: json.Unmarshal leaves alone what the JSON does not mention, so a variable that is used again may keep a part of the input of the tick before.

func (*Take) ReadStart added in v0.3.0

func (k *Take) ReadStart(into any) (bool, error)

ReadStart fills into with the start value of the take, as json.Unmarshal does. It returns false when the take has none.

type Tree

type Tree struct {
	// contains filtered or unexported fields
}

Tree collects the leaves that a program grows while it runs.

The root of the tree is the function that called NewTree: routes start with the functions that it calls. When that function is no longer running, routes start below the deepest function that is on both the stack of NewTree and the stack of Grow. With nothing in common, a route is the whole stack of the goroutine.

A nil *Tree is valid and does nothing, so a game can leave its tree nil when it does not record.

A tree keeps every leaf until Dump writes them out, so a tree that records a long session has to be dumped from time to time.

A Tree is safe for concurrent use. The handles that Here, Branch and Fork return grow leaves on the same tree, and the methods that read the tree (HasRoute, Routes, Counts, Leaves, String...) read all of it whichever handle they are called on.

func FromJson

func FromJson(tj TreeJson) *Tree

FromJson rebuilds a tree, for example one that was logged by a running game, so that a test can compare it with the tree of its own run. The root of the leaves grown on it afterwards is the function that called FromJson.

Numbers in the metadata of a tree that went through JSON are float64.

func Load

func Load(r io.Reader) (*Tree, error)

Load reads what Dump wrote, any number of lines, into one tree. The root of the leaves grown on it afterwards is the function that called Load.

When the reader fails or a line is not a dump (the last line of a game that crashed while writing, for example), Load returns the tree of the lines before it together with an error with the tag TagLoadDecodeFailed.

Numbers in the metadata of a loaded tree are float64.

func NewTree

func NewTree() *Tree

NewTree returns an empty tree whose root is the calling function.

func (*Tree) Around added in v0.5.0

func (t *Tree) Around(route string, before, after int) *Tree

Around returns a tree with the leaves that grew near a leaf of the given route (see Leaf.HasRoute): at most before ticks before it, in its own tick, or at most after ticks after it. It answers what led to something and what came of it:

tree.Around("Barrel.explode", 60, 0) // the second before each explosion, and its tick

Around(route, 0, 0) is everything that grew in the same ticks as the route.

func (*Tree) Branch

func (t *Tree) Branch(name string) *Tree

Branch returns a handle for a named part of the tree. In the routes of what grows through the handle, the function that called Branch appears under the given name:

func (n *Node) update(t *destiny.Tree) {
    t = t.Branch(n.Name)
    for _, child := range n.Children {
        child.update(t)
    }
}

Without Branch every route of this scene graph would read Node.update->Node.update->Node.update. With it they read World->Level1->Door3.

Calling Branch again in the same function, on the handle it returned, adds a name below the first one.

A name is part of the route, so it has to come from a small, fixed set (the names of nodes, states or scripts) and must not contain "." or "->". What changes for each entity or frame belongs in the metadata of a leaf.

func (*Tree) Counts added in v0.4.0

func (t *Tree) Counts() map[string]int

Counts returns how often a leaf grew along each route of the tree. Its keys are the routes that Routes lists. Over one game it says what happened how often; over many games it shows what never happens and what happens far too often. Cut the tree first to count a part of it: Only(route).Counts().

func (*Tree) CountsBy added in v0.5.0

func (t *Tree) CountsBy(key string) map[string]int

CountsBy returns how often each value stands under the given key in the metadata of the leaves: by whom, of which kind, at which place. Leaves without the key are not counted. Cut the tree first to ask about one outcome:

tree.Only("Elephant.startle.Startled").CountsBy("by") // map[crowd:4 ostrich:79 tiger:86]

A key of the result is the value as text: a string as it is, anything else as the JSON that Dump writes, so 3 and 3.0 are both "3".

func (*Tree) Dump

func (t *Tree) Dump(w io.Writer) error

Dump writes the leaves that the tree holds to w and then forgets them, so that a tree that records a long session does not grow without end. Call it from time to time: every tick, every few seconds, or when Len passes a limit.

Each call writes one line of JSON, a TreeJson, that can be read on its own: the output can be cut into files between two calls. A tree without leaves and without a tape writes nothing. Load reads the lines back.

The line also holds the tape since the last call (Tree.Start, Tree.Input), which the tree forgets with the leaves.

When writing fails, Dump returns an error with the tag TagDumpWriteFailed and the tree keeps its leaves and its tape. A metadata value that JSON cannot hold (a channel, a function, a NaN) is written as its text. A start value or an input that JSON could not hold is not on the tape: Dump writes the rest and then returns the error with the tag TagTapeEncodeFailed.

Dump may be called from another goroutine than the one that grows the tree. Growing does not wait for the writer.

func (*Tree) During

func (t *Tree) During(first, last int) *Tree

During returns a tree with the leaves that grew in the ticks from first to last, both included.

func (*Tree) Filter added in v0.5.0

func (t *Tree) Filter(keep func(*Leaf) bool) *Tree

Filter returns a tree with the leaves that keep accepts. It is what the other filters (Only, Without, Tagged, Where, During, Around, First, Last) are made of: use it for a question that none of them asks.

What a filter returns is a copy: leaves grown later on either tree do not appear on the other. It has no tape: call Takes on the tree that recorded or loaded it. Filters combine, each one cutting what the one before it left.

tree.Filter(func(l *destiny.Leaf) bool { hp, _ := l.Metadata["hp"].(int); return hp < 10 })

Numbers in the metadata of a tree that Load returned are float64. A nil keep accepts every leaf.

func (*Tree) Find

func (t *Tree) Find(route string) []*Leaf

Find returns the leaves whose route has the given route, in the order they grew. Use it to count how often a path was taken, to read the metadata of its leaves, or to compare the ticks of two outcomes.

func (*Tree) First added in v0.5.0

func (t *Tree) First(n int) *Tree

First returns a tree with the first n leaves.

func (*Tree) Fork

func (t *Tree) Fork() *Tree

Fork returns a handle that continues the current path somewhere else: in another goroutine, or at a later moment in the same one.

A goroutine's call stack does not contain the function that started it. Call Fork in the goroutine that hands the work off and use the handle in the new one:

go ai.think(tree.Fork()) // the arguments of a go statement run in the parent

An event that is queued and handled later has the same problem: when the handler runs, the function that sent the event has returned. Store a fork in the event and grow through it in the handler:

queue.push(event{kind: doorOpened, fate: tree.Fork()})

The routes of the leaves grown through the handle start with the path of the Fork call and continue with the functions of the stack of Grow that were not already running when Fork was called.

func (*Tree) Grow

func (t *Tree) Grow(tag string, metadata ...any)

Grow adds a leaf with the given tag at the end of the current path.

The metadata is a list of key-value pairs, as in log/slog: Grow("LowHealth", "hp", 12). A value without a string key before it is stored as "arg<index>". Pass values, not pointers to things that change: the leaf keeps what it is given, and what a pointer points to may be different when the leaf is read.

Whatever is different for each entity or each frame (an ID, a position) belongs in the metadata. The tag is part of the route, and the tree keeps every different path it has seen.

func (*Tree) HasRoute

func (t *Tree) HasRoute(route string) bool

HasRoute reports whether the tree grew a leaf along the given route. See Leaf.HasRoute for what a route may leave out.

func (*Tree) Here

func (t *Tree) Here() *Tree

Here returns a handle whose routes continue with the calling function alone, and leave out everything else that is on the call stack above it.

A game engine calls the frame function of a game through many functions of its own, and a test calls it through others. Call Here at the top of the frame function and grow through the handle: the routes then start with that function wherever it was called from.

func (w *World) Step(in Input) {
    fate := w.fate.Here()
    w.player.act(fate, in) // World.Step->Player.act...
}

On a handle of Fork or Branch, Here keeps the path of the handle and adds the calling function to it.

func (*Tree) Input added in v0.3.0

func (t *Tree) Input(v any)

Input stores the input of the current tick: what the rules of the game are given in it. Call it once in every tick, before the rules run. Called again in the same tick, it replaces the first. A tick without a call has no input.

v is turned into JSON at once, so a game may pass a slice that it uses again in the next tick. Equal inputs of ticks that follow each other are stored once. Take.ReadInput reads the value back.

A value that JSON cannot hold (a function, a NaN) is not kept: Dump returns an error with the tag TagTapeEncodeFailed, and Take.ReadInput of that tick returns the same error.

func (*Tree) Last added in v0.5.0

func (t *Tree) Last(n int) *Tree

Last returns a tree with the last n leaves: how a game that went wrong ended.

func (*Tree) Leaves

func (t *Tree) Leaves() []*Leaf

Leaves returns the leaves that the tree holds, in the order they grew. A path that was taken twice has two leaves.

func (*Tree) Len

func (t *Tree) Len() int

Len returns the number of leaves that the tree holds.

func (*Tree) LogValue

func (t *Tree) LogValue() slog.Value

LogValue implements slog.LogValuer. The keys match the fields of TreeJson, so a logged tree can be unmarshaled into TreeJson and rebuilt with FromJson.

func (*Tree) Only

func (t *Tree) Only(route string) *Tree

Only returns a tree with the leaves whose route has the given route (see Leaf.HasRoute). Use it to look at one part of a tree: the routes below one function, or the leaves with one tag.

func (*Tree) Routes

func (t *Tree) Routes() []string

Routes returns the different routes of the tree, in the order they first grew. A path that was taken many times appears once, so the result describes the shape of the tree: comparing it with a list of expected routes checks both what happened and that nothing else did.

func (*Tree) Start added in v0.3.0

func (t *Tree) Start(v any)

Start begins a take at the current tick: a part of a session that starts from nothing, such as one level or one match. v is what the game needs to begin it again: the level, the players, the seed of its random numbers.

A take covers the ticks until the next Start. Together with the inputs of its ticks (Input) it lets a deterministic game play the take again, up to any tick. Take.ReadStart reads the value back.

v is turned into JSON at once. A value that JSON cannot hold is not kept: the take then has no start value, Dump returns an error with the tag TagTapeEncodeFailed, and Take.ReadStart returns the same error.

func (*Tree) String

func (t *Tree) String() string

String draws the tree, one step or leaf per line, in the order they first grew. A leaf is written as its tag in brackets followed by its metadata. Leaves with the same tag at the same place are drawn once, with how many there are instead of their metadata:

Game.Tick
├── EnemyAI.decide
│   └── EnemyAI.flee
│       └── [LowHealth] hp=12
└── Physics.step
    └── [Grounded] x120

func (*Tree) TagCounts added in v0.4.0

func (t *Tree) TagCounts() map[string]int

TagCounts returns how often a leaf with each tag grew, along whatever route.

func (*Tree) Tagged added in v0.5.0

func (t *Tree) Tagged(tags ...string) *Tree

Tagged returns a tree with the leaves that have one of the given tags, whatever their route. With the leaves in the order they grew, a few tags tell a story:

tree.Tagged("Latched", "Unlatched", "Escaped").Leaves()

func (*Tree) TakeAt added in v0.3.0

func (t *Tree) TakeAt(tick int) *Take

TakeAt returns the take that a tick belongs to: the one that began last at or before it. Give it the tick of a leaf to find the take in which the leaf grew. It returns nil when no take had begun.

func (*Tree) Takes added in v0.3.0

func (t *Tree) Takes() []*Take

Takes returns the takes that the tree holds, in the order they began. Inputs from before the first Start are a take without a start value.

func (*Tree) Tick

func (t *Tree) Tick() int

Tick ends the current tick and starts the next one. It returns the number of the tick that starts. Call it at the end of each frame: every leaf then knows in which frame it grew (Leaf.Tick), counted from 0.

func (*Tree) ToJson

func (t *Tree) ToJson() *TreeJson

ToJson returns the leaves that the tree holds in a form that can be marshaled. The tree keeps them.

func (*Tree) Where added in v0.5.0

func (t *Tree) Where(key string, values ...any) *Tree

Where returns a tree with the leaves whose metadata has the given key and, when values are given, one of these values under it.

tree.Where("orc", 3)               // what happened to orc 3, and what it did
tree.Where("by", "tiger", "crowd") // by either of them
tree.Where("target")               // every leaf that names a target

Values are compared as the JSON that Dump writes, so that a tree which recorded and the tree which Load made of it answer the same: 3, int64(3) and 3.0 are equal, a struct equals the map that it loads as, and "3" is not 3.

func (*Tree) Without added in v0.5.0

func (t *Tree) Without(route string) *Tree

Without returns a tree without the leaves whose route has the given route: the opposite of Only. Use it to take the noise out of a tree before reading it.

tree.Without("Physics.step").Without("Idle")

type TreeJson

type TreeJson struct {
	Paths  []PathJson
	Leaves []LeafJson
	Starts []StartJson `json:",omitempty"`
	Inputs []InputJson `json:",omitempty"`
}

TreeJson is a Tree in a form that can be marshaled: the different paths, the leaves in the order they grew, and the tape when the game recorded one.

Directories

Path Synopsis
cmd
destiny command
Command destiny reads a recording that Tree.Dump wrote and prints what is in it: the leaves with the ticks they grew in, or how often each route or each value of a metadata key grew.
Command destiny reads a recording that Tree.Dump wrote and prints what is in it: the leaves with the ticks they grew in, or how often each route or each value of a metadata key grew.

Jump to

Keyboard shortcuts

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