chess

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package chess is a self-contained chess engine: board state, pieces, move generation, legality checking, FEN parsing, make/unmake, and game-result detection.

It is the project's only public, reusable surface — an external program can depend on it to represent a position and enumerate legal moves without pulling in any of gambit's agents, GUI or game-loop code.

Squares are indexed 0..63 with A1=0 and H8=63. Colors, pieces and moves are compact value types so move lists are cheap to copy and sort during search.

Index

Constants

View Source
const StartingFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"

StartingFEN is the FEN of the standard initial position.

Variables

This section is empty.

Functions

func Perft added in v0.1.0

func Perft(b *Board, depth int) uint64

Perft counts the leaf nodes of the move tree to the given depth. It is the standard correctness check for move generation.

Types

type Board

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

Board is a single chess position using an 8x8 mailbox representation. It is deliberately representation-agnostic at the API level so the internals could be swapped for bitboards later without breaking callers.

Board.MakeMove and Board.UnmakeMove mutate the receiver in place and are meant to be paired for fast search; Board.ApplyMove instead returns a new board and leaves the receiver unchanged, for callers that want an immutable step.

func NewStartingBoard

func NewStartingBoard() *Board

NewStartingBoard returns a board in the standard initial position.

func ParseFEN

func ParseFEN(fen string) (*Board, error)

ParseFEN parses a FEN string into a Board.

func (*Board) ApplyMove

func (b *Board) ApplyMove(m Move) *Board

ApplyMove returns a new board with the move applied, leaving the receiver unchanged. This clone-based variant suits search strategies (e.g. beam search) that keep many independent positions alive at once.

func (*Board) CastleRights

func (b *Board) CastleRights() CastleRights

CastleRights returns the current castling rights.

func (*Board) Clone

func (b *Board) Clone() *Board

Clone returns an independent copy of the board.

func (*Board) Each

func (b *Board) Each(fn func(s Square, p Piece))

Each calls fn for every square on the board in index order. Useful for rendering without exposing the internal array.

func (*Board) EnPassantSquare

func (b *Board) EnPassantSquare() Square

EnPassantSquare returns the current en-passant target, or NoSquare.

func (*Board) FEN

func (b *Board) FEN() string

FEN returns the board's position as a FEN string.

func (*Board) FullMoveNumber

func (b *Board) FullMoveNumber() int

FullMoveNumber returns the full-move counter.

func (*Board) GenerateMoves

func (b *Board) GenerateMoves(dst []Move) []Move

GenerateMoves appends all fully-legal moves for the side to move to dst and returns the extended slice. The pseudo-legal moves are generated into dst and filtered in place, so hot search loops that pass a reused buffer avoid a per-call allocation.

func (*Board) GeneratePseudoLegal

func (b *Board) GeneratePseudoLegal(dst []Move) []Move

