chess

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: GPL-3.0 Imports: 8 Imported by: 11

README

chess - core chess primitives

godoc go report card

A small, well-tested Go library that implements core chess primitives: board and square management, pieces and moves, position handling, simple metrics and a textual visualizer.

Requirements

  • Go 1.23 or newer

Install with:

go get github.com/elaxer/chess

About

What this library is NOT

This library is not:

  • A ready-to-play chess game with UI
  • A full-featured chess engine with AI, evaluation, or search algorithms
  • A beginner-friendly “learn chess by coding” toolkit

There is no GUI, no bots, no minimax, no magic. This package focuses strictly on core chess primitives and rules infrastructure.

Who this library is for

This library is designed for developers who:

  • want to build their own chess engine or experiment with custom rules
  • need a clean, testable, low-level chess model (board, moves, states)
  • care about explicit state management and invariants
  • are comfortable working with interfaces and composing their own implementations
Engine implementations

This package is intentionally engine-agnostic. It defines chess primitives such as board representation, positions, directions, move semantics, states, and metrics, without enforcing any concrete rule set or starting position.

Concrete rule implementations are provided as separate engines built on top of this core:

Think of this repository as the core mechanics layer, while standardchess and fischerchess are engine-level compositions that define concrete rules and constraints.

If you want to implement any of the following:

  • chess variants
  • alternative starting positions
  • custom rule sets
  • non-standard boards

this library remains unchanged, while the engine implementation varies.

Documentation

Board information

You can retrieve information stored in the board. See examples below:

Get the current turn:

var board chess.Board
var turn chess.Color = board.Turn()

Get the current board state:

var state chess.State = board.State()

Get a list of executed moves on the board:

var moveHistory []chess.MoveResult = board.MoveHistory()
Moves

You can easily get available moves on the board:

var availableMoves []chess.Position = board.Moves()

The board.Moves method returns the set of positions to which the pieces can move. Each piece has a method PseudoMoves, so board.Moves returns a filtered set of the pieces' moves.

You can also get a filtered set of moves for a specific piece:

var piece chess.Piece = board.Squares().FindByPosition(chess.PositionFromString("e2"))
var pieceLegalMoves []chess.Position = board.LegalMoves(piece)

Here the question arises: what do legal and pseudo moves mean?

Legal moves are moves that can be made without breaking the board's rules. Pseudo moves include moves that would be considered illegal. For example, in standard chess, an illegal move is one after which the opponent can capture the king. board.Moves and board.LegalMoves both return legal moves.

Making moves

You can make moves:

var move chess.Move = chess.StringMove("Bc5")
var moveResult chess.MoveResult

moveResult, err := board.MakeMove(move)

The method returns a chess.MoveResult and an error. MoveResult contains the input move (MoveResult.Move) and provides methods to get the captured piece (if any) via MoveResult.CapturedPiece, the side that made the move (MoveResult.Side), and the new board state after the move (MoveResult.BoardNewState). The error is non‑nil if the move was incorrect or impossible.

You can also undo the last move:

var lastMoveResult chess.MoveResult

lastMoveResult, err := board.UndoMove()
Working with squares

Operations on chess squares and piece arrangement are encapsulated in the chess.Square structure. Your board contains it:

var squares *chess.Square = board.Squares()

... or you can create your own:

edgePosition := chess.NewPosition(chess.FileH, chess.Rank8)
squares = chess.NewSquares(edgePosition)

"Edge position" refers to the most extreme square on the board and defines the board's size. In our example we created an 8x8 field.

NOTE: It is impossible to create squares larger than the value specified by chess.MaxSupportedPosition.

You can also create squares with placed pieces:

// Here should be your implementation of the piece
var piece chess.Piece
squares, err := SquaresFromPlacement(edgePosition, map[chess.Position]Piece{
    chess.PositionFromString("g3"): piece,
})

... or you can place a piece on an existing field:

err := squares.PlacePiece(piece, chess.PositionFromString("g3"))
Finding pieces, positions

You can find your placed pieces:

piece, err := squares.FindByPosition(chess.PositionFromString("g3"))
if piece != nil {
    // The piece is found
}

... or you can find them in different ways:

var pieceNotation = "K"
var pieceColor = chess.ColorWhite

// Also it finds the position:
piece, position := squares.FindPiece(pieceNotation, pieceColor)
if piece != nil {
    // The piece is found
}

// ... or you can find several pieces with the same notation and the same color:
var piecesIter iter.Seq[Piece] = squares.GetPieces(pieceNotation, pieceColor)

... or you can get all the pieces of a certain color:

pieces = squares.GetAllPieces(pieceColor)

Conversely, you can get the position of a piece placed on it:

pos := squares.GetByPiece(piece)
if !pos.IsNull() {
    // Position is found
}

Moving pieces

You can move a piece from one position to another:

capturedPiece, err := squares.MovePiece(chess.PositionFromString("c3"), chess.PositionFromString("h8"))
if capturedPiece != nil {
    // If true, then there was a piece on the "h8" square.
}

... or you can move the piece, call a callback, and then return the board to its original position:

