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
- type Classification
- type ClassifyContext
- type ErrEngineFailure
- type ErrInvalidPGN
- type GamePhase
- type GameResult
- type GameSummary
- type MoveEvaluation
- type MoveReview
- type Option
- type PlayerSummary
- type Reviewer
- func (r *Reviewer) Close() error
- func (r *Reviewer) ReviewGame(ctx context.Context, pgn string) ([]MoveReview, error)
- func (r *Reviewer) ReviewGameFull(ctx context.Context, pgn string) (GameResult, error)
- func (r *Reviewer) ReviewGameFullStream(ctx context.Context, pgn string) (moves <-chan MoveReview, errs <-chan error, summaries <-chan GameSummary)
- func (r *Reviewer) ReviewGameStream(ctx context.Context, pgn string) (moves <-chan MoveReview, errs <-chan error)
Constants ¶
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 ¶
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.
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 ¶
WithDepth sets the search depth for engine analysis. Higher values produce stronger but slower analysis. The default depth is 18.
func WithHash ¶
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 ¶
WithThreads sets the number of CPU threads the engine may use. The default is 1.
func WithTopMoves ¶ added in v0.1.2
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 ¶
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) ReviewGame ¶
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 ¶
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.
Source Files
¶
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. |