replay

package
v0.3.0 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: 1 module, 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.

Documentation

Overview

Package replay records per-step game input to versioned YAML text files and plays it back deterministically for debugging and automated tests.

Index

Examples

Constants

View Source
const FormatVersion = 2

FormatVersion is the version written to every Recording and the only one Decode accepts.

Version 2 is the YAML text format described in Encode; version 1 was a compact JSON form that is no longer read.

Variables

This section is empty.

Functions

func AssertEndState

func AssertEndState[S any](t testing.TB, rec *Recording, want S, equal func(a, b S) bool, makeSim func(seed uint64, src ActionSource) (step func(dt time.Duration), state func() S)) S

AssertEndState plays rec with Run and fails t with a diagnostic if the end state does not match want according to equal (or reflect.DeepEqual when equal is nil). It returns the end state produced by the run.

func Run

func Run[S any](t testing.TB, rec *Recording, makeSim func(seed uint64, src ActionSource) (step func(dt time.Duration), state func() S)) S

Run plays rec from start to finish against the simulation returned by makeSim and returns its end state.

makeSim receives rec.Seed and a *Player as its ActionSource, and returns the per-step update function and a function returning the current state. Run calls step rec.TotalSteps times with rec.StepDuration(), matching game.Loop's fixed dt; step is expected to call src.Step() once per update, just as a live game.Loop.Update does with *input.Actions.

func SaveFile

func SaveFile(path string, rec *Recording) error

SaveFile writes rec to path as the YAML text Encode produces. The conventional extension is ".replay.yaml".

Types

type ActionSource

type ActionSource interface {
	Pressed(name string) bool
	JustPressed(name string) bool
	JustReleased(name string) bool
	Axis(name string) float64
	Step()
}

ActionSource supplies named actions and axes sampled once per game.Loop step.

*input.Actions satisfies ActionSource for live play, *Recorder wraps an ActionSource to record it, and *Player satisfies ActionSource for playback, so a game reading input through ActionSource behaves identically in all three modes.

type AxisChange

type AxisChange struct {
	// Index is the position of the axis in Recording.Axes.
	Index int
	// Value is the axis value from this step on.
	Value float64
}

AxisChange records a new value for Recording.Axes[Index].

type Player

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

Player plays back a Recording as an ActionSource.

Each call to Step advances one recorded step and updates the action and axis snapshots so Pressed, JustPressed, JustReleased and Axis reproduce the recorded run on every step, including transitions on step 0, multi-step holds, rapid single-step taps and axis changes.

func NewPlayer

func NewPlayer(rec *Recording) *Player

NewPlayer returns a Player ready to play rec from step 0. A nil rec plays as an empty recording whose Done is immediately true.

func (*Player) Axis

func (p *Player) Axis(name string) float64

Axis returns the recorded value of axis name for the current step. If name is not a recorded axis, it falls back to 1 when action name is pressed and 0 otherwise, matching input.Actions.Axis.

func (*Player) Done

func (p *Player) Done() bool

Done reports whether all recorded steps have been played.

func (*Player) JustPressed

func (p *Player) JustPressed(name string) bool

JustPressed reports whether name became pressed on the current step and was not pressed on the previous step.

func (*Player) JustReleased

func (p *Player) JustReleased(name string) bool

JustReleased reports whether name was pressed on the previous step and is no longer pressed on the current step.

func (*Player) Pressed

func (p *Player) Pressed(name string) bool

Pressed reports whether name is pressed during the current step.

func (*Player) Rate

func (p *Player) Rate() int

Rate returns the fixed step rate recorded in the underlying Recording (60 when unset).

func (*Player) Reset

func (p *Player) Reset()

Reset rewinds playback to step 0 and clears the current and previous step snapshots.

func (*Player) Seed

func (p *Player) Seed() uint64

Seed returns the random seed recorded in the underlying Recording.

func (*Player) Step

func (p *Player) Step()

Step advances playback by one recorded step and updates the action and axis snapshots.

Once Done is true, further calls to Step release any actions that were still pressed on the final recorded step (firing JustReleased once) and leave all actions and axes idle.

func (*Player) StepIndex

func (p *Player) StepIndex() int

StepIndex returns the number of steps played so far, from 0 before the first Step up to TotalSteps when Done is true.

func (*Player) TotalSteps

func (p *Player) TotalSteps() int

TotalSteps returns the total number of steps in the Recording.

type Recorder

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

Recorder wraps an ActionSource, implements ActionSource itself, and records watched actions and axes on every Step.

Calling Step steps the wrapped source once and appends a StepEvent only when at least one watched action's pressed state or watched axis's value changed from the previous step. Pass a Recorder anywhere a game accepts ActionSource to record live play without changing the game's update loop.

Example

A Recorder wraps the live input and records each step's changes; a Player then plays the Recording back as the same ActionSource, so the game cannot tell the difference.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/input"
	"github.com/nsgo-dev/game/pkg/replay"
)

func main() {
	live := input.NewActions()
	rec := replay.NewRecorder(live, 42, 60, []string{"jump"}, nil)
	for step := range 5 {
		if step == 2 {
			live.Trigger("jump")
		}
		rec.Step()
	}
	recording := rec.Recording()
	fmt.Println(recording.TotalSteps, len(recording.Events))

	p := replay.NewPlayer(recording)
	for !p.Done() {
		p.Step()
		if p.JustPressed("jump") {
			fmt.Println("jump on step", p.StepIndex()-1)
		}
	}
}
Output:
5 2
jump on step 2

func NewRecorder

func NewRecorder(src ActionSource, seed uint64, rate int, actions, axes []string) *Recorder

