undo

package
v0.3.0-rc.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: 6 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 undo records the reversible moves of puzzle and turn-based games, with linear undo and redo.

A History owns a game's state and a list of moves. Do applies a move and records it, Undo reverts the last applied move, and Redo applies the last undone one again; a new move after an undo discards the moves that could have been redone. Every move is kept until Clear, so a player can undo back to the start of a level however long they played.

In-game editors, such as level makers and character creators, get three more tools. DoMerge folds a move into the latest one when it is a Merger that accepts it, so one drag of a slider is one move to undo. Limit bounds how many moves are kept, forgetting the oldest applied ones first. MarkSaved and Dirty track whether the state differs from the last saved one, and Version identifies the current point in the history.

Each Move both applies and reverts its change, so undoing every move returns the state to exactly where it started as long as each Revert is the exact inverse of its Apply. A move may record what its Apply changed (the crate it pushed, the piece it captured) in its own fields and read it back in Revert.

A History whose moves are one concrete type can be saved as a versioned YAML Log and restored from it, which replays the applied moves on the starting state and keeps the undone ones for Redo.

Nothing in undo reads the clock, spawns goroutines or keeps package-level state.

Index

Examples

Constants

View Source
const LogVersion = 2

LogVersion is the schema version of the Log YAML format this package reads and writes. Version 2 adds the forgotten key; version 1 logs, which predate History.Limit and so forgot nothing, are still read.

Variables

This section is empty.

Functions

func EncodeLog

func EncodeLog[M any](log Log[M]) ([]byte, error)

EncodeLog validates log and writes it as deterministic 2-space YAML of the current version: a log read from an older version is saved in the current form.

Types

type Func

type Func[S any] struct {
	Do   func(state S) // makes the change
	Undo func(state S) // takes the change back
}

Func is a Move made of two functions, for moves that close over what they change.

func (Func[S]) Apply

func (f Func[S]) Apply(state S)

Apply calls f.Do.

func (Func[S]) Revert

func (f Func[S]) Revert(state S)

Revert calls f.Undo.

type Group

type Group[S any] []Move[S]

Group is a Move made of several moves that undo and redo as one, such as a turn that moves a piece and captures another. It applies its moves in order and reverts them in reverse order.

func (Group[S]) Apply

func (g Group[S]) Apply(state S)

Apply applies each move of g in order.

func (Group[S]) Revert

func (g Group[S]) Revert(state S)

Revert reverts each move of g in reverse order.

type History

type History[S any, M Move[S]] struct {
	// OnChange, when set, is called after each call that applies or reverts moves or forgets them, so a game can update its undo and redo buttons.
	OnChange func()

	// Limit, when positive, is the most moves kept. As a new move is recorded past the limit, the oldest applied moves are forgotten: their effects stay in the state but they can no longer be undone, and Seek and a Log count from the oldest kept move. Zero keeps every move.
	Limit int
	// contains filtered or unexported fields
}

History holds a game's state and the moves made on it, with linear undo and redo. Every move is kept until Clear unless Limit is set.

M is the type of the moves: Move[S] for moves of several kinds, or one concrete move type, which lets the history be saved as a Log. A History is not safe for concurrent use.

Example
package main

