stockfish

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2026 License: MIT Imports: 11 Imported by: 1 module, 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.

README

Stockfish Go

Tests codecov Go Report Card Go Reference

A Go wrapper library for the Stockfish chess engine implementing the Universal Chess Interface (UCI) protocol. Provides a clean, idiomatic Go API for launching and communicating with the Stockfish process, setting options, configuring positions, streaming search results, and issuing both standard and non-standard UCI commands.

Installation

go get github.com/ksysoev/stockfish@latest

Usage

Basic setup

Launch the engine, print its name and author, then close it cleanly.

package main

import (
	"fmt"
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	fmt.Println("Engine:", client.Name())
	fmt.Println("Author:", client.Author())
}

Set the starting position, run a search to depth 15, and print the principal variation at each depth along with the final best move.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	if err = client.SetPosition(stockfish.StartPosition()); err != nil {
		log.Fatal(err)
	}

	ch, err := client.Go(context.Background(), &stockfish.SearchParams{Depth: 15})
	if err != nil {
		log.Fatal(err)
	}

	for info := range ch {
		if info.IsBestMove {
			fmt.Println("Best move:", info.BestMove)
			break
		}
		fmt.Printf("depth=%-3d score=%d cp  pv=%s\n",
			info.Depth, info.Score.Value, strings.Join(info.PV, " "))
	}
}
Configuring options

Pass one or more typed option constructors to Apply. Each constructor validates the value against the engine's reported metadata (type, min/max bounds, allowed combo values) before sending the command.

package main

import (
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	if err = client.Apply(
		stockfish.WithThreads(4),
		stockfish.WithHash(256),
		stockfish.WithClearHash(),
	); err != nil {
		log.Fatal(err)
	}
}

Available named constructors:

Constructor UCI type Option name
WithThreads(n int) spin Threads
WithHash(mb int) spin Hash
WithPonder(v bool) check Ponder
WithMultiPV(n int) spin MultiPV
WithSkillLevel(n int) spin Skill Level
WithMoveOverhead(ms int) spin Move Overhead
WithClearHash() button Clear Hash
WithUCIChess960(v bool) check UCI_Chess960
WithSyzygyPath(path string) string SyzygyPath
WithUCIAnalyseMode(v bool) check UCI_AnalyseMode

For any other engine option use the generic constructors directly:

client.Apply(
    stockfish.WithSpinOption("Minimum Thinking Time", 20),
    stockfish.WithComboOption("NumaPolicy", "auto"),
    stockfish.WithStringOption("Debug Log File", "/tmp/sf.log"),
    stockfish.WithButtonOption("Clear Hash"),
)
Starting a new game

Call NewGame between games to reset the engine's transposition table and search history so that previous analysis does not influence the new game.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	for _, moves := range [][]string{
		{"e2e4", "e7e5"},
		{"d2d4", "d7d5"},
	} {
		if err = client.NewGame(); err != nil {
			log.Fatal(err)
		}

		pos := stockfish.StartPosition().WithMoves(moves...)
		if err = client.SetPosition(pos); err != nil {
			log.Fatal(err)
		}

		ch, err := client.Go(context.Background(), &stockfish.SearchParams{Depth: 10})
		if err != nil {
			log.Fatal(err)
		}

		for info := range ch {
			if info.IsBestMove {
				fmt.Printf("moves=%v  best=%s\n", moves, info.BestMove)
				break
			}
		}
	}
}

License

Stockfish Go is licensed under the MIT License. See the LICENSE file for more details.

Documentation

Overview

Package stockfish provides a Go wrapper for the Stockfish chess engine, implementing the Universal Chess Interface (UCI) protocol.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEngineNotRunning = errors.New("engine is not running")

ErrEngineNotRunning is returned when an operation is attempted on an engine that has not been started or has already been stopped.

View Source
var ErrEngineTimeout = errors.New("engine response timed out")

ErrEngineTimeout is returned when the engine does not respond within the expected time frame.

View Source
var ErrNoSearchInProgress = errors.New("no search in progress")

ErrNoSearchInProgress is returned when Stop or PonderHit is called but no search is currently running.

View Source
var ErrSearchInProgress = errors.New("search already in progress")

ErrSearchInProgress is returned when a new search command is issued while another search is already running.

Functions

This section is empty.

Types

type BenchParams

type BenchParams struct {
	FENFile   string
	LimitType string
	TTSize    int
	Threads   int
	Limit     int
}

