Documentation
¶
Overview ¶
Package chess provides interfaces and types for chess game mechanics development. It includes definitions for the chess board, pieces, moves, and game state. It allows for the creation and manipulation of chess boards, including making moves, checking legal moves, and managing the game state. The package is designed to be flexible and extensible, supporting various chess variants and rules. It is intended for use in chess applications, engines, and libraries that require chess logic.
Index ¶
- Constants
- Variables
- type Board
- type Color
- type File
- type Move
- type MoveResult
- type Piece
- type Position
- type Rank
- type Squares
- func (s *Squares) EdgePosition() Position
- func (s *Squares) FindByPosition(position Position) (Piece, error)
- func (s *Squares) FindPiece(notation string, color Color) (Piece, Position)
- func (s *Squares) GetAllPieces(color Color) iter.Seq[Piece]
- func (s *Squares) GetByPiece(piece Piece) Position
- func (s *Squares) GetPieces(notation string, color Color) iter.Seq[Piece]
- func (s *Squares) Iter() iter.Seq2[Position, Piece]
- func (s *Squares) IterByDirection(from, direction Position) iter.Seq2[Position, Piece]
- func (s *Squares) IterOverRows(backward bool) iter.Seq2[Rank, iter.Seq2[File, Piece]]
- func (s *Squares) MovePiece(from, to Position) (capturedPiece Piece, err error)
- func (s *Squares) MovePieceTemporarily(from, to Position, callback func()) error
- func (s *Squares) PlacePiece(piece Piece, position Position) error
- type State
- type StateType
- type StringMove
Constants ¶
const ( // FileNull has a zero value and represents an empty file. // This value is considered valid. FileNull = position.FileNull // FileMin is the minimum file value after FileNull. FileMin = position.FileMin // FileMax is the maximum file value supported by the engine. // File values greater than FileMax are considered invalid. FileMax = position.FileMax FileA = position.FileA FileB = position.FileB FileC = position.FileC FileD = position.FileD FileE = position.FileE FileF = position.FileF FileG = position.FileG FileH = position.FileH FileI = position.FileI FileJ = position.FileJ FileK = position.FileK FileL = position.FileL FileM = position.FileM FileN = position.FileN FileO = position.FileO FileP = position.FileP // RankNull has a zero value and represents an empty rank. // This value considered valid. RankNull = position.RankNull // RankMin is the minimum rank value after RankNull. RankMin = position.RankMin // RankMax is the maximum rank value supported by the engine. // Rank values greater than RankMax are considered invalid. RankMax = position.RankMax Rank1 = position.Rank1 Rank2 = position.Rank2 Rank3 = position.Rank3 Rank4 = position.Rank4 Rank5 = position.Rank5 Rank6 = position.Rank6 Rank7 = position.Rank7 Rank8 = position.Rank8 Rank9 = position.Rank9 Rank10 = position.Rank10 Rank11 = position.Rank11 Rank12 = position.Rank12 Rank13 = position.Rank13 Rank14 = position.Rank14 Rank15 = position.Rank15 Rank16 = position.Rank16 )
Variables ¶
var ( DirectionTop = NewPosition(FileNull, Rank(1)) DirectionBottom = NewPosition(FileNull, Rank(-1)) DirectionLeft = NewPosition(File(-1), RankNull) DirectionRight = NewPosition(File(1), RankNull) DirectionTopLeft = NewPosition(File(-1), Rank(1)) DirectionTopRight = NewPosition(File(1), Rank(1)) DirectionBottomLeft = NewPosition(File(-1), Rank(-1)) DirectionBottomRight = NewPosition(File(1), Rank(-1)) )
var ErrSquareOutOfRange = errors.New("square position is out of range")
ErrSquareOutOfRange is returned when given square position is out of the valid range.
var MaxSupportedPosition = NewPosition(FileMax, RankMax)
MaxSupportedPosition is the maximum supported position for the chess board. It represents the bottom-right corner of the board, which is typically the highest rank and file in standard chess notation. The engine does not support positions greater than this value.
var ( // StateClear represents a clear state of the chess board. // This state indicates that there are no threats or special conditions on the board. StateClear = NewState("clear", StateTypeClear) )
Functions ¶
This section is empty.
Types ¶
type Board ¶
type Board interface {
// Squares returns a reference to the squares on the board.
// It allows access to the individual squares and their pieces.
Squares() *Squares
// Turn returns the current turn of the board.
// It indicates which side (white or black) is to move next.
Turn() Color
// State returns the current state of the board.
// Returns chess.StateClear if the board is in a clear state.
// Should not return nil.
State() State
// CapturedPieces returns a slice of pieces that have been captured on the board.
CapturedPieces() []Piece
// MoveHistory returns the history of moves made on the board.
// It returns a slice of MoveResult, which contains the details of each move.
MoveHistory() []MoveResult
// Moves returns a set of available legal moves.
Moves() []Position
// IsSquareAttacked checks whether a square is attacked by enemy pieces.
IsSquareAttacked(position Position) bool
// LegalMoves returns a set of legal moves for the specified piece.
// If the piece is nil or not found, it returns an empty set.
LegalMoves(piece Piece) []Position
// MakeMove applies a move to the board and returns the result of the move.
// It returns a MoveResult which contains the details of the move made.
// If the move is invalid or cannot be made, it returns an error.
MakeMove(move Move) (MoveResult, error)
// UndoLastMove undoes the last move made on the board and returns it.
// It returns an error if the undo operation fails.
// Returns nil, nil if there are no moves to undo.
UndoLastMove() (MoveResult, error)
}
Board represents a chessboard with its squares, pieces, and board state. It provides methods to access the current turn, state of the board, and to make moves.
type Color ¶ added in v1.2.0
type Color bool
Color is a type that represents the color of a chess piece, board side or turn. It can be either white or black. The Color type is used to determine the color of a piece and to check if a side or a turn is white or black.
type File ¶ added in v1.0.2
File represents the horizontal coordinate on the board. It takes values from 1 to 16, where 1 corresponds to FileA and 16 to FileP. FileNull is a special value representing an uninitialized file, but is still considered valid.
A file may be valid or invalid.
type Move ¶
Move represents a chess input move which used to make a move on the chessboard. It is an interface that can be implemented by different types of moves, such as Normal move or Castling and so on. The Move interface requires a String method for string representation and a Validate method for validation purposes.
type MoveResult ¶
type MoveResult interface {
fmt.Stringer
// Move returns the Move that was made.
// This method is used to retrieve the move that resulted in this MoveResult.
Move() Move
// Side returns the Side that made the move.
// This method is used to determine which side (white or black) made the move.
Side() Color
// CapturedPiece returns the captured piece as a result of the move.
CapturedPiece() Piece
// BoardNewState returns the new state of the board after the move.
BoardNewState() State
// SetBoardNewState sets a value of the new board state as a result of a move.
SetBoardNewState(state State)
}
MoveResult is an interface that represents the result of a move made on the chessboard. It includes additional methods for retrieving the move itself and validating the result. It is used to encapsulate the details of a move, including the side that made the move, the new state of the board after the move, and can includes any additional information such as captured pieces or castling details. The MoveResult interface requires a String method for string representation, a Validate method for validation purposes, and a Move method to retrieve the move that was made.
type Piece ¶
type Piece interface {
fmt.Stringer
// Color returns the color of the piece.
Color() Color
// Notation returns the algebraic notation of the piece.
// For example, for a pawn it could returns "", for a knight it returns "N", etc.
Notation() string
// Weight returns the weight of the piece.
// The weight is used to evaluate the piece's value in the game.
Weight() uint8
// IsMoved returns true if the piece has been moved.
// This is can be used to determine if the piece can perform castling or en passant.
IsMoved() bool
// SetIsMoved marks the piece as moved or not.
SetIsMoved(isMoved bool)
// PseudoMoves returns all pseudo-legal moves for the piece from the given position.
// Pseudo-move is a move that does not check for checks or other game rules,
// but only considers the piece's movement capabilities.
// It returns a set of positions that the piece can move to from the given position.
PseudoMoves(from Position, squares *Squares) []Position
}
Piece interface describes a chess piece. It provides methods to get the piece's color, check if it has been moved, get pseudo-legal moves, and retrieve its notation and weight. It is used to represent different types of chess pieces such as pawns, knights, bishops, etc. Each piece implements this interface to provide its specific behavior and properties. The Piece interface is essential for the chess game logic, allowing the game to handle pieces generically while still respecting the unique movement and rules associated with each type of piece.
type Position ¶ added in v1.0.2
Position represents the coordinates of a square on a chessboard. Position consists of File and Rank. Positions can have different states:
- Full: File and Rank are filled and both values are not null.
- Partial, not empty: File or Rank has null value.
- Empty: File and Rank both have null value.
- Invalid: File or Rank is invalid (see File and Rank documentation).
func NewPosition ¶ added in v1.0.2
func NewPositionEmpty ¶ added in v1.0.4
func NewPositionEmpty() Position
NewPositionEmpty creates a new empty position. File and rank will have null values.
func PositionFromString ¶ added in v1.0.2
PositionFromString creates a new position from chess notation. If the string is invalid or it's empty, it returns an empty position.
type Rank ¶ added in v1.0.2
Rank represents the horizontal coordinate on the board. It takes values from 1 to 16, where 1 corresponds to Rank1 and 16 to Rank16. RankNull is a special value representing an uninitialized rank, but is still considered valid.
A rank may be valid or invalid.
type Squares ¶
type Squares struct {
// contains filtered or unexported fields
}
Squares represents squares on a chess board. It is a 2D slice of Piece, where each Piece represents a chess piece on the board. Squares provides methods to iterate over the pieces, find pieces by position, get pieces by type and color, move pieces, and place pieces on the squares.
func NewSquares ¶
NewSquares creates a new Squares instance with the specified edge position. The edge position defines the size of the squares, which is the maximum rank and file. If the edge position exceeds the maximum supported position by the engine, it panics.
func SquaresFromPlacement ¶
SquaresFromPlacement creates a new Squares instance from a given placement map. The placement map is a mapping of position to Piece, where each Piece is placed at its corresponding position. If the placement is nil or empty, it returns an empty Squares instance with the specified edge position. If any piece in the placement is out of boundaries defined by the edge position, it returns an error. If edgePosition is not bounded by the maximum supported position, it panics.
func (*Squares) EdgePosition ¶
EdgePosition returns the edge position of the squares.
func (*Squares) FindByPosition ¶
FindByPosition finds a piece by its position on the squares. If the position is out of boundaries, it returns ErrSquareOutOfRange. If the position is valid, it returns the piece at that position or nil if no piece is found.
func (*Squares) FindPiece ¶
FindPiece finds the first piece of a given type for a specific color and returns it along with its position. If no piece is found, it returns nil and an empty position.
func (*Squares) GetAllPieces ¶
GetAllPieces returns all pieces on the squares for a given color.
func (*Squares) GetByPiece ¶
GetByPiece returns the position of the occupied square by the given piece. If the piece is not found on the squares or it is nil, it returns an empty position.
func (*Squares) GetPieces ¶
GetPieces returns all pieces of a specific type (notation) for a given color. It iterates through all squares and collects pieces that match the given notation and color.
func (*Squares) Iter ¶
Iter iterates over all squares and yields each position and the piece at that position. It starts from the top-left corner (FileA, Rank1) and goes to the bottom-right corner (edgePosition).
func (*Squares) IterByDirection ¶
IterByDirection iterates over the squares in a specific direction from a given position. From is the starting position, and direction is the step to take in each iteration. The direction is defined by a Position, which indicates the change in file and rank. It yields each position and the piece at that position until it goes out of boundaries. The boundaries are defined by the edgePosition of the squares.
func (*Squares) IterOverRows ¶
IterOverRows iterates over the squares by rows. It yields each row starting from the top (Rank1) to the bottom (edgeRank). If backward is true, it iterates from the bottom to the top. Each row is yielded as a sequence of file and their corresponding piece.
func (*Squares) MovePiece ¶
MovePiece moves a piece from one position to another. It returns the captured piece if any, or nil if no piece was captured. If the move is out of boundaries, it returns ErrSquareOutOfRange. The piece at the 'from' position is moved to the 'to' position, and the 'from' position is set to nil. If the 'to' position already has a piece, it is captured and returned. If the 'from' position is empty, it returns nil and no error.
func (*Squares) MovePieceTemporarily ¶
MovePieceTemporarily moves a piece from one position to another temporarily. It allows executing a callback function while the piece is moved. After the callback is executed, the piece is moved back to its original position. If the move is out of boundaries, it returns ErrSquareOutOfRange. This is useful for testing or simulating moves without permanently changing the squares position.
func (*Squares) PlacePiece ¶
PlacePiece places a piece on the squares at the specified position. If the position is out of boundaries, it returns ErrSquareOutOfRange. The piece is placed at the given position, and any existing piece at that position is overwritten. If the piece is nil, it will overwrite the existing piece at that position with nil.
type State ¶
type State interface {
fmt.Stringer
// Type returns the type of the state.
// The type can be one of the predefined StateType values,
// such as StateTypeClear, StateTypeThreat or StateTypeTerminal.
Type() StateType
}
State represents the type of a board state. It is used to categorize the state of the chess board.
func NewState ¶
NewState creates a new State with the given name and type. The name is a string representation of the state, and the stateType is one of the predefined StateType values. This function is used to create a new state that can be used in the chess game. It allows for the creation of custom states with specific names and types, which can be useful for representing different conditions on the chess board.
type StateType ¶
type StateType uint8
StateType represents the type of a chess board state. It is used to categorize the state of the chess board. The StateType can be one of the following: - StateTypeClear - StateTypeThreat - StateTypeTerminal.
const ( // StateTypeClear indicates that the chess board is in a clear state, // meaning there are no threats or special conditions affecting the game. // This is the default state of the board when no pieces are threatening each other. StateTypeClear StateType = iota // StateTypeThreat indicates that there is a threat on the chess board, // which is useful for indicating check or other conditions where a piece is under threat. StateTypeThreat // StateTypeTerminal indicates that the game has reached a terminal state, // such as checkmate or stalemate, where no further moves can be made. // This state is used to signify the end of the game. StateTypeTerminal )
func (StateType) IsTerminal ¶
IsTerminal checks if the state type indicates a terminal state.
type StringMove ¶
type StringMove string
StringMove is a simple implementation of the Move interface that represents a move as a string. It is used for cases where the move can be represented as a string, such as in standard chess notation.
func (StringMove) String ¶
func (m StringMove) String() string
func (StringMove) Validate ¶
func (m StringMove) Validate() error
Validate implements the validation.Validatable interface for StringMove. It does not perform any validation and always returns nil.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package chesstest provides utility functions and mocks for testing chess-related components.
|
Package chesstest provides utility functions and mocks for testing chess-related components. |
|
internal
|
|
|
position
Package position provides functionality to work with chess positions.
|
Package position provides functionality to work with chess positions. |
|
Package metric provides utilities to compute various numeric and descriptive metrics for a chess board (for example: material balance, move counters, and last move).
|
Package metric provides utilities to compute various numeric and descriptive metrics for a chess board (for example: material balance, move counters, and last move). |
|
Package visualizer renders a human-readable textual representation of a chess.Board.
|
Package visualizer renders a human-readable textual representation of a chess.Board. |