chessreview

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: GPL-2.0 Imports: 9 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

chess-review

Tests codecov Go Report Card Go Reference

A Go library for analyzing chess games using the Stockfish engine. It parses a PGN game, evaluates each position at a configurable depth, and returns a per-move review with move-quality classifications — similar to chess.com's game review feature.

Features

  • Parse PGN input via github.com/notnil/chess
  • Evaluate each position with Stockfish (N+1 engine calls for N plies — no redundant work)
  • Return the top N candidate moves (MultiPV) for each position with their centipawn scores
  • Classify moves as Best, Excellent, Good, Inaccuracy, Mistake, Blunder, or Miss (missed forced mate)
  • Configurable search depth, thread count, hash table size, and number of candidate moves
  • Typed errors with full errors.Is/errors.As chain support

Requirements

  • Go 1.26+
  • A Stockfish binary accessible on the system

Installation

go get github.com/ksysoev/chess-review

Usage

package main

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

    chessreview "github.com/ksysoev/chess-review"
)

func main() {
    pgn := `[Event "Example"]
[White "Alice"]
[Black "Bob"]
[Result "*"]

1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 *`

    reviewer, err := chessreview.New("/usr/local/bin/stockfish",
        chessreview.WithDepth(18),
        chessreview.WithThreads(2),
        chessreview.WithHash(64),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer reviewer.Close()

    reviews, err := reviewer.ReviewGame(context.Background(), pgn)
    if err != nil {
        log.Fatal(err)
    }

    for _, r := range reviews {
        bestMove := ""
        topParts := make([]string, 0, len(r.TopMoves))

        for _, m := range r.TopMoves {
            if bestMove == "" {
                bestMove = m.Move
            }

            if m.MateIn != nil {
                mate := *m.MateIn
                if mate > 0 {
                    topParts = append(topParts, fmt.Sprintf("%s(M%d)", m.Move, mate))
                } else {
                    topParts = append(topParts, fmt.Sprintf("%s(-M%d)", m.Move, -mate))
                }
            } else {
                topParts = append(topParts, fmt.Sprintf("%s(%+d)", m.Move, m.Score))
            }
        }

        fmt.Printf("Move %d (%s) %s → %s [%s]   top: %s\n",
            r.MoveNumber, r.Color, r.PlayedMove, bestMove, r.Classification,
            strings.Join(topParts, " "))
    }
}
Example output
Move 1 (white) e2e4 → e2e4 [Best]   top: e2e4(+18) d2d4(+15) g1f3(+10)
Move 1 (black) e7e5 → e7e5 [Best]   top: e7e5(+0) c7c5(-5) e7e6(-8)
Move 2 (white) g1f3 → g1f3 [Best]   top: g1f3(+25) f1c4(+22) b1c3(+18)
Move 2 (black) b8c6 → b8c6 [Best]   top: b8c6(+0) g8f6(-3) d7d6(-6)
Move 3 (white) f1c4 → f1c4 [Best]   top: f1c4(+30) f1b5(+28) d2d4(+20)
Move 3 (black) f8c5 → f8c5 [Best]   top: f8c5(+0) g8f6(-4) d7d6(-7)

API

New(stockfishPath string, opts ...Option) (*Reviewer, error)

Creates a new Reviewer backed by the Stockfish binary at stockfishPath. Returns *ErrEngineFailure if the engine cannot be started or the options are invalid.

(*Reviewer) ReviewGame(ctx context.Context, pgn string) ([]MoveReview, error)

Analyses every half-move in the PGN and returns a MoveReview slice. Errors:

  • *ErrInvalidPGN — PGN cannot be parsed or contains no moves
  • *ErrEngineFailure — communication with Stockfish failed
(*Reviewer) Close() error

Shuts down the underlying Stockfish process.

MoveReview
Field Type Description
PlayedMove string The move that was played, in UCI notation (e.g. e2e4)
TopMoves []MoveEvaluation Engine's top N candidate moves at the configured depth
Color string "white" or "black"
MoveNumber int Full-move number (1-indexed)
Classification Classification Quality rating of the played move
ScoreBefore int Centipawn score before the move (side-to-move frame)
ScoreAfter int Centipawn score after the move, from the perspective of the side that just moved (negated from the engine's output so both ScoreBefore and ScoreAfter share the same reference frame)
ScoreDelta int ScoreAfter − ScoreBefore; negative means loss
MoveEvaluation
Field Type Description
Move string Candidate move in UCI notation (e.g. e2e4)
Score int Centipawn evaluation from the side-to-move perspective
MateIn *int Moves to forced mate (nil if no forced mate; negative = mated)
Move classifications
Classification Centipawn loss
Best Played == engine best
Excellent 0–10 cp
Good 11–25 cp
Inaccuracy 26–100 cp
Mistake 101–300 cp
Blunder > 300 cp
Miss Missed forced mate (sentinel loss ≥ 20 000 cp)
Functional options
Option Default Description
WithDepth(n int) 18 Stockfish search depth (must be ≥ 1)
WithThreads(n int) 1 CPU threads for the engine (must be ≥ 1)
WithHash(mb int) 16 Transposition table size in MB (≥ 1)
WithTopMoves(n int) 3 Number of candidate moves to evaluate per position (≥ 1)

Development

make test    # run tests with race detector
make lint    # run golangci-lint
make fmt     # format with gofmt
make tidy    # go mod tidy
make mocks   # regenerate mocks with mockery
make fields  # fix struct field alignment

License

GPL 2.0

Documentation

Overview

Package chessreview provides chess game analysis powered by the Stockfish engine. It accepts a PGN game string, evaluates each position, and returns a per-move review with quality classifications for each move.

Each move is classified into one of seven categories: Best, Excellent, Good, Inaccuracy, Mistake, Blunder, or Miss (missed forced mate).

Package chessreview provides chess game analysis using the Stockfish engine.

Index

Constants

View Source
const (
	// DefaultDepth is the default Stockfish search depth used when no WithDepth
	// option is provided. It is exported so that callers (e.g. a CLI) can use it
	// as their own default without duplicating the value.
	DefaultDepth = 18
	// DefaultThreads is the default number of CPU threads Stockfish may use.
	// It is exported so that callers (e.g. a CLI) can use it as their own default.
	DefaultThreads = 1
	// DefaultHashMB is the default transposition table size in megabytes.
	// It is exported so that callers (e.g. a CLI) can use it as their own default.
	DefaultHashMB = 16
	// DefaultTopMoves is the default number of candidate moves (principal
	// variations) the engine evaluates per position. It is exported so that
	// callers (e.g. a CLI) can use it as their own default.
	DefaultTopMoves = 3
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Classification

type Classification int

Classification represents the quality rating of a chess move.

const (
	// Book indicates the move is part of known opening theory (ECO database).
	// Book moves are not judged by engine evaluation — they represent memorised
	// theory and are excluded from accuracy calculations.
	Book Classification = iota
	// Brilliant indicates a material sacrifice that is the engine's top choice,
	// improves or maintains the position after the sacrifice, and was made when
	// the position was not already clearly winning. Corresponds to the "!!"
	// annotation in standard chess notation.
	Brilliant
	// Great indicates a critical turning-point move: one that swings the position
	// from losing to equal/winning, or from equal to clearly winning, while also
	// keeping the win-probability loss within the Excellent threshold (≤ 2%).
	// These moves are decisive contributions that change the expected outcome of
	// the game without throwing away the newly gained advantage.
	Great
	// Best indicates the move matches the engine's top choice.
	Best
	// Excellent indicates a near-optimal move with minimal win-probability loss (0–2%).
	Excellent
	// Good indicates a solid move with small win-probability loss (2–5%).
	Good
	// Inaccuracy indicates a suboptimal move with noticeable win-probability loss (5–10%).
	Inaccuracy
	// Mistake indicates a poor move with significant win-probability loss (10–20%).
	Mistake
	// Blunder indicates a very bad move with severe win-probability loss (> 20%).
	Blunder
	// Miss indicates a move that misses an immediate winning tactic (e.g. missed mate).
	Miss
)

func Classify

func Classify(ctx ClassifyContext) Classification

Classify returns the move classification for the given context.

Classification priority (highest to lowest):

Book       – move is in the ECO opening book (theory)
Brilliant  – sacrifice that is the engine's top choice, improves or maintains
             the position (ScoreAfter >= ScoreBefore), not already clearly winning (< +2.00),
             and the sacrificed piece is not a pawn
Great      – critical turning-point: losing→equal/winning, or equal→clearly winning,
             AND win-probability loss ≤ 2% (excellentWinProbThreshold).
             Checked against both the immediate ScoreBefore (1-ply) and, when
             HasPrev is true, the same player's ScoreBefore from two half-moves
             ago (2-ply lookback) to capture moves that capitalise on an
             opponent blunder.
Best       – played move equals engine best (and not a qualifying sacrifice/turning-point)
Miss       – move throws away a forced mate (cp loss ≥ 20 000); checked before win-prob tiers
             because sentinel-based cp loss can produce misleading win-probability values
Excellent  – 0–2%  win-probability loss
Good       – 2–5%  win-probability loss
Inaccuracy – 5–10% win-probability loss
Mistake    – 10–20% win-probability loss
Blunder    – >20%  win-probability loss

func (Classification) String

func (c Classification) String() string

String returns a human-readable label for the classification.

type ClassifyContext

type ClassifyContext struct {
	// PlayedMove is the UCI move that was actually played (e.g. "e2e4").
	PlayedMove string
	// BestMove is the engine's top-recommended move at the configured depth.
	BestMove string
	// ScoreBefore is the centipawn evaluation immediately before the move, from
	// the perspective of the side to move.
	ScoreBefore int
	// ScoreAfter is the centipawn evaluation immediately after the move, from
	// the perspective of the side that just moved (same reference frame as
	// ScoreBefore — i.e. the engine score negated after the move).
	ScoreAfter int
	// ScoreBeforePrev is the same player's ScoreBefore from two half-moves ago
	// (i.e. the player's own ScoreBefore on their previous turn). It is used to
	// detect the "capitalise on opponent's blunder" variant of a Great move:
	// the player was in a losing or equal position on their last turn, but the
	// opponent's intervening blunder swung the game, and this move seizes the
	// newly won advantage. Only meaningful when HasPrev is true.
	ScoreBeforePrev int
	// HasPrev is true when ScoreBeforePrev is valid. It is false for the first
	// move of each colour (no prior turn to look back to).
	HasPrev bool
	// IsSacrifice is true when the move gives up material that the opponent can
	// immediately recapture. It is a necessary but not sufficient condition for
	// a Brilliant annotation: SacrificedPieceType must also be set and must not
	// be a pawn (pawn sacrifices are excluded from Brilliant).
	IsSacrifice bool
	// SacrificedPieceType is the type of the piece that was sacrificed when
	// IsSacrifice is true, and chess.NoPieceType otherwise. Pawn sacrifices are
	// excluded from the Brilliant classification — only non-pawn sacrifices qualify.
	SacrificedPieceType chess.PieceType
	// IsBook is true when the move is part of known opening theory (ECO
	// database). Book moves are returned immediately as Book — they are not
	// judged by engine evaluation.
	IsBook bool
}

ClassifyContext holds all inputs required to classify a single half-move. Using a struct keeps the Classify signature stable as new contextual fields are added in the future.

type ErrEngineFailure

type ErrEngineFailure struct {
	// Cause is the underlying error, if any.
	Cause  error
	Reason string
}

ErrEngineFailure is returned when communication with the Stockfish engine fails.

func (*ErrEngineFailure) Error

func (e *ErrEngineFailure) Error() string

Error implements the error interface.

func (*ErrEngineFailure) Unwrap

func (e *ErrEngineFailure) Unwrap() error

Unwrap returns the underlying cause so callers can use errors.Is/As.

type ErrInvalidPGN

type ErrInvalidPGN struct {
	// Cause is the underlying error, if any.
	Cause  error
	Reason string
}

ErrInvalidPGN is returned when the provided PGN string cannot be parsed.

func (*ErrInvalidPGN) Error

func (e *ErrInvalidPGN) Error() string

Error implements the error interface.

func (*ErrInvalidPGN) Unwrap

func (e *ErrInvalidPGN) Unwrap() error

Unwrap returns the underlying cause so callers can use errors.Is/As.

type GamePhase

type GamePhase int

GamePhase represents a named phase of a chess game based on move number.

const (
	// Opening covers moves 1–10.
	Opening GamePhase = iota
	// Middlegame covers moves 11–25.
	Middlegame
	// Endgame covers moves 26 and beyond.
	Endgame
)

type GameResult

type GameResult struct {
	Reviews []MoveReview
	Summary GameSummary
}

GameResult holds the full output of a game review: per-move analysis and an aggregated summary for both players.

type GameSummary

type GameSummary struct {
	WhitePlayer  string
	BlackPlayer  string
	OpeningCode  string
	OpeningTitle string
	White        PlayerSummary
	Black        PlayerSummary
}

GameSummary holds the aggregated summary for both players in a game.

func Summarize

func Summarize(reviews []MoveReview, whiteName, blackName, openingCode, openingTitle string) GameSummary

Summarize builds a GameSummary from a slice of MoveReviews, player names, and the ECO opening code and title detected from the game's moves. It computes per-color classification counts, overall accuracy (using the Lichess sliding-window algorithm), estimated game rating (logistic mapping), and per-phase accuracy (harmonic mean of per-move accuracies) for each player. Book moves are excluded from accuracy calculations because they represent memorised theory rather than the player's own decisions.

type MoveEvaluation added in v0.1.2

type MoveEvaluation struct {
	// MateIn is non-nil when this candidate leads to a forced-mate sequence.
	// Positive means the side to move mates in that many moves; negative means
	// they are being mated in that many moves. Nil when no forced mate is found.
	MateIn *int
	// Move is the candidate move in UCI notation (e.g. "e2e4").
	Move string
	// Score is the centipawn evaluation from the side-to-move perspective.
	Score int
}

MoveEvaluation holds the engine's evaluation for a single candidate move.

type MoveReview

type MoveReview struct {
	// MateInBefore is non-nil when the position before this move has a forced-mate
	// sequence. Positive means the side to move can force checkmate in that many
	// moves; negative means they are being mated in that many moves.
	MateInBefore *int
	// MateInAfter is non-nil when the position after this move has a forced-mate
	// sequence, expressed from the perspective of the side that just moved.
	// Positive means the side that just moved can still force checkmate in that many
	// moves; negative means the opponent now has the forced mate in that many moves.
	MateInAfter *int
	// PlayedMove is the move that was actually played, in UCI notation (e.g. "e2e4").
	PlayedMove string
	// Color is the side that played: "white" or "black".
	Color string
	// TopMoves is the engine's ordered list of candidate moves for the position
	// before this move was played (i.e. the pre-move position). TopMoves[0] is
	// always PV1 — the best continuation at the configured depth. The length is
	// controlled by WithTopMoves (default 3).
	TopMoves       []MoveEvaluation
	Classification Classification
	// ScoreBefore is the centipawn evaluation before the move, from the perspective
	// of the side to move.
	ScoreBefore int
	// ScoreAfter is the centipawn evaluation after the move, from the perspective
	// of the side that just moved (negated from the engine's output so both
	// ScoreBefore and ScoreAfter share the same reference frame).
	ScoreAfter int
	// ScoreDelta is the change in centipawns (ScoreAfter - ScoreBefore).
	// Negative values indicate centipawn loss.
	ScoreDelta int
	// MoveNumber is the full-move number (1-indexed; increments after Black's move).
	MoveNumber int
	// IsSacrifice is true when the move was detected as a material sacrifice:
	// the moved piece's value exceeds what was captured, and the opponent had
	// at least one legal recapture on the destination square.
	IsSacrifice bool
	// IsBook is true when the move is part of a known ECO opening line.
	// Book moves take priority over engine-based classifications and are
	// excluded from accuracy calculations.
	IsBook bool
}

MoveReview holds the analysis result for a single half-move (ply).

type Option

type Option func(*config)

Option is a functional option for configuring a Reviewer.

func WithDepth

func WithDepth(depth int) Option

WithDepth sets the search depth for engine analysis. Higher values produce stronger but slower analysis. The default depth is 18.

func WithHash

func WithHash(mb int) Option

WithHash sets the transposition table size in megabytes. Larger values can improve analysis quality at the cost of memory. The default is 16 MB.

func WithThreads

func WithThreads(threads int) Option

WithThreads sets the number of CPU threads the engine may use. The default is 1.

func WithTopMoves added in v0.1.2

func WithTopMoves(n int) Option

WithTopMoves sets the number of candidate moves (principal variations) the engine evaluates for each position. The result is available as MoveReview.TopMoves, ordered from best to worst. The default is 3.

type PlayerSummary

type PlayerSummary struct {
	// ClassificationCounts holds the count of each move classification.
	// Index with a Classification constant (e.g. ClassificationCounts[Brilliant]).
	ClassificationCounts [numClassifications]int
	// PhaseAccuracy holds accuracy percentages for each game phase.
	// Index with a GamePhase constant (e.g. PhaseAccuracy[Opening]).
	// A value of math.NaN() means the player had no moves in that phase.
	PhaseAccuracy [numPhases]float64
	// Accuracy is the overall accuracy percentage (0–100), computed using the
	// Lichess sliding-window volatility-weighted algorithm.
	Accuracy float64
	// GameRating is an estimated Elo-like rating derived from the accuracy score
	// using a logistic mapping.
	GameRating int
}

PlayerSummary holds per-player aggregated statistics derived from a game review.

type Reviewer

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

Reviewer analyses chess games using a Stockfish engine. It must be created with New; the zero value is not usable.

func New

func New(stockfishPath string, opts ...Option) (*Reviewer, error)

New creates a new Reviewer that uses the Stockfish binary at stockfishPath. Optional functional options can be provided to configure depth, threads, and hash table size.

Returns ErrEngineFailure if the engine cannot be started.

func (*Reviewer) Close

func (r *Reviewer) Close() error

Close shuts down the underlying Stockfish engine process.

func (*Reviewer) ReviewGame

func (r *Reviewer) ReviewGame(ctx context.Context, pgn string) ([]MoveReview, error)

ReviewGame analyses the provided PGN string and returns a MoveReview for each half-move in the game. It evaluates each position once at the configured depth (N+1 total calls for N plies) and carries the score forward between plies to avoid redundant engine work.

PGN games with a custom starting position (SetUp/FEN headers) are fully supported: Stockfish is initialised from the FEN rather than the standard starting position, and move numbers reflect the FEN's full-move counter.

Returns ErrInvalidPGN when the PGN cannot be parsed. Returns ErrEngineFailure when communication with the engine fails.

func (*Reviewer) ReviewGameFull

func (r *Reviewer) ReviewGameFull(ctx context.Context, pgn string) (GameResult, error)

ReviewGameFull analyses the provided PGN string and returns a GameResult containing per-move analysis and an aggregated GameSummary for both players.

It is equivalent to calling ReviewGame and then Summarize, but player names are extracted directly from the PGN headers so the caller does not need to parse them separately.

Returns ErrInvalidPGN when the PGN cannot be parsed. Returns ErrEngineFailure when communication with the engine fails.

func (*Reviewer) ReviewGameFullStream

func (r *Reviewer) ReviewGameFullStream(ctx context.Context, pgn string) (moves <-chan MoveReview, errs <-chan error, summaries <-chan GameSummary)

ReviewGameFullStream analyses the provided PGN string and streams each MoveReview to the returned moves channel as soon as it is computed. Once all moves have been processed, an aggregated GameSummary is sent on the summary channel and all three channels are closed.

Any engine, parse, or context-cancellation error is sent on the separate error channel (buffered, capacity 1), which is closed after at most one value. In particular, if the caller cancels the context while a move is being sent, ctx.Err() is delivered on errs. When an error occurs the summary channel is closed without a value.

Callers must keep receiving from moves (or cancel the context) until it is closed to avoid blocking the background goroutine. The errs and summaries channels are buffered (capacity 1) and will not block the producer; reading them is recommended for correctness but is not required to prevent blocking.

PGN games with a custom starting position (SetUp/FEN headers) are fully supported.

func (*Reviewer) ReviewGameStream

func (r *Reviewer) ReviewGameStream(ctx context.Context, pgn string) (moves <-chan MoveReview, errs <-chan error)

ReviewGameStream analyses the provided PGN string and streams each MoveReview to the returned channel as soon as it is computed. The moves channel is closed when all moves have been processed or when an error occurs.

Any engine, parse, or context-cancellation error is sent on the separate error channel (buffered, capacity 1), which is closed after at most one value. In particular, if the caller cancels the context while a move is being sent, ctx.Err() is delivered on errs.

Callers must keep receiving from moves (or cancel the context) until it is closed to avoid blocking the background goroutine. Reading from errs is recommended for correctness but is not required to prevent blocking, as the error channel is buffered.

PGN games with a custom starting position (SetUp/FEN headers) are fully supported.

Directories

Path Synopsis
cmd
chess-review command
Package main is the entry point for the chess-review CLI.
Package main is the entry point for the chess-review CLI.

Jump to

Keyboard shortcuts

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