BenchParams configures the "bench" non-standard UCI command.

type Client

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

Client is a high-level UCI client that manages the lifecycle of a Stockfish engine process and provides methods for all standard and non-standard UCI commands.

A Client must be created with New and must be closed with Close when no longer needed to release the underlying process resources.

func New

func New(path string, opts ...Option) (*Client, error)

New launches the Stockfish binary at path, performs the UCI handshake, and returns a ready-to-use Client. The caller must call Close to release resources.

Optional opts are applied immediately after the handshake completes, before the Client is returned. If any option fails the engine is shut down and the error is returned.

Example

ExampleNew demonstrates launching the engine, reading its identity, and shutting it down cleanly.

package main

import (
	"fmt"
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Engine:", client.Name())
	fmt.Println("Author:", client.Author())

	if err = client.Close(); err != nil {
		log.Fatal(err)
	}
}
Example (WithOptions)

ExampleNew_withOptions demonstrates launching the engine and applying typed options in a single call so the client is fully configured before use.

package main

import (
	"fmt"
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New(
		"/usr/local/bin/stockfish",
		stockfish.WithThreads(4),
		stockfish.WithHash(256),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Engine:", client.Name())

	if err = client.Close(); err != nil {
		log.Fatal(err)
	}
}

func (*Client) Apply

func (c *Client) Apply(opts ...Option) error

Apply applies one or more Options to the engine. Each Option validates and sends the corresponding "setoption" UCI command. Options are applied in the order they are provided; the first error aborts the remaining options.

Returns ErrEngineNotRunning if the client has been closed. Returns ErrSearchInProgress if a search is active. Returns ErrOptionNotFound if an option name is not among those reported by the engine during initialisation. Returns ErrOptionTypeMismatch if the value type does not match the option's UCI type. Returns ErrOptionOutOfRange if a spin value falls outside [Min, Max]. Returns ErrOptionInvalidValue if a combo value is not in the allowed set.

Example

ExampleClient_Apply demonstrates configuring engine options before starting a search using the typed option constructors.

package main

import (
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}

	// Set thread count and hash table size, then clear the hash table.
	if err = client.Apply(
		stockfish.WithThreads(4),
		stockfish.WithHash(256),
		stockfish.WithClearHash(),
	); err != nil {
		log.Fatal(err)
	}

	if err = client.Close(); err != nil {
		log.Fatal(err)
	}
}

func (*Client) Author

func (c *Client) Author() string

Author returns the engine author as reported by the "id author" UCI response.

func (*Client) Bench

func (c *Client) Bench(params BenchParams) ([]string, error)

Bench runs the non-standard "bench" command and returns the raw output lines. It blocks until the "===" summary terminator line is received.

func (*Client) Close

func (c *Client) Close() error

Close sends "quit" to the engine and waits for the process to exit, releasing all resources. It is safe to call Close multiple times; subsequent calls return nil immediately.

func (*Client) Compiler

func (c *Client) Compiler() (string, error)

Compiler sends the non-standard "compiler" command and returns the compiler information string.

func (*Client) Display

func (c *Client) Display() (string, error)

Display sends the non-standard "d" command and returns the board display output as a single string.

func (*Client) Eval

func (c *Client) Eval() (string, error)

Eval sends the non-standard "eval" command and returns the full output as a single string.

func (*Client) ExportNet

func (c *Client) ExportNet(bigNet, smallNet string) error

ExportNet sends the non-standard "export_net" command. Pass empty strings for bigNet and smallNet to export the embedded networks with their default names.

func (*Client) Flip

func (c *Client) Flip() error

Flip sends the non-standard "flip" command which flips the side to move.

func (*Client) Go

func (c *Client) Go(ctx context.Context, params *SearchParams) (<-chan SearchInfo, error)

Go starts a search using the given parameters. It returns a read-only channel that streams SearchInfo values as the engine emits "info" lines, ending with a final SearchInfo where IsBestMove is true (containing BestMove and optionally PonderMove). The channel is closed after the bestmove line.

params may be nil, in which case a default (unlimited) search is started.

The search can be cancelled early by cancelling ctx, which will cause Stop to be sent automatically. On cancellation the bestmove is drained internally and the channel is closed without delivering a final bestmove entry.

Returns ErrEngineNotRunning if the client has been closed.

Example

