board

package
v0.91.1 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package board contain chess board representation and utilities.

Index

Constants

View Source
const (
	NoCastlingRights    = Castling(0)
	WhiteCastlingRights = WhiteKingSideCastle | WhiteQueenSideCastle
	BlackCastlingRights = BlackKingSideCastle | BlackQueenSideCastle
	FullCastingRights   = WhiteCastlingRights | BlackCastlingRights

	ZeroCastling = NoCastlingRights
	NumCastling  = FullCastingRights + 1
)

Variables

View Source
var (
	AllPieces                 = []Piece{King, Queen, Rook, Knight, Bishop, Pawn}
	KingQueen                 = []Piece{King, Queen}
	KingQueenRookKnightBishop = []Piece{King, Queen, Rook, Knight, Bishop}
	QueenRookBishop           = []Piece{Queen, Rook, Bishop}
	QueenRookKnightBishop     = []Piece{Queen, Rook, Knight, Bishop}
	QueenRookKnightBishopPawn = []Piece{Queen, Rook, Knight, Bishop, Pawn}
)

Functions

func FormatMoves

func FormatMoves(list []Move, fn func(Move) string) string

FormatMoves formats a list of moves.

func IsSameDiagonal

func IsSameDiagonal(a, b Square) bool

IsSameDiagonal returns true if the squares are on the same diagonal.

func IsSameRankOrFile

func IsSameRankOrFile(a, b Square) bool

IsSameRankOrFile returns true if the squares are on the same rank or same file.

func PrintMoves

func PrintMoves(list []Move) string

PrintMoves prints a list of moves.

func SortByPriority added in v0.90.1

func SortByPriority(moves []Move, fn MovePriorityFn)

SortByPriority sorts the moves by priority, preserving order for same priority.

Types

type Bitboard

type Bitboard uint64

Bitboard is a bit-wise representation of the chess board. Each bit represents the appearance of some piece on that square. (bit 63 = A8 and bit 0 = H1). It relies on CPU-support for certain operations, such as popcount and bitscan.

const (
	EmptyBitboard Bitboard = 0
)

func Attackboard

func Attackboard(bb RotatedBitboard, sq Square, piece Piece) Bitboard

Attackboard returns all potential moves/attacks for an officer (= non-Pawn) at the given square.

func BishopAttackboard

func BishopAttackboard(bb RotatedBitboard, sq Square) Bitboard

BishopAttackboard returns all potential moves/attacks for a Bishop at the given square.

func BitFile

func BitFile(f File) Bitboard

BitFile returns a bitboard for the given file.

func BitMask

func BitMask(sq Square) Bitboard

BitMask returns a bitboard with the given square populated.

func BitRank

func BitRank(r Rank) Bitboard

BitRank returns a bitboard for the given rank.

func KingAttackboard

func KingAttackboard(sq Square) Bitboard

KingAttackboard returns all potential moves/attacks for a King at the given square.

func KnightAttackboard

func KnightAttackboard(sq Square) Bitboard

KnightAttackboard returns all potential moves/attacks for a Knight at the given square.

func PawnCaptureboard

func PawnCaptureboard(c Color, pawns Bitboard) Bitboard

PawnCaptureboard returns all potential pawn captures for the given color.

func PawnJumpRank

func PawnJumpRank(c Color) Bitboard

PawnJumpRank returns the mask of the target rank for jump moves for the given color, i.e., Rank4 for White or Rank5 for Black.

func PawnMoveboard

func PawnMoveboard(all Bitboard, c Color, pawns Bitboard) Bitboard

PawnMoveboard returns all potential pawn sigle-step moves for the given color.

func PawnPromotionRank

func PawnPromotionRank(c Color) Bitboard

PawnPromotionRank returns the mask of the promotion rank for the given color, i.e., Rank8 for White or Rank1 for Black.

func QueenAttackboard

func QueenAttackboard(bb RotatedBitboard, sq Square) Bitboard

QueenAttackboard returns all potential moves/attacks for a Queen at the given square. Convenience function.

func RookAttackboard