GeneratePseudoLegal appends all pseudo-legal moves (legal except that they may leave the mover's king in check) to dst and returns the extended slice.

func (*Board) HalfMoveClock

func (b *Board) HalfMoveClock() int

HalfMoveClock returns the halfmove clock (for the fifty-move rule).

func (*Board) Hash

func (b *Board) Hash() uint64

Hash returns a Zobrist hash of the position, suitable for repetition detection. Positions that are equal for repetition purposes (same pieces, side to move, castling rights and en-passant possibility) hash equally.

func (*Board) InCheck

func (b *Board) InCheck() bool

InCheck reports whether the side to move is in check.

func (*Board) IsCheckmate

func (b *Board) IsCheckmate() bool

IsCheckmate reports whether the side to move is checkmated.

func (*Board) IsInsufficientMaterial

func (b *Board) IsInsufficientMaterial() bool

IsInsufficientMaterial reports whether neither side has enough material to force checkmate (K vs K, K+minor vs K, and K+B vs K+B with same-colored bishops are treated as insufficient).

func (*Board) IsSquareAttacked

func (b *Board) IsSquareAttacked(s Square, by Color) bool

IsSquareAttacked reports whether square s is attacked by any piece of the given color.

func (*Board) IsStalemate

func (b *Board) IsStalemate() bool

IsStalemate reports whether the side to move is stalemated.

func (*Board) KingSquare

func (b *Board) KingSquare(c Color) Square

KingSquare returns the square of the given color's king.

func (*Board) LegalMoves

func (b *Board) LegalMoves() []Move

LegalMoves returns all fully-legal moves for the side to move. It allocates a fresh slice; hot search loops should prefer GenerateMoves with a reused buffer.

func (*Board) MakeMove

func (b *Board) MakeMove(m Move) Undo

MakeMove applies a move to the board and returns an Undo that reverses it. The move must be legal (or at least pseudo-legal); behavior is undefined otherwise.

func (*Board) PieceAt

func (b *Board) PieceAt(s Square) Piece

PieceAt returns the piece on the given square (NoPiece if empty).

func (*Board) SideToMove

func (b *Board) SideToMove() Color

SideToMove returns the color to move.

func (*Board) Status

func (b *Board) Status() (Result, DrawReason)

Status returns the outcome derivable from the current position alone (checkmate, stalemate, insufficient material). Threefold repetition and the fifty-move rule depend on game history and are handled by callers; the fifty-move clock is exposed via HalfMoveClock.

func (*Board) UnmakeMove

func (b *Board) UnmakeMove(m Move, u Undo)

UnmakeMove reverses a MakeMove given the Undo it returned.

type CastleRights

type CastleRights uint8

CastleRights is a bitset of the four castling possibilities.

const (
	WhiteKingside CastleRights = 1 << iota
	WhiteQueenside
	BlackKingside
	BlackQueenside
)

Castling-rights bits.

func (CastleRights) Has

func (c CastleRights) Has(r CastleRights) bool

Has reports whether all of the given rights are present.

type Color

type Color uint8

Color identifies which side a piece belongs to or which side is to move.

const (
	White Color = iota
	Black
)

The two colors.

func (Color) Opposite

func (c Color) Opposite() Color

Opposite returns the other color.

func (Color) String

func (c Color) String() string

String returns "white" or "black".

type DrawReason

type DrawReason uint8

DrawReason explains why a game was drawn.

const (
	NotDraw DrawReason = iota
	Stalemate
	FiftyMoveRule
	ThreefoldRepetition
	InsufficientMaterial
)

Draw reasons.

func (DrawReason) String

func (d DrawReason) String() string

String returns a human-readable draw reason.

type Move

type Move uint16

Move packs a from-square, to-square and flag into a single uint16: bits 0..5 = from, bits 6..11 = to, bits 12..15 = flag. This keeps move lists cheap to copy and sort during search.

const NoMove Move = 0

NoMove is the zero value, distinguishable because a real move never has equal from/to squares.

func NewMove

func NewMove(from, to Square, flag MoveFlag) Move

NewMove constructs a move from its components.

func (Move) Flag

func (m Move) Flag() MoveFlag

Flag returns the move flag.

func (Move) From

func (m Move) From() Square

From returns the origin square.

func (Move) IsNull

func (m Move) IsNull() bool

IsNull reports whether the move is the zero value.

func (Move) IsPromotion

func (m Move) IsPromotion() bool

IsPromotion reports whether the move promotes a pawn.

func (Move) Promotion

func (m Move) Promotion() PieceType

Promotion returns the piece type a pawn promotes to, or NoPieceType.

func (Move) String

func (m Move) String() string

String returns long algebraic notation, e.g. "e2e4" or "e7e8q".

func (Move) To

func (m Move) To() Square

To returns the destination square.

type MoveFlag

type MoveFlag uint8

MoveFlag describes the special nature of a move, if any.

const (
	FlagNormal MoveFlag = iota
	FlagDoublePawnPush
	FlagEnPassant
	FlagCastleKingside
	FlagCastleQueenside
	FlagPromoKnight
	FlagPromoBishop
	FlagPromoRook
	FlagPromoQueen
)

Move flags.

type Piece

type Piece uint8

Piece encodes a colored piece in a single byte. The low three bits hold the PieceType and the next bit holds the Color. NoPiece (zero) is an empty square.

const NoPiece Piece = 0

NoPiece is the empty-square sentinel.

func MakePiece

func MakePiece(c Color, t PieceType) Piece

MakePiece builds a Piece from a color and type.

func (Piece) Color

func (p Piece) Color() Color

Color returns the owning color. Meaningless for NoPiece.

func (Piece) IsEmpty

func (p Piece) IsEmpty() bool

IsEmpty reports whether the piece is the empty-square sentinel.

func (Piece) Symbol

func (p Piece) Symbol() rune

Symbol returns the FEN letter for the piece: uppercase for white, lowercase for black. Returns a space for an empty square.

func (Piece) Type

func (p Piece) Type() PieceType

Type returns the piece type (NoPieceType for an empty square).

type PieceType

type PieceType uint8

PieceType is the kind of a piece, independent of color.

const (
	NoPieceType PieceType = iota
	Pawn
	Knight
	Bishop
	Rook
	Queen
	King
)

Piece types. NoPieceType marks an empty square's type.

type Result

type Result uint8

Result is the outcome of a game.

const (
	InProgress Result = iota
	WhiteWins
	BlackWins
	Draw
)

Game outcomes.

func (Result) String

func (r Result) String() string

String returns a PGN-style result token.

type Square

type Square uint8

Square is a board square index in the range 0..63, where A1=0, B1=1, ..., H8=63. NoSquare (64) is the "no such square" sentinel.

const NoSquare Square = 64

NoSquare marks the absence of a square (e.g. no en-passant target).

func NewSquare

func NewSquare(file, rank int) Square

NewSquare builds a square from zero-based file (0=a..7=h) and rank (0=rank 1..7=rank 8).

func ParseSquare

func ParseSquare(str string) (Square, error)

ParseSquare parses an algebraic square such as "e4".

func (Square) File

func (s Square) File() int

File returns the zero-based file (0=a..7=h).

func (Square) Rank

func (s Square) Rank() int

Rank returns the zero-based rank (0=rank 1..7=rank 8).

func (Square) String

func (s Square) String() string

String returns the square in algebraic form, e.g. "e4", or "-" for NoSquare.

func (Square) Valid

func (s Square) Valid() bool

Valid reports whether the square is on the board.

type Undo

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

Undo holds the information needed to reverse a MakeMove.

Jump to

Keyboard shortcuts

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