Documentation
¶
Overview ¶
Package stockfish provides a Go wrapper for the Stockfish chess engine, implementing the Universal Chess Interface (UCI) protocol.
Index ¶
- Variables
- type BenchParams
- type Client
- func (c *Client) Apply(opts ...Option) error
- func (c *Client) Author() string
- func (c *Client) Bench(params BenchParams) ([]string, error)
- func (c *Client) Close() error
- func (c *Client) Compiler() (string, error)
- func (c *Client) Display() (string, error)
- func (c *Client) Eval() (string, error)
- func (c *Client) ExportNet(bigNet, smallNet string) error
- func (c *Client) Flip() error
- func (c *Client) Go(ctx context.Context, params *SearchParams) (<-chan SearchInfo, error)
- func (c *Client) IsReady() error
- func (c *Client) Name() string
- func (c *Client) NewGame() error
- func (c *Client) Options() map[string]OptionInfo
- func (c *Client) PonderHit() error
- func (c *Client) SetPosition(pos Position) error
- func (c *Client) Stop() error
- type ErrInvalidPosition
- type ErrOptionInvalidCharacters
- type ErrOptionInvalidValue
- type ErrOptionNotFound
- type ErrOptionOutOfRange
- type ErrOptionTypeMismatch
- type ErrUnexpectedResponse
- type Option
- func WithButtonOption(name string) Option
- func WithCheckOption(name string, value bool) Option
- func WithClearHash() Option
- func WithComboOption(name, value string) Option
- func WithHash(mb int) Option
- func WithMoveOverhead(ms int) Option
- func WithMultiPV(n int) Option
- func WithPonder(v bool) Option
- func WithSkillLevel(n int) Option
- func WithSpinOption(name string, value int) Option
- func WithStringOption(name, value string) Option
- func WithSyzygyPath(path string) Option
- func WithThreads(n int) Option
- func WithUCIAnalyseMode(v bool) Option
- func WithUCIChess960(v bool) Option
- type OptionInfo
- type OptionType
- type Position
- type Score
- type ScoreBound
- type ScoreType
- type SearchInfo
- type SearchParams
- type WDL
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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.
var ErrEngineTimeout = errors.New("engine response timed out")
ErrEngineTimeout is returned when the engine does not respond within the expected time frame.
var ErrNoSearchInProgress = errors.New("no search in progress")
ErrNoSearchInProgress is returned when Stop or PonderHit is called but no search is currently running.
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 ¶
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 ¶
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)
}
}
Output:
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)
}
}
Output:
func (*Client) Apply ¶
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)
}
}
Output:
func (*Client) Author ¶
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 ¶
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 ¶
Compiler sends the non-standard "compiler" command and returns the compiler information string.
func (*Client) Display ¶
Display sends the non-standard "d" command and returns the board display output as a single string.
func (*Client) Eval ¶
Eval sends the non-standard "eval" command and returns the full output as a single string.
func (*Client) ExportNet ¶
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) 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)
}
}
Output:
func (*Client) IsReady ¶
IsReady sends "isready" and waits for "readyok". This synchronises the client with the engine after any potentially slow operation.
func (*Client) NewGame ¶
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)
}
}
Output:
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 ¶
PonderHit sends the "ponderhit" command, switching the engine from pondering to normal search mode.
func (*Client) SetPosition ¶
SetPosition sends a "position" command to the engine. Returns ErrEngineNotRunning if the client has been closed. Returns ErrSearchInProgress if a search is active.
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 ¶
ErrOptionInvalidCharacters is returned when an option value contains characters that are not permitted, such as CR or LF in string options.
func (*ErrOptionInvalidCharacters) Error ¶
func (e *ErrOptionInvalidCharacters) Error() string
Error implements the error interface.
type ErrOptionInvalidValue ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithPonder returns an Option that sets the "Ponder" check option.
func WithSkillLevel ¶
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 ¶
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 ¶
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 ¶
WithSyzygyPath returns an Option that sets the "SyzygyPath" string option.
func WithThreads ¶
WithThreads returns an Option that sets the "Threads" spin option. The value must be within the engine's reported [Min, Max] range.
func WithUCIAnalyseMode ¶
WithUCIAnalyseMode returns an Option that sets the "UCI_AnalyseMode" check option, enabling analysis mode in the engine.
func WithUCIChess960 ¶
WithUCIChess960 returns an Option that sets the "UCI_Chess960" check option.
type OptionInfo ¶
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 ¶
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.
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.
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).