func RookAttackboard(bb RotatedBitboard, sq Square) Bitboard

RookAttackboard returns all potential moves/attacks for a Rook at the given square.

func (Bitboard) IsSet

func (b Bitboard) IsSet(sq Square) bool

func (Bitboard) LastPopSquare

func (b Bitboard) LastPopSquare() Square

LastPopSquare returns the index of the least-significant 1. Returns 64 if zero.

func (Bitboard) PopCount

func (b Bitboard) PopCount() int

PopCount returns the population count of the bitboard, i.e., number of 1s.

func (Bitboard) String

func (b Bitboard) String() string

func (Bitboard) ToSquares added in v0.90.1

func (b Bitboard) ToSquares() []Square

ToSquares returns population as a square list. Convenience function.

type Board

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

Board represents a chess board, metadata and history of positions to correctly handle game results, notably various draw conditions. Not thread-safe.

func NewBoard

func NewBoard(zt *ZobristTable, pos *Position, turn Color, noprogress, fullmoves int) *Board

func (*Board) Adjudicate

func (b *Board) Adjudicate(result Result)

Adjudicate the position as given.

func (*Board) AdjudicateNoLegalMoves

func (b *Board) AdjudicateNoLegalMoves() Result

AdjudicateNoLegalMoves adjudicates the position assuming no legal moves exist. The result is then either Mate or Stalemate.

func (*Board) Fork

func (b *Board) Fork() *Board

Fork branches off a new board, sharing the node history for past positions. If forked, the shared history should not be mutated (via PopMove) as the forward moves in node might then become stale.

func (*Board) FullMoves

func (b *Board) FullMoves() int

FullMoves returns the number of full moves. May be larger than game history suggests for FromPosition games.

func (*Board) HasCastled

func (b *Board) HasCastled(c Color) bool

HasCastled returns true iff the color has castled.

func (*Board) HasMoved

func (b *Board) HasMoved(limit int) Bitboard

HasMoved returns which pieces have moved, up to the given limit.

func (*Board) Hash

func (b *Board) Hash() ZobristHash

Hash returns the Zobrist hashcode for the current position.

func (*Board) LastMove

func (b *Board) LastMove() (Move, bool)

LastMove returns the last move, if any.

func (*Board) NoProgress

func (b *Board) NoProgress() int

NoProgress returns the ply count since last irreversible move, i.e, pawn move, castling or capture. Used solely to track the 50 move draw rule.

func (*Board) Ply

func (b *Board) Ply() int

Ply returns the number of half-moves since the beginning of the game. It is equal to teh number of positions in the game history.

func (*Board) PopMove

func (b *Board) PopMove() (Move, bool)

func (*Board) Position

func (b *Board) Position() *Position

Position returns the current position.

func (*Board) PushMove

func (b *Board) PushMove(m Move) bool

PushMove attempts to make a pseudo-legal move. Returns true iff legal.

func (*Board) Result

func (b *Board) Result() Result

Result returns the game result.

func (*Board) SecondToLastMove

func (b *Board) SecondToLastMove() (Move, bool)

SecondToLastMove returns the second-to-last move, if any.

func (*Board) String

func (b *Board) String() string

func (*Board) Turn

func (b *Board) Turn() Color

Turn returns the color whose turn it is to move.

type Castling

type Castling uint8

Castling represents the set of castling rights. 4 bits.

const (
	WhiteKingSideCastle Castling = 1 << iota
	WhiteQueenSideCastle
	BlackKingSideCastle
	BlackQueenSideCastle
)

func CastlingRights

func CastlingRights(c Color) Castling

CastlingRights returns the castling rights for the given color.

func (Castling) IsAllowed

func (c Castling) IsAllowed(right Castling) bool

IsAllowed returns true iff all the given rights are allowed.

func (Castling) String

func (c Castling) String() string

type Color

type Color uint8

Color represents the playing side/color: white or black. 1 bit.

const (
	White Color = iota
	Black
)
const (
	ZeroColor Color = 0
	NumColors Color = 2
)