ExampleClient_Go demonstrates setting the starting position, running a depth-limited search, and printing the principal variation at each depth together with the final best move.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}

	if err = client.SetPosition(stockfish.StartPosition()); err != nil {
		log.Fatal(err)
	}

	ch, err := client.Go(context.Background(), &stockfish.SearchParams{Depth: 15})
	if err != nil {
		log.Fatal(err)
	}

	for info := range ch {
		if info.IsBestMove {
			fmt.Println("Best move:", info.BestMove)
			break
		}

		fmt.Printf("depth=%-3d score=%d cp  pv=%s\n",
			info.Depth, info.Score.Value, strings.Join(info.PV, " "))
	}

	if err = client.Close(); err != nil {
		log.Fatal(err)
	}
}

func (*Client) IsReady

func (c *Client) IsReady() error

IsReady sends "isready" and waits for "readyok". This synchronises the client with the engine after any potentially slow operation.

func (*Client) Name

func (c *Client) Name() string

Name returns the engine name as reported by the "id name" UCI response.

func (*Client) NewGame

func (c *Client) NewGame() error

NewGame sends "ucinewgame" followed by "isready" to prepare the engine for a new game. This clears the engine's transposition table and search history.

Example

ExampleClient_NewGame demonstrates resetting the engine between games to clear the transposition table and search history.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ksysoev/stockfish"
)

func main() {
	client, err := stockfish.New("/usr/local/bin/stockfish")
	if err != nil {
		log.Fatal(err)
	}

	games := [][]string{
		{"e2e4", "e7e5"},
		{"d2d4", "d7d5"},
	}

	for _, moves := range games {
		if err = client.NewGame(); err != nil {
			log.Fatal(err)
		}

		pos := stockfish.StartPosition().WithMoves(moves...)
		if err = client.SetPosition(pos); err != nil {
			log.Fatal(err)
		}

		ch, err := client.Go(context.Background(), &stockfish.SearchParams{Depth: 10})
		if err != nil {
			log.Fatal(err)
		}

		for info := range ch {
			if info.IsBestMove {
				fmt.Printf("moves=%v  best=%s\n", moves, info.BestMove)
				break
			}
		}
	}

	if err = client.Close(); err != nil {
		log.Fatal(err)
	}
}

func (*Client) Options

func (c *Client) Options() map[string]OptionInfo

Options returns a copy of the UCI options map discovered during initialisation. Keys are option names.

func (*Client) PonderHit

func (c *Client) PonderHit() error

PonderHit sends the "ponderhit" command, switching the engine from pondering to normal search mode.

func (*Client) SetPosition

func (c *Client) SetPosition(pos Position) error

SetPosition sends a "position" command to the engine. Returns ErrEngineNotRunning if the client has been closed. Returns ErrSearchInProgress if a search is active.

func (*Client) Stop

func (c *Client) Stop() error

Stop sends the "stop" command to the engine, ending the current search. The search channel returned by Go will receive the final bestmove and then be closed.

type ErrInvalidPosition

type ErrInvalidPosition struct {
	Detail string
}

ErrInvalidPosition is returned when a malformed FEN string or invalid move is provided to SetPosition.

func (*ErrInvalidPosition) Error

func (e *ErrInvalidPosition) Error() string

Error implements the error interface.

type ErrOptionInvalidCharacters

type ErrOptionInvalidCharacters struct {
	Name  string
	Value string
}

ErrOptionInvalidCharacters is returned when an option value contains characters that are not permitted, such as CR or LF in string options.

func (*ErrOptionInvalidCharacters) Error

Error implements the error interface.

type ErrOptionInvalidValue

type ErrOptionInvalidValue struct {
	Name    string
	Value   string
	Allowed []string
}

ErrOptionInvalidValue is returned when a combo option value is not among the allowed variants reported by the engine.

func (*ErrOptionInvalidValue) Error

func (e *ErrOptionInvalidValue) Error() string

Error implements the error interface.

type ErrOptionNotFound

type ErrOptionNotFound struct {
	Name string
}

ErrOptionNotFound is returned when an option name is not among the options reported by the engine during initialisation.

func (*ErrOptionNotFound) Error

func (e *ErrOptionNotFound) Error() string

Error implements the error interface.

type ErrOptionOutOfRange

type ErrOptionOutOfRange struct {
	Name  string
	Value int
	Min   int
	Max   int
}

ErrOptionOutOfRange is returned when a spin option value falls outside the [Min, Max] bounds reported by the engine.