err := squares.MovePiece(chess.PositionFromString("c3"), chess.PositionFromString("h8"), func () {
    // Do things within this new temporary position
})
Iteration over squares

There are different ways to iterate over squares. All these methods are built on the Go standard package iter. Here is one of them, which goes through all the squares starting from the very first one and ending with the edge square:

for pos, piece := range square.Iter() {
    if piece != nil {
        // There is a piece at that position
    }
}

... or you can iterate over rows:

// Switch the iteration direction
backwards = false
for rank, row := range square.Iter(backwards) {
    for file, piece := range row {
        if piece != nil {
            // There is a piece
        }

        pos := chess.NewPosition(file, rank)
    }
}

... or iterate over squares in a given direction:

// Traverse squares on the same file and the next rank
dir1 := chess.DirectionTop
// Traverse squares on the previous file and the same rank
dir2 := chess.DirectionBottom
// Traverse diagonally down and to the right
dir3 := chess.DirectionTopRight
// Traverse diagonally up and to the left
dir4 := chess.DirectionBottomLeft
// Use a custom direction
dir5 := position.New(chess.File(2), chess.Rank(1))
// and so on...

fromPos := chess.PositionFromString("d4")
for pos, piece := range square.IterByDirection(fromPos, dir1) {
    if piece != nil {
        // There is a piece on the position
    }
}
Positions, files, ranks

The chess.Position structure is used for working with positions. It contains two fields: File and Rank. The fields correspond to types chess.File and chess.Rank respectively. A file can range between chess.FileNull and chess.FileMax. A rank can range between chess.RankNull and chess.RankMax. The engine doesn't expect you to use values outside these ranges.

Files

There is a special type for file representation:

type File int8

There are several built-in file constants that you should use: chess.FileNull, chess.FileMin which equals chess.FileA, chess.FileB ..., chess.FileP which equals chess.FileMax. chess.FileNull is the zero value and does not necessarily mean it is invalid.

You can check if the file has zero value:

var file chess.File
if file.IsNull() {
    // ...
}

or validate the file:

if err := file.Validate(); err != nil {
    // ...
}

You can also get the text representation of the file:

fileStr := file.String()

An empty string for zero value or invalid files, and letters for other files (chess.FileA.String() == "A", chess.FileG.String() == "G" etc.)

Ranks

There is a special type for rank representation:

type Rank int8

There are several built-in rank constants that you should use: chess.RankNull, chess.RankMin which equals chess.Rank1, chess.Rank2 ..., chess.Rank16 which equals chess.RankMax. chess.RankNull is the zero value and does not necessarily mean it is invalid.

You can check if the rank has zero value:

var rank chess.Rank
if rank.IsNull() {
    // ...
}

or validate the rank:

if err := rank.Validate(); err != nil {
    // ...
}

You can also get the text representation of the rank:

rankStr := rank.String()

An empty string for zero value or invalid ranks, and numbers for other ranks (chess.Rank1.String() == "1", chess.Rank10.String() == "10" etc.)

Positions

Create a position in any way convenient for you:

// Create empty position: 
pos := chess.Position{}
pos = chess.NewPositionEmpty()
pos = chess.NewPosition(chess.FileNull, chess.RankNull)
pos = chess.PositionFromString("")

// ... or half-filled position:
pos = chess.Position{File: chess.FileA}
pos = chess.NewPosition(chess.FileNull, chess.Rank8)
pos = chess.PositionFromString("g")
pos = chess.PositionFromString("7")

// ... or full filled positions:
pos = chess.Position{File: chess.FileA, Rank: chess.Rank8}
pos = chess.NewPosition(chess.FileD, chess.Rank2)
pos = chess.PositionFromString("j3")

Get the string representation of the position:

chess.NewPosition(chess.FileNull, chess.RankNull) == ""
chess.NewPosition(chess.FileG, chess.RankNull) == "g"
chess.NewPosition(chess.FileNull, chess.Rank7) == "7"
chess.NewPosition(chess.FileJ, chess.Rank3) == "j3"

A position may have several states:

chess.PositionFromString("j3").IsFull() == true
chess.NewPositionEmpty().IsEmpty() == true
chess.PositionFromString("g").IsValid() == true // It is not empty and full but still valid
chess.PositionFromString("z22").IsValid() == false // Invalid
Pieces

You can get a piece's color:

var piece chess.Piece
color := piece.Color()

... or its notation:

var notation string = piece.Notation()

... or its weight, which evaluates the piece's value on the board:

var pieceWeight uint8 = piece.Weight()

... or check if the piece has moved:

if piece.IsMoved() {
    // ...
}

... or mark it as moved:

piece.MarkMoved()
piece.IsMove() == true 

... or get pseudo moves which the piece generates:

piecePosition := squares.GetByPiece(piece)

var pseudoMoves []chess.Position = piece.PseudoMoves(piecePosition, squares)
States, state types

There are three board state types: chess.StateTypeClear, chess.StateTypeThreat, chess.StateTypeTerminal.

chess.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.

chess.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.

chess.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.

There are states which are built on state types. The chess.State interface provides a string representation and includes a state type. The difference between a state and a state type is that a state type is more abstract, while a state represents a concrete case of the board state.