func (Color) Opponent

func (c Color) Opponent() Color

func (Color) String

func (c Color) String() string

type File

type File uint8

File represents a chess board file from FileH=0, ..FileA=7. The numbering is reversed to match Square. 3bits.

const (
	FileH File = iota
	FileG
	FileF
	FileE
	FileD
	FileC
	FileB
	FileA
)
const (
	ZeroFile File = 0
	NumFiles File = 8
)

func ParseFile

func ParseFile(r rune) (File, bool)

func (File) IsValid

func (f File) IsValid() bool

func (File) String

func (f File) String() string

func (File) V

func (f File) V() int

type Move

type Move struct {
	Type      MoveType
	From, To  Square
	Piece     Piece // moved piece
	Promotion Piece // desired piece for promotion, if any.
	Capture   Piece // captured piece, if any. Not set if EnPassant.
}

Move represents a not-necessarily legal move along with contextual metadata. 64bits.

func FindMoves added in v0.90.1

func FindMoves(moves []Move, fn MovePredicateFn) []Move

FindMoves returns moves that satisfy a predicate from a list of moves.

func ParseMove

func ParseMove(str string) (Move, error)

ParseMove parses a move in pure algebraic coordinate notation, such as "a2a4" or "a7a8q". The parsed move does not contain contextual information like castling or en passant.

func (Move) CastlingRightsLost

func (m Move) CastlingRightsLost() Castling

CastlingRightsLost returns the castling rights that are definitely not present after this move. If king moves, rights are lost. Ditto if rook moves or is captured.

func (Move) CastlingRookMove

func (m Move) CastlingRookMove() (Square, Square, bool)

CastlingRookMove returns the implicit rook move (from, to), if a KingSideCastle or QueenSideCastle move.

func (Move) EnPassantCapture

func (m Move) EnPassantCapture() (Square, bool)

EnPassantCapture return the e.p capture square, if a EnPassant move. For d4*e3 e.p, it turns e4.

func (Move) EnPassantTarget

func (m Move) EnPassantTarget() (Square, bool)

EnPassantTarget return the e.p target square, if a Jump move. For e2-e4, it turns e3.

func (Move) Equals

func (m Move) Equals(o Move) bool

func (Move) IsCapture

func (m Move) IsCapture() bool

IsCapture returns true iff the move is a Capture or CapturePromotion. Convenience function.

func (Move) IsCaptureOrEnPassant added in v0.90.1

func (m Move) IsCaptureOrEnPassant() bool

IsCaptureOrEnPassant returns true iff the move is a Capture, CapturePromotion or EnPassant. Convenience function.

func (Move) IsCastle

func (m Move) IsCastle() bool

IsCastle returns true iff the move is a KingSideCastle or QueenSideCastle. Convenience function.

func (Move) IsInvalid

func (m Move) IsInvalid() bool

IsInvalid true iff the move is of invalid type. Convenience function.

func (Move) IsNotUnderPromotion added in v0.90.1

func (m Move) IsNotUnderPromotion() bool

IsNotUnderPromotion returns false if under-promotion. Convenience function for move selection.

func (Move) IsPromotion

func (m Move) IsPromotion() bool

IsPromotion returns true iff the move is a Promotion or CapturePromotion. Convenience function.

func (Move) IsUnderPromotion added in v0.90.1

func (m Move) IsUnderPromotion() bool

IsUnderPromotion returns true iff the move is a Promotion, but not to a Queen. Convenience function.

func (Move) String

func (m Move) String() string

type MoveList added in v0.90.1

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

MoveList is move priority queue for move ordering.

func NewMoveList added in v0.90.1

func NewMoveList(moves []Move, fn MovePriorityFn) *MoveList

NewMoveList returns a new move list with the given priorities.

func (*MoveList) Next added in v0.90.1

func (ml *MoveList) Next() (Move, bool)

Next returns the next move. It is the highest priority move in the list.

func (*MoveList) Size added in v0.90.1

func (ml *MoveList) Size() int

func (*MoveList) String added in v0.90.1