NewRecorder returns a Recorder that wraps src and records the named actions and axes with seed and fixed step rate (60 when rate <= 0).

Empty or duplicate names in actions and axes are ignored, preserving first-seen order.

func (*Recorder) Axis

func (r *Recorder) Axis(name string) float64

Axis returns the value of name on the wrapped ActionSource.

func (*Recorder) JustPressed

func (r *Recorder) JustPressed(name string) bool

JustPressed reports whether name became pressed on the wrapped ActionSource on the current step.

func (*Recorder) JustReleased

func (r *Recorder) JustReleased(name string) bool

JustReleased reports whether name was released on the wrapped ActionSource on the current step.

func (*Recorder) Pressed

func (r *Recorder) Pressed(name string) bool

Pressed reports whether name is pressed on the wrapped ActionSource.

func (*Recorder) Rate

func (r *Recorder) Rate() int

Rate returns the fixed step rate stored in the recording.

func (*Recorder) Recording

func (r *Recorder) Recording() *Recording

Recording returns a deep copy of everything recorded so far. Continuing to step r afterwards does not affect the returned Recording.

func (*Recorder) Reset

func (r *Recorder) Reset(seed uint64)

Reset clears the recorded steps and events and begins a fresh recording with seed, keeping the wrapped source, rate and watched names.

func (*Recorder) Seed

func (r *Recorder) Seed() uint64

Seed returns the random seed stored in the recording.

func (*Recorder) Step

func (r *Recorder) Step()

Step steps the wrapped ActionSource once and records any watched actions or axes whose values changed on this step.

func (*Recorder) TotalSteps

func (r *Recorder) TotalSteps() int

TotalSteps returns the number of steps recorded so far.

type Recording

type Recording struct {
	// Version is the format version; it must equal FormatVersion.
	Version int
	// Seed is the random seed the recorded run started from.
	Seed uint64
	// Rate is the fixed step rate in steps per second.
	Rate int
	// Actions are the watched action names that StepEvent.Press and StepEvent.Release index into.
	Actions []string
	// Axes are the watched axis names that AxisChange.Index indexes into.
	Axes []string
	// TotalSteps is the number of recorded steps, including steps without events.
	TotalSteps int
	// Events are the steps where input changed, in strictly increasing Step order.
	Events []StepEvent
}

Recording holds a game's random seed, fixed step rate, watched action and axis names, total step count and delta-encoded step events.

Only steps where at least one watched action's pressed state or watched axis's value changed from the previous step appear in Events, keeping long recordings compact. Encode writes a Recording as YAML text with one line per event, and Decode reads that text back.

func Decode

func Decode(data []byte) (*Recording, error)

Decode reads a Recording from the YAML text Encode writes, including text a person has edited, and validates it.

Unknown keys, a missing seed, total_steps or step number, names that are not in the header's actions or axes, and trailing YAML documents are refused. Steps must be listed in increasing order. A recording with another version, such as the compact JSON of version 1, is refused with an error naming that version.

Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as LoadFile does.

Example

Encode writes a Recording as versioned text that Decode reads back, so recordings can be checked in next to the tests that replay them.

package main

import (
	"fmt"

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

func main() {
	rec := &replay.Recording{
		Version: replay.FormatVersion, Seed: 7, Rate: 60, TotalSteps: 3,
		Actions: []string{"fire"},
		Events:  []replay.StepEvent{{Step: 1, Press: []int{0}}, {Step: 2, Release: []int{0}}},
	}
	data, err := rec.Encode()
	if err != nil {
		fmt.Println(err)
		return
	}
	back, err := replay.Decode(data)
	fmt.Println(err, back.Seed, back.StepDuration(), len(back.Events))
}
Output:
<nil> 7 16.666666ms 2

func LoadFile

func LoadFile(path string) (*Recording, error)

LoadFile reads and decodes the YAML Recording at path. Its errors are *loaderr.Error values that name path.

func (*Recording) Clone

func (r *Recording) Clone() *Recording

Clone returns an independent deep copy of r, or nil if r is nil.

func (*Recording) Encode

func (r *Recording) Encode() ([]byte, error)

Encode validates r and writes it as deterministic YAML text: a header with the version, seed, rate, watched names and total step count, then one line per step on which input changed.

version: 2
seed: 99537266
rate: 60
actions: [left, right, jump, dash]
axes: [move_x]
total_steps: 254
steps:
  - {step: 6, press: [right], axes: {move_x: 1}}
  - {step: 85, press: [jump, dash]}
  - {step: 95, release: [jump, dash]}

Each step line names the actions it presses and releases and the new values of the axes that changed. The same Recording always encodes to the same bytes, and Decode followed by Encode reproduces a file Encode wrote byte for byte.

func (*Recording) StepDuration

func (r *Recording) StepDuration() time.Duration

StepDuration returns the fixed duration of one step, 1/Rate seconds (1/60 s when Rate <= 0).

func (*Recording) Validate

func (r *Recording) Validate() error

Validate checks that r uses the supported format version, has a valid rate and step count, unique non-empty action and axis names, and strictly increasing in-bounds step events. Its errors are *loaderr.Error values that name the field at fault in the YAML text Encode writes, such as "steps[3].press[0]", and how to fix it.

type StepEvent

type StepEvent struct {
	// Step is the zero-based step the changes take effect on.
	Step int
	// Press lists the actions that became pressed on Step.
	Press []int
	// Release lists the actions that were released on Step.
	Release []int
	// Axes lists the axes whose value changed on Step.
	Axes []AxisChange
}

StepEvent holds the action and axis changes that occurred on Step.

Press and Release hold indices into Recording.Actions. Axes holds index-to-value updates into Recording.Axes.

Jump to

Keyboard shortcuts

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