You can create your own states for various cases:

var (
    StateCheck = chess.NewState("check", chess.StateTypeThreat)
    StateCheckmate = chess.NewState("checkmate", chess.StateTypeTerminal)
    // etc.
)

Also, there is a single built-in engine state, chess.StateClear, with the state type chess.StateTypeClear.

Note that boards contain states:

var board chess.Board
var state chess.State = board.State()
if !state.Type().IsTerminal() {
    // The game is over
}

... which can be changed during the process of working with the board

Metrics

Metrics show meta information about the board. There are metric functions which return metrics.

Use these built-in metric functions to get metrics:

// The number of half-moves made in the game
metr = metric.HalfmoveCounter(board)
// The number of full moves made in the game
metr = metric.FullmoveCounter(board)
// The last move made, or nil if no moves exist
metr = metric.LastMove(board)
// Material values for White and Black as a slice [white, black]
metr = metric.Material(board)
// The material advantage (white - black)
metr = metric.MaterialDifference(board)

fmt.Printf("Metric \"%s\" shows: %v\n", metr.Name(), metr.Value())

... or create your own:

func TurnMetric(board chess.Board) Metric {
    return metric.New("Turn", board.Turn())
}

Note that a metric function should implement the metric.MetricFunc type

Visualizer

Use the visualizer package for displaying your board in the ascii format. It's very useful for debugging your code. Here is a quick example:


// Thus the white side will be at the bottom and the black side at the top
var orientation visualizer.OptionOrientation = visualizer.OptionOrientationDefault
// The black side will be at the bottom and the white side at the top
orientation = visualizer.OptionOrientationReversed
// The white side will be at the bottom if the current turn is White,
// otherwise the black side will be at the bottom
orientation = visualizer.OptionOrientationByTurn

var vis visualizer.Visualizer{
    Options: visualizer.Options{
        Orientation: orientation,
        // If it is true then the visualizer will show ranks at the left and files at the bottom
        DisplayPositions: true,
        // Metric funcs for displaying the board metrics 
        MetricFuncs: [
            metric.HalfmoveCounterFunc,
            metric.LastMove,
            metric.MaterialDifference,
        ],
    }
}

var board chess.Board

// It will show the board in the terminal
vis.Fprintln(board, os.Stdout)

Contributing

Bug reports and contributions are welcome. Please open issues or pull requests against this repository. Keep changes small and add tests for new behavior.

License

The GNU General Public License

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

View Source
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

View Source
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))
)
View Source
var ErrSquareOutOfRange = errors.New("square position is out of range")

ErrSquareOutOfRange is returned when given square position is out of the valid range.

View Source
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.

View Source
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.

const (
	ColorWhite Color = true
	ColorBlack Color = false
)

func (Color) IsBlack added in v1.2.0

func (c Color) IsBlack() bool

IsBlack checks if the color is black.

func (Color) IsWhite added in v1.2.0

func (c Color) IsWhite() bool

IsWhite checks if the color is white.

func (Color) String added in v1.2.0

func (c Color) String() string

type File added in v1.0.2

type File = position.File

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

type Move interface {
	fmt.Stringer
}

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

type Position = position.Position

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 NewPosition(file File, rank Rank) Position

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

func PositionFromString(str string) Position

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

type Rank = position.Rank

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

func NewSquares(edgePosition Position) *Squares

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

func SquaresFromPlacement(
	edgePosition Position,
	placement map[Position]Piece,
) (*Squares, error)

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

func (s *Squares) EdgePosition() Position

EdgePosition returns the edge position of the squares.

func (*Squares) FindByPosition

func (s *Squares) FindByPosition(position Position) (Piece, error)

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

func (s *Squares) FindPiece(notation string, color Color) (Piece, Position)

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

func (s *Squares) GetAllPieces(color Color) iter.Seq[Piece]

GetAllPieces returns all pieces on the squares for a given color.

func (*Squares) GetByPiece

func (s *Squares) GetByPiece(piece Piece) Position

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

func (s *Squares) GetPieces(notation string, color Color) iter.Seq[Piece]

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

func (s *Squares) Iter() iter.Seq2[Position, Piece]

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

func (s *Squares) IterByDirection(
	from, direction Position,
) iter.Seq2[Position, Piece]

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

func (s *Squares) IterOverRows(
	backward bool,
) iter.Seq2[Rank, iter.Seq2[File, Piece]]

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

func (s *Squares) MovePiece(from, to Position) (capturedPiece Piece, err error)

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

func (s *Squares) MovePieceTemporarily(from, to Position, callback func()) error

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

func (s *Squares) PlacePiece(piece Piece, position Position) error

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

func NewState(name string, stateType StateType) State

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) IsClear

func (t StateType) IsClear() bool

IsClear checks if the state type is clear.

func (StateType) IsTerminal

func (t StateType) IsTerminal() bool

IsTerminal checks if the state type indicates a terminal state.

func (StateType) IsThreat

func (t StateType) IsThreat() bool

IsThreat checks if the state type indicates a threat on the board.

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.

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.

Jump to

Keyboard shortcuts

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