func (ml *MoveList) String() string

type MovePredicateFn added in v0.90.1

type MovePredicateFn func(move Move) bool

MovePredicateFn is a move predicate.

type MovePriority added in v0.90.1

type MovePriority int16

MovePriority represents the move order priority.

type MovePriorityFn added in v0.90.1

type MovePriorityFn func(move Move) MovePriority

MovePriorityFn assigns a priority to moves

func First added in v0.90.1

func First(first Move, fn MovePriorityFn) MovePriorityFn

First puts the given move first. Otherwise uses the given function.

type MoveType

type MoveType uint8

MoveType indicates the type of move. The no-progress counter is reset with any non-Normal move.

const (
	Normal    MoveType = 1 + iota
	Push               // Pawn move
	Jump               // Pawn 2-square move
	EnPassant          // Implicitly a pawn capture
	QueenSideCastle
	KingSideCastle
	Capture
	Promotion
	CapturePromotion
)

func (MoveType) String

func (m MoveType) String() string

type Outcome

type Outcome uint8

Outcome represents the result of a game, if any. Result include a special Unknown option to better support the lazy movegen approach, where we only discover the true result when no legal move exists. 3 bits.

const (
	Unknown Outcome = iota // = is one of the below options, but not known which yet
	Undecided
	WhiteWins
	BlackWins
	Draw
)

func Loss

func Loss(c Color) Outcome

Loss returns a loss outcome for the color.

func Win

func Win(c Color) Outcome

Win returns a win outcome for the color.

func (Outcome) String

func (o Outcome) String() string

type Piece

type Piece uint8

Piece represents a chess piece (King, Pawn, etc) with no color. Zero indicates "No Piece". 3 bits.

const (
	NoPiece Piece = iota
	Pawn
	Bishop
	Knight
	Rook
	Queen
	King
)
const (
	ZeroPiece Piece = 1
	NumPieces Piece = 7
)

func ParsePiece

func ParsePiece(r rune) (Piece, bool)

func (Piece) IsValid

func (p Piece) IsValid() bool

func (Piece) String

func (p Piece) String() string

type Placement

type Placement struct {
	Square Square
	Color  Color
	Piece  Piece
}

Placement defines a piece placement.

func (Placement) String

func (p Placement) String() string

type Position

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

Position represents a board position suitable for move generation. It includes castling and en passant, but not game metadata to determine various Draw conditions.

func NewPosition

func NewPosition(pieces []Placement, castling Castling, ep Square) (*Position, error)

func (*Position) All

func (p *Position) All() Bitboard

All returns a bitboard contains all pirces.

func (*Position) Castling

func (p *Position) Castling() Castling

Castling returns the castling rights.

func (*Position) Color

func (p *Position) Color(c Color) Bitboard

Color returns the bitboard for a given color.

func (*Position) EnPassant

func (p *Position) EnPassant() (Square, bool)

EnPassant return the target en passant square, if previous move was a Jump. For example, after e2e4, the en passant target square is e3 whether or not black has pawns on d4 or f4.

func (*Position) HasInsufficientMaterial

func (p *Position) HasInsufficientMaterial() bool

HasInsufficientMaterial returns true iff there is not sufficient material for either side to win. The cases are: K v K, KN v K, KB v KB (or KBB v K) w/ Bishops on same square color. Assumes 2 kings.

func (*Position) IsAttacked

func (p *Position) IsAttacked(c Color, sq Square) bool

IsAttacked returns true iff the square is attacked by the opposing color. Does not include en passant.

func (*Position) IsAttackedBy added in v0.91.1

func (p *Position) IsAttackedBy(c Color, sq Square, list []Piece) bool

IsAttackedBy returns true iff the square is attacked by the given pieces of the opposing color. Does not include en passant.

func (*Position) IsCheckMate

func (p *Position) IsCheckMate(c Color) bool

IsCheckMate returns true iff the color is checkmate. Convenient for IsChecked && len(LegalMoves)==0.

func (*Position) IsChecked

func (p *Position) IsChecked(c Color) bool