import (
	"fmt"

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

func main() {
	type counter struct{ N int }
	add := func(d int) undo.Move[*counter] {
		return undo.Func[*counter]{
			Do:   func(c *counter) { c.N += d },
			Undo: func(c *counter) { c.N -= d },
		}
	}
	c := &counter{}
	h := undo.New[*counter, undo.Move[*counter]](c)
	h.Do(add(5))
	h.Do(add(3))
	h.Undo()
	fmt.Println(c.N, h.CanRedo())
	h.Redo()
	h.Seek(0)
	fmt.Println(c.N, h.Applied(), h.Len())
}
Output:
5 true
0 0 2

func New

func New[S any, M Move[S]](state S) *History[S, M]

New returns an empty History over state, the game's starting state.

func Restore

func Restore[S any, M Move[S]](state S, log Log[M]) (*History[S, M], error)

Restore returns a History over state, the starting state the log was recorded from (the state given to New, or the state at the history's last Clear), with the log's moves: it applies the first log.Applied moves to state in order and keeps the rest for Redo. OnChange is not called.

A log whose Limit forgot moves cannot be restored: the forgotten moves' effects are part of the history's state but not of the starting state the log was recorded from, and the log no longer holds the moves that would replay them. Clear the history and save the state at the Clear with the log, as after any Clear, so the next log forgets nothing.

func (*History[S, M]) Applied

func (h *History[S, M]) Applied() int

Applied returns the number of moves applied, which is the index of the move Redo would apply.

func (*History[S, M]) CanRedo

func (h *History[S, M]) CanRedo() bool

CanRedo reports whether Redo has a move to apply again.

func (*History[S, M]) CanUndo

func (h *History[S, M]) CanUndo() bool

CanUndo reports whether Undo has a move to revert.

func (*History[S, M]) Clear

func (h *History[S, M]) Clear()

Clear forgets every move and keeps the state as it is, which becomes the new starting state. A Log taken after Clear holds only the later moves, so a game that saves it must also save the state at the Clear and pass that to Restore. The saved point is forgotten with the moves, so the history is dirty until the next MarkSaved.

func (*History[S, M]) Dirty

func (h *History[S, M]) Dirty() bool

Dirty reports whether the state differs from the one MarkSaved saw: the current point is not the saved one, or no point was ever marked. It compares positions, so undoing or redoing back to the saved point reports clean. Once Limit forgets moves past the saved point or a new move discards the branch the saved point was on, the point is unreachable and the history stays dirty until the next MarkSaved.

func (*History[S, M]) Do

func (h *History[S, M]) Do(m M)

Do applies m to the state and records it as the latest move, discarding any moves that were undone and not redone. It panics, before applying anything, if m is nil or is a Group holding a nil move; a nil or empty Group is a valid move that changes nothing.

func (*History[S, M]) DoMerge

func (h *History[S, M]) DoMerge(m M)

DoMerge applies m to the state like Do, then folds it into the latest applied move when that move is a Merger whose Merge accepts it, so the steps of one drag become one move to undo. A refused merge, or one after EndMerge or MarkSaved, records m as a move of its own.

func (*History[S, M]) EndMerge

func (h *History[S, M]) EndMerge()

EndMerge ends the current merge run: the next DoMerge starts a new move even if the latest one would accept it. Call it when a drag ends, so the next drag of the same slider or object does not fold into this one's move.

func (*History[S, M]) Len

func (h *History[S, M]) Len() int

Len returns the number of moves recorded, applied and undone.

func (*History[S, M]) Log

func (h *History[S, M]) Log() Log[M]

Log returns the history's moves as a Log of the current version. The slice is a copy, but moves that are pointers are shared with the history.

func (*History[S, M]) MarkSaved

func (h *History[S, M]) MarkSaved()

MarkSaved records the current point as the saved one, for an in-game editor's "unsaved changes" mark, and ends the current merge run as EndMerge does, so the first DoMerge after a save cannot rewrite the move the saved point rests on.

func (*History[S, M]) Moves

func (h *History[S, M]) Moves() []M

Moves returns a copy of the recorded moves in the order they were made; the first Applied of them are applied.

func (*History[S, M]) Redo

func (h *History[S, M]) Redo() bool

Redo applies the latest undone move again and reports whether there was one.

func (*History[S, M]) Seek

func (h *History[S, M]) Seek(n int)

Seek undoes or redoes moves until n moves are applied: Seek(0) returns to the starting state (the oldest kept one, when Limit forgot moves) and Seek(h.Len()) redoes every move. It panics if n is outside [0, h.Len()].

func (*History[S, M]) State

func (h *History[S, M]) State() S

State returns the state the history's moves change.

func (*History[S, M]) Undo

func (h *History[S, M]) Undo() bool

Undo reverts the latest applied move and reports whether there was one.

func (*History[S, M]) Version

func (h *History[S, M]) Version() uint64

Version identifies the current point in the history: it changes on every Do, Undo, Redo, Seek and Clear, and a DoMerge that starts a new move counts as a Do. A DoMerge that folds into the latest move keeps the version, since that move's place in the history is unchanged.

type Log

type Log[M any] struct {
	Version   int `yaml:"version"`   // LogVersion; version 1 is read as 2 with no forgotten moves
	Applied   int `yaml:"applied"`   // moves applied, in [0, len(Moves)]
	Forgotten int `yaml:"forgotten"` // moves a History.Limit forgot before Moves; written since version 2
	Moves     []M `yaml:"moves"`     // every recorded move, applied first
}

Log is the saved form of a History: its moves in order, how many of them are applied and how many a Limit forgot before them. It does not hold the starting state, which is the state given to New or, after a Clear, the state at that Clear; a game saves that state with the log and passes it to Restore. It is written as YAML with its fields in the order below, the first three and moves required:

version: 2
applied: 2
forgotten: 0
moves:
  - dir: left
  - dir: up
  - dir: up

M must be a concrete type the YAML package encodes and decodes, keeping what a move records during Apply in unexported fields or fields tagged `yaml:"-"`, so a Log holds only what a player chose.

func DecodeLog

func DecodeLog[M any](data []byte) (Log[M], error)

DecodeLog reads a YAML Log and validates it. Missing version, applied or moves keys, a null moves list, unknown fields, in the log or in its moves, and trailing YAML documents are refused.

func (Log[M]) Validate

func (l Log[M]) Validate() error

Validate reports whether l has a supported version, an applied count within its moves and no forgotten moves a version 1 log cannot hold.

type Merger

type Merger[M any] interface {
	// Merge folds next into the receiver and reports whether it did; next is already applied to the state, so a refused merge leaves both moves in place.
	Merge(next M) bool
}

Merger is a move that can absorb the next one of its kind, such as two steps of one drag of a slider or an object. History.DoMerge folds a move into the latest applied move when that move is a Merger whose Merge accepts it.

type Move

type Move[S any] interface {
	Apply(state S)
	Revert(state S)
}

Move is one reversible change to a game's state S, which is usually a pointer to the game's board or world.

Apply makes the change and Revert takes it back; Revert(s) after Apply(s) must leave s exactly as it was before Apply. Apply may store what it needs to revert in the move itself (a move with a pointer receiver), since a History applies a move again on Redo only to the same state it first saw. Neither method may call the History that holds the move.

Jump to

Keyboard shortcuts

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