func (*ErrOptionOutOfRange) Error

func (e *ErrOptionOutOfRange) Error() string

Error implements the error interface.

type ErrOptionTypeMismatch

type ErrOptionTypeMismatch struct {
	Name     string
	Expected OptionType
	Got      OptionType
}

ErrOptionTypeMismatch is returned when a typed option constructor is applied to an option whose UCI type differs from the expected type.

func (*ErrOptionTypeMismatch) Error

func (e *ErrOptionTypeMismatch) Error() string

Error implements the error interface.

type ErrUnexpectedResponse

type ErrUnexpectedResponse struct {
	Line string
}

ErrUnexpectedResponse is returned when the engine returns output that does not conform to the expected UCI format.

func (*ErrUnexpectedResponse) Error

func (e *ErrUnexpectedResponse) Error() string

Error implements the error interface.

type Option

type Option func(*Client) error

Option is a functional option that configures a Client by sending a "setoption" UCI command. It validates the value against the engine's reported metadata before sending.

func WithButtonOption

func WithButtonOption(name string) Option

WithButtonOption returns an Option that triggers any button-type UCI option by name. It validates that the option exists and is of type button.

func WithCheckOption

func WithCheckOption(name string, value bool) Option

WithCheckOption returns an Option that sets any check-type UCI option by name. It validates that the option exists and is of type check.

func WithClearHash

func WithClearHash() Option

WithClearHash returns an Option that triggers the "Clear Hash" button option, clearing the engine's transposition table.

func WithComboOption

func WithComboOption(name, value string) Option

WithComboOption returns an Option that sets any combo-type UCI option by name. It validates that:

  • the option exists on the engine,
  • the option is of type combo,
  • value is one of the engine's reported Vars.

func WithHash

func WithHash(mb int) Option

WithHash returns an Option that sets the "Hash" spin option (hash table size in MB). The value must be within the engine's reported [Min, Max] range.

func WithMoveOverhead

func WithMoveOverhead(ms int) Option

WithMoveOverhead returns an Option that sets the "Move Overhead" spin option (time in ms to reserve per move for network/GUI overhead). The value must be within the engine's reported [Min, Max] range.

func WithMultiPV

func WithMultiPV(n int) Option

WithMultiPV returns an Option that sets the "MultiPV" spin option (number of principal variations to search). The value must be within the engine's reported [Min, Max] range.

func WithPonder

func WithPonder(v bool) Option

WithPonder returns an Option that sets the "Ponder" check option.

func WithSkillLevel

func WithSkillLevel(n int) Option

WithSkillLevel returns an Option that sets the "Skill Level" spin option. The value must be within the engine's reported [Min, Max] range.

func WithSpinOption

func WithSpinOption(name string, value int) Option

WithSpinOption returns an Option that sets any spin-type UCI option by name. It validates that:

  • the option exists on the engine,
  • the option is of type spin,
  • value is within the engine's [Min, Max] bounds.

func WithStringOption

func WithStringOption(name, value string) Option

WithStringOption returns an Option that sets any string-type UCI option by name. It validates that the option exists and is of type string.

The value must not contain CR or LF characters, as these would allow injecting additional UCI commands into the engine's stdin stream.

func WithSyzygyPath

func WithSyzygyPath(path string) Option

WithSyzygyPath returns an Option that sets the "SyzygyPath" string option.

func WithThreads

func WithThreads(n int) Option

WithThreads returns an Option that sets the "Threads" spin option. The value must be within the engine's reported [Min, Max] range.

func WithUCIAnalyseMode

func WithUCIAnalyseMode(v bool) Option

WithUCIAnalyseMode returns an Option that sets the "UCI_AnalyseMode" check option, enabling analysis mode in the engine.

func WithUCIChess960

func WithUCIChess960(v bool) Option

WithUCIChess960 returns an Option that sets the "UCI_Chess960" check option.

type OptionInfo

type OptionInfo struct {
	Name    string
	Type    OptionType
	Default string
	Vars    []string
	Min     int
	Max     int
}

OptionInfo describes a single UCI engine option as reported during initialisation.

type OptionType

type OptionType string

OptionType represents the UCI option type as reported by the engine.

const (
	// OptionTypeSpin represents a numeric option with min/max bounds.
	OptionTypeSpin OptionType = "spin"
	// OptionTypeCheck represents a boolean (true/false) option.
	OptionTypeCheck OptionType = "check"
	// OptionTypeString represents a free-form string option.
	OptionTypeString OptionType = "string"
	// OptionTypeButton represents a button option with no value.
	OptionTypeButton OptionType = "button"
	// OptionTypeCombo represents an option with a fixed set of allowed values.
	OptionTypeCombo OptionType = "combo"
)

type Position

type Position struct {
	// FEN is the Forsyth-Edwards Notation string for the position.
	// Leave empty when StartPos is true.
	FEN string
	// Moves is the list of moves played from the base position in long
	// algebraic notation (e.g. "e2e4", "g1f3").
	Moves []string
	// StartPos indicates that the position is the standard chess starting
	// position. When true, FEN is ignored.
	StartPos bool
}

Position represents a chess position that can be sent to the engine using the "position" UCI command. Either StartPos or FEN must be set, but not both.

func FENPosition

func FENPosition(fen string) Position

FENPosition returns a Position set to the given FEN string with no moves applied.

func StartPosition

func StartPosition() Position

StartPosition returns a Position set to the standard chess starting position with no moves applied.

func (Position) WithMoves

func (p Position) WithMoves(moves ...string) Position

WithMoves returns a copy of the position with the given moves appended.

type Score

type Score struct {
	// Type indicates whether Value is in centipawns or mate-in-N.
	Type ScoreType
	// Bound indicates whether the score is exact, a lower bound, or an upper bound.
	// ScoreBoundExact (empty string) means the score is the exact minimax value.
	Bound ScoreBound
	// Value is the numeric score (centipawns or mate-in-N).
	Value int
}

Score holds the evaluation score from a search info line.

type ScoreBound

type ScoreBound string

ScoreBound indicates whether the score is an exact value or a bound.

const (
	// ScoreBoundExact means the score is the exact minimax value.
	ScoreBoundExact ScoreBound = ""
	// ScoreBoundLower means the score is a lower bound (fail-high) on the true value.
	ScoreBoundLower ScoreBound = "lowerbound"
	// ScoreBoundUpper means the score is an upper bound (fail-low) on the true value.
	ScoreBoundUpper ScoreBound = "upperbound"
)

type ScoreType

type ScoreType string

ScoreType indicates whether the score is in centipawns or mate distance.

const (
	// ScoreTypeCentipawns means the score is in centipawns.
	ScoreTypeCentipawns ScoreType = "cp"
	// ScoreTypeMate means the score is mate-in-N (negative = being mated).
	ScoreTypeMate ScoreType = "mate"
)

type SearchInfo

type SearchInfo struct {
	WDL            *WDL
	BestMove       string
	PonderMove     string
	CurrMove       string
	Score          Score
	PV             []string
	NPS            int64
	Nodes          int64
	HashFull       int64
	TBHits         int64
	Time           int64
	Depth          int
	SelDepth       int
	MultiPV        int
	CurrMoveNumber int
	IsBestMove     bool
}

SearchInfo represents a single info line (or the final bestmove line) emitted by the engine during a search.

type SearchParams

type SearchParams struct {
	// SearchMoves restricts the search to only these moves (long algebraic notation).
	SearchMoves []string
	// WTime is the time White has remaining on the clock.
	WTime time.Duration
	// BTime is the time Black has remaining on the clock.
	BTime time.Duration
	// WInc is White's increment per move.
	WInc time.Duration
	// BInc is Black's increment per move.
	BInc time.Duration
	// MoveTime limits search to this duration.
	MoveTime time.Duration
	// MovesToGo is the number of moves remaining until the next time control.
	MovesToGo int
	// Depth limits search to this ply depth.
	Depth int
	// Nodes limits search to approximately this many nodes.
	Nodes int
	// Mate stops the search when a mate in this many moves is found.
	Mate int
	// Perft runs perft to this depth instead of a normal search.
	Perft int
	// Ponder starts the search in pondering mode.
	Ponder bool
	// Infinite starts an unbounded search; only stops on an explicit Stop().
	Infinite bool
}

SearchParams configures a "go" UCI command. At least one limiting parameter should be set; if none are set the engine will search with depth 245 (its internal default for unlimited search).

type WDL

type WDL struct {
	Win  int
	Draw int
	Loss int
}

WDL holds the Win/Draw/Loss statistics from a search info line (requires UCI_ShowWDL to be enabled).

Jump to

Keyboard shortcuts

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