IsChecked returns true iff the color is in check. Convenient for IsAttacked(King).

func (*Position) IsDefended added in v0.90.1

func (p *Position) IsDefended(c Color, sq Square) bool

IsDefended returns true iff the square is defended by the color.

func (*Position) IsDefendedBy added in v0.91.1

func (p *Position) IsDefendedBy(c Color, sq Square, list []Piece) bool

IsDefendedBy returns true iff the square is defended by pieces of the color.

func (*Position) IsEmpty

func (p *Position) IsEmpty(sq Square) bool

IsEmpty returns true iff the square is empty.

func (*Position) KingSquare added in v0.90.1

func (p *Position) KingSquare(c Color) Square

KingSquare returns the square for a given color. Must be valid and unique.

func (*Position) LegalMoves

func (p *Position) LegalMoves(turn Color) []Move

LegalMoves returns a list of all legal moves. Convenience function.

func (*Position) Move

func (p *Position) Move(m Move) (*Position, bool)

Move attempts to make a pseudo-legal move. The attempted move is assumed to be pseudo-legal and generated from the position. Returns false if not legal.

func (*Position) Piece

func (p *Position) Piece(c Color, piece Piece) Bitboard

Piece returns the bitboard for a given color/piece.

func (*Position) PieceSquares added in v0.90.1

func (p *Position) PieceSquares(c Color, piece Piece) []Square

PieceSquares returns the squares for a given color/piece.

func (*Position) PseudoLegalMoves

func (p *Position) PseudoLegalMoves(turn Color) []Move

PseudoLegalMoves returns a list of all pseudo-legal moves. The move may not respect either side being in check, which must be validated subsequently.

func (*Position) Rotated

func (p *Position) Rotated() RotatedBitboard

Rotated returns the rotated bitboard.

func (*Position) Square

func (p *Position) Square(sq Square) (Color, Piece, bool)

Square returns the content of the given square. Returns false is no piece present.

func (*Position) String

func (p *Position) String() string

type Rank

type Rank uint8

Rank represents a chess board rank from Rank1=0, ..Rank8=7. 3bits.

const (
	Rank1 Rank = iota
	Rank2
	Rank3
	Rank4
	Rank5
	Rank6
	Rank7
	Rank8
)
const (
	ZeroRank Rank = 0
	NumRanks Rank = 8
)

func ParseRank

func ParseRank(r rune) (Rank, bool)

func PromotionRank added in v0.90.1

func PromotionRank(c Color) Rank

PromotionRank returns the promotion rank of the given color.

func (Rank) IsValid

func (r Rank) IsValid() bool

func (Rank) String

func (r Rank) String() string

func (Rank) V

func (r Rank) V() int

type Reason

type Reason string

Reason is the reason for a terminal result.

const (
	Checkmate Reason = "Checkmate"
	Resigned  Reason = "Opponent Resigned"
	TimedOut  Reason = "Opponent lost on time"

	Stalemate            Reason = "Stalemate"
	Repetition3          Reason = "3-Fold Repetition" // can be claimed, but does not have to be
	Repetition5          Reason = "5-Fold Repetition"
	NoProgress           Reason = "No progress"
	InsufficientMaterial Reason = "Insufficient Material"
	Agreement            Reason = "Agreement"
)

type Result

type Result struct {
	Outcome Outcome
	Reason  Reason
}

Result represents the result of a game, if any, with reason.

func (Result) IsKnown

func (r Result) IsKnown() bool

func (Result) IsTerminal

func (r Result) IsTerminal() bool

func (Result) String

func (r Result) String() string

type RotatedBitboard

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

RotatedBitboard represents the piece-agnostic population of the board as so-called "rotated bitboards". It is designed to map files/diagonals into adjacent memory cells. It is conceptually simpler to view the transformations as rotations, but we are free to "shuffle" the files/diagonals as we please: the 'rot90' is really a flip. In the diagonal case we have to hold additional information about the length and offset of the desired diagonal, since that information is not constant.

func NewRotatedBitboard

func NewRotatedBitboard(bb Bitboard) RotatedBitboard

func (RotatedBitboard) Mask

func (r RotatedBitboard) Mask() Bitboard

Mask returns the bitboard mask (in normal orientation).

func (RotatedBitboard) String

func (r RotatedBitboard) String() string

func (RotatedBitboard) Xor

Xor returns the rotated bitboard xor the square mask.

type Square

type Square uint8

Square represents a square on the board, ordered H1=0, G1=1 .., A8=63. This numbering matches a 64-bit interpretation as a bitboard:

A8 = 63, B8 = 62, C8 = 61, D8 = 60, E8 = 59, F8 = 58, G8 = 57, H8 = 56,
A7 = 55, B7 = 54, C7 = 53, D7 = 52, E7 = 51, F7 = 50, G7 = 49, H7 = 48,
A6 = 47, B6 = 46, C6 = 45, D6 = 44, E6 = 43, F6 = 42, G6 = 41, H6 = 40,
A5 = 39, B5 = 38, C5 = 37, D5 = 36, E5 = 35, F5 = 34, G5 = 33, H5 = 32,
A4 = 31, B4 = 30, C4 = 29, D4 = 28, E4 = 27, F4 = 26, G4 = 25, H4 = 24,
A3 = 23, B3 = 22, C3 = 21, D3 = 20, E3 = 19, F3 = 18, G3 = 17, H3 = 16,
A2 = 15, B2 = 14, C2 = 13, D2 = 12, E2 = 11, F2 = 10, G2 =  9, H2 =  8,
A1 =  7, B1 =  6, C1 =  5, D1 =  4, E1 =  3, F1 =  2, G1 =  1, H1 =  0

A square is a bit-index into the bitboard layout. 6 bits.

const (
	H1 Square = iota
	G1
	F1
	E1
	D1
	C1
	B1
	A1

	H2
	G2
	F2
	E2
	D2
	C2
	B2
	A2

	H3
	G3
	F3
	E3
	D3
	C3
	B3
	A3

	H4
	G4
	F4
	E4
	D4
	C4
	B4
	A4

	H5
	G5
	F5
	E5
	D5
	C5
	B5
	A5

	H6
	G6
	F6
	E6
	D6
	C6
	B6
	A6

	H7
	G7
	F7
	E7
	D7
	C7
	B7
	A7

	H8
	G8
	F8
	E8
	D8
	C8
	B8
	A8
)
const (
	ZeroSquare Square = 0
	NumSquares Square = 64
)

Iteration helpers to enable "for i := ZeroSquare; i<NumSquares; i++".

func NewSquare

func NewSquare(f File, r Rank) Square

func ParseSquare

func ParseSquare(f, r rune) (Square, error)

func ParseSquareStr

func ParseSquareStr(str string) (Square, error)

func (Square) File

func (s Square) File() File

func (Square) IsValid

func (s Square) IsValid() bool

func (Square) Rank

func (s Square) Rank() Rank

func (Square) String

func (s Square) String() string

type ZobristHash

type ZobristHash uint64

ZobristHash is a position hash based on piece-squares. It is intended for 3-fold repetition draw detection and hashes "identical" positions under that rule to the same hash value.

See also: https://research.cs.wisc.edu/techreports/1970/TR88.pdf.

type ZobristTable

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

ZobristTable is a pseudo-randomized table for computing a position hash.

func NewZobristTable

func NewZobristTable(seed int64) *ZobristTable

func (*ZobristTable) Hash

func (z *ZobristTable) Hash(pos *Position, turn Color) ZobristHash

Hash computes the zobrist hash for the given position.

func (*ZobristTable) Move

func (z *ZobristTable) Move(h ZobristHash, pos *Position, m Move) ZobristHash

Move computes a hash for the position after the (legal) move incrementally. Cheaper than computing it for the new position directly.

Directories

Path Synopsis
Package fen contains utilities for read and writing positions in FEN notation.
Package fen contains utilities for read and writing positions in FEN notation.

Jump to

Keyboard shortcuts

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