chess

package module
v0.0.0-...-e387cd9 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2020 License: MIT Imports: 13 Imported by: 0

README

chess

GoDoc Coverage Status Go Report Card License

Introduction

Chess is a go library which provides common chess utilities such as move generation, turn management, checkmate detection, PGN encoding, and others. It is well tested and optimized for performance and has no dependencies outside the standard library.

Installation

The package can be installed using "go get".

go get -u github.com/notnil/chess

Usage

Movement

Chess exposes two ways of moving: valid move generation and notation parsing. Valid moves are calculated from the current position and are returned from the ValidMoves method. Even if the client isn't a go program (e.g. a web app) the list of moves can be serialized into their string representation and supplied to the client. Once a move is selected the MoveStr method can be used to parse the selected move's string.

Valid Moves

Valid moves generated from the game's current position:

game := chess.NewGame()
moves := game.ValidMoves()
game.Move(moves[0])
fmt.Println(moves[0]) // b1a3
Parse Notation

Game's MoveStr method accepts string input using the default Algebraic Notation:

game := chess.NewGame()
if err := game.MoveStr("e4"); err != nil {
	// handle error
}
Outcome

The outcome of the match is calculated automatically from the inputted moves if possible. Draw agreements, resignations, and other human initiated outcomes can be inputted as well.

Checkmate

Black wins by checkmate (Fool's Mate):

game := chess.NewGame()
game.MoveStr("f3")
game.MoveStr("e6")
game.MoveStr("g4")
game.MoveStr("Qh4")
fmt.Println(game.Outcome()) // 0-1
fmt.Println(game.Method()) // Checkmate
/*
 A B C D E F G H
8♜ ♞ ♝ - ♚ ♝ ♞ ♜
7♟ ♟ ♟ ♟ - ♟ ♟ ♟
6- - - - ♟ - - -
5- - - - - - - -
4- - - - - - ♙ ♛
3- - - - - ♙ - -
2♙ ♙ ♙ ♙ ♙ - - ♙
1♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
*/
Stalemate

Black king has no safe move:

fenStr := "k1K5/8/8/8/8/8/8/1Q6 w - - 0 1"
fen, _ := chess.FEN(fenStr)
game := chess.NewGame(fen)
game.MoveStr("Qb6")
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method())  // Stalemate
/*
 A B C D E F G H
8♚ - ♔ - - - - -
7- - - - - - - -
6- ♕ - - - - - -
5- - - - - - - -
4- - - - - - - -
3- - - - - - - -
2- - - - - - - -
1- - - - - - - -
*/
Resignation

Black resigns and white wins:

game := chess.NewGame()
game.MoveStr("f3")
game.Resign(chess.Black)
fmt.Println(game.Outcome()) // 1-0
fmt.Println(game.Method()) // Resignation
Draw Offer

Draw by mutual agreement:

game := chess.NewGame()
game.Draw(chess.DrawOffer)
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method())  // DrawOffer
Threefold Repetition

Threefold repetition occurs when the position repeats three times (not necessarily in a row). If this occurs both players have the option of taking a draw, but aren't required until Fivefold Repetition.

game := chess.NewGame()
moves := []string{"Nf3", "Nf6", "Ng1", "Ng8", "Nf3", "Nf6", "Ng1", "Ng8"}
for _, m := range moves {
	game.MoveStr(m)
}
fmt.Println(game.EligibleDraws()) //  [DrawOffer ThreefoldRepetition]
Fivefold Repetition

According to the FIDE Laws of Chess if a position repeats five times then the game is drawn automatically.

game := chess.NewGame()
moves := []string{
	"Nf3", "Nf6", "Ng1", "Ng8",
	"Nf3", "Nf6", "Ng1", "Ng8",
	"Nf3", "Nf6", "Ng1", "Ng8",
	"Nf3", "Nf6", "Ng1", "Ng8",
}
for _, m := range moves {
	game.MoveStr(m)
}
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method()) // FivefoldRepetition
Fifty Move Rule

Fifty-move rule allows either player to claim a draw if no capture has been made and no pawn has been moved in the last fifty moves.

fen, _ := chess.FEN("2r3k1/1q1nbppp/r3p3/3pP3/pPpP4/P1Q2N2/2RN1PPP/2R4K b - b3 100 23")
game := chess.NewGame(fen)
game.Draw(chess.FiftyMoveRule)
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method()) // FiftyMoveRule
Seventy Five Move Rule

According to FIDE Laws of Chess Rule 9.6b if 75 consecutive moves have been made without movement of any pawn or any capture, the game is drawn unless the last move was checkmate.

fen, _ := chess.FEN("2r3k1/1q1nbppp/r3p3/3pP3/pPpP4/P1Q2N2/2RN1PPP/2R4K b - b3 149 23")
game := chess.NewGame(fen)
game.MoveStr("Kf8")
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method()) // SeventyFiveMoveRule
Insufficient Material

Impossibility of checkmate, or insufficient material, results when neither white or black has the pieces remaining to checkmate the opponent.

fen, _ := chess.FEN("8/2k5/8/8/8/3K4/8/8 w - - 1 1")
game := chess.NewGame(fen)
fmt.Println(game.Outcome()) // 1/2-1/2
fmt.Println(game.Method()) // InsufficientMaterial
PGN

PGN, or Portable Game Notation, is the most common serialization format for chess matches. PGNs include move history and metadata about the match. Chess includes the ability to read and write the PGN format.

Example PGN
[Event "F/S Return Match"]
[Site "Belgrade, Serbia JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
[Result "1/2-1/2"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 {This opening is called the Ruy Lopez.}
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7
11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
Nf2 42. g4 Bd3 43. Re6 1/2-1/2
Read PGN

PGN supplied as an optional parameter to the NewGame constructor:

pgn, err := chess.PGN(pgnReader)
if err != nil {
	// handle error
}
game := chess.NewGame(pgn)
Write PGN

Moves and tag pairs added to the PGN output:

game := chess.NewGame()
game.AddTagPair("Event", "F/S Return Match")
game.MoveStr("e4")
game.MoveStr("e5")
fmt.Println(game)
/*
[Event "F/S Return Match"]

1.e4 e5  *
*/
FEN

FEN, or Forsyth–Edwards Notation, is the standard notation for describing a board position. FENs include piece positions, turn, castle rights, en passant square, half move counter (for 50 move rule), and full move counter.

Read FEN

FEN supplied as an optional parameter to the NewGame constructor:

fen, err := chess.FEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
if err != nil {
	// handle error
}
game := chess.NewGame(fen)
Write FEN

Game's current position outputted in FEN notation:

game := chess.NewGame()
pos := game.Position()
fmt.Println(pos.String()) // rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
Notations

Chess Notation define how moves are encoded in a serialized format. Chess uses a notation when converting to and from PGN and for accepting move text.

Algebraic Notation

Algebraic Notation (or Standard Algebraic Notation) is the official chess notation used by FIDE. Examples: e2, e5, O-O (short castling), e8=Q (promotion)

game := chess.NewGame(chess.UseNotation(chess.AlgebraicNotation{}))
game.MoveStr("e4")
game.MoveStr("e5")
fmt.Println(game) // 1.e4 e5  *
Long AlgebraicNotation Notation

LongAlgebraicNotation is a more computer friendly alternative to algebraic notation. This notation uses the same format as the UCI (Universal Chess Interface). Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion)

game := chess.NewGame(chess.UseNotation(chess.LongAlgebraicNotation{}))
game.MoveStr("e2e4")
game.MoveStr("e7e5")
fmt.Println(game) // 1.e2e4 e7e5  *
Visualization

Chess has multiple ways to visualize board positions for debugging and presentation.

Text Representation

Board's Draw() method can be used to visualize a position using unicode chess symbols.

game := chess.NewGame()
fmt.Println(game.Position().Board().Draw())
/*
 A B C D E F G H
8♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟
6- - - - - - - -
5- - - - - - - -
4- - - - - - - -
3- - - - - - - -
2♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
*/
SVG Representation

chessimg is an image utility designed to work with the chess package to render an SVG of a chess position. It presents configuration options such as dark and white square colors and squares to highlight.

// create file
f, err := os.Create("example.svg")
if err != nil {
	// handle error
}
defer f.Close()

// create board position
fenStr := "rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b KQkq - 0 1"
pos := &chess.Position{}
if err := pos.UnmarshalText([]byte(fenStr)); err != nil {
	// handle error
}

// write board SVG to file
yellow := color.RGBA{255, 255, 0, 1}
mark := chessimg.MarkSquares(yellow, chess.D2, chess.D4)
if err := chessimg.SVG(f, pos.Board(), mark); err != nil {
	// handle error
}

rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b KQkq - 0 1

Example Program

Valid moves are randomly selected until the game is over:

package main

import (
	"fmt"
	"math/rand"

	"github.com/notnil/chess"
)

func main() {
	game := chess.NewGame()
	// generate moves until game is over
	for game.Outcome() == chess.NoOutcome {
		// select a random move
		moves := game.ValidMoves()
		move := moves[rand.Intn(len(moves))]
		game.Move(move)
	}
	// print outcome and game PGN
	fmt.Println(game.Position().Board().Draw())
	fmt.Printf("Game completed. %s by %s.\n", game.Outcome(), game.Method())
	fmt.Println(game.String())    
}

Performance

Chess has been performance tuned, using pprof, with the goal of being fast enough for use by chess bots. The original map based board representation was replaced by bitboards resulting in a large performance increase.

Benchmarks

The benchmarks can be run with the following command:

go test -bench=.

Results from the baseline 2015 MBP:

BenchmarkBitboardReverse-4              2000000000               1.01 ns/op
BenchmarkStalemateStatus-4                500000              3116 ns/op
BenchmarkInvalidStalemateStatus-4         500000              2290 ns/op
BenchmarkPositionHash-4                  1000000              1864 ns/op
BenchmarkValidMoves-4                     100000             13445 ns/op
BenchmarkPGN-4                               300           5549192 ns/op

Documentation

Overview

Package chess is a go library designed to accomplish the following:

  • chess game / turn management
  • move validation
  • PGN encoding / decoding
  • FEN encoding / decoding

Using Moves

game := chess.NewGame()
moves := game.ValidMoves()
game.Move(moves[0])

Using Algebraic Notation

game := chess.NewGame()
game.MoveStr("e4")

Using PGN

pgn, _ := chess.PGN(pgnReader)
game := chess.NewGame(pgn)

Using FEN

fen, _ := chess.FEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
game := chess.NewGame(fen)

Random Game

package main

import (
    "fmt"
    "math/rand"

    "github.com/notnil/chess"
)

func main() {
    game := chess.NewGame()
    // generate moves until game is over
    for game.Outcome() == chess.NoOutcome {
        // select a random move
        moves := game.ValidMoves()
        move := moves[rand.Intn(len(moves))]
        game.Move(move)
    }
    // print outcome and game PGN
    fmt.Println(game.Position().Board().Draw())
    fmt.Printf("Game completed. %s by %s.\n", game.Outcome(), game.Method())
    fmt.Println(game.String())
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FEN

func FEN(fen string) (func(*Game), error)

FEN takes a string and returns a function that updates the game to reflect the FEN data. Since FEN doesn't encode prior moves, the move list will be empty. The returned function is designed to be used in the NewGame constructor. An error is returned if there is a problem parsing the FEN data.

func PGN

func PGN(r io.Reader) (func(*Game), error)

PGN takes a reader and returns a function that updates the game to reflect the PGN data. The PGN can use any move notation supported by this package. The returned function is designed to be used in the NewGame constructor. An error is returned if there is a problem parsing the PGN data.

func TagPairs

func TagPairs(tagPairs []*TagPair) func(*Game)

TagPairs returns a function that sets the tag pairs to the given value. The returned function is designed to be used in the NewGame constructor.

func UseNotation

func UseNotation(n Notation) func(*Game)

UseNotation returns a function that sets the game's notation to the given value. The notation is used to parse the string supplied to the MoveStr() method as well as the any PGN output. The returned function is designed to be used in the NewGame constructor.

Types

type AlgebraicNotation

type AlgebraicNotation struct{}

AlgebraicNotation (or Standard Algebraic Notation) is the official chess notation used by FIDE. Examples: e2, e5, O-O (short castling), e8=Q (promotion)

func (AlgebraicNotation) Decode

func (_ AlgebraicNotation) Decode(pos *Position, s string) (*Move, error)

Decode implements the Decoder interface.

func (AlgebraicNotation) Encode

func (_ AlgebraicNotation) Encode(pos *Position, m *Move) string

Encode implements the Encoder interface.

func (AlgebraicNotation) String

func (_ AlgebraicNotation) String() string

String implements the fmt.Stringer interface and returns the notation's name.

type Board

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

A Board represents a chess board and its relationship between squares and pieces.

func NewBoard

func NewBoard(m map[Square]Piece) *Board

NewBoard returns a board from a square to piece mapping.

func (*Board) Draw

func (b *Board) Draw() string

Draw returns visual representation of the board useful for debugging.

func (*Board) MarshalBinary

func (b *Board) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface and returns the bitboard representations as a array of bytes. Bitboads are encoded in the following order: WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight WhitePawn, BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn

func (*Board) MarshalText

func (b *Board) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface and returns a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

func (*Board) Piece

func (b *Board) Piece(sq Square) Piece

Piece returns the piece for the given square.

func (*Board) SquareMap

func (b *Board) SquareMap() map[Square]Piece

SquareMap returns a mapping of squares to pieces. A square is only added to the map if it is occupied.

func (*Board) String

func (b *Board) String() string

String implements the fmt.Stringer interface and returns a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

func (*Board) UnmarshalBinary

func (b *Board) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface and parses the bitboard representations as a array of bytes. Bitboads are decoded in the following order: WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight WhitePawn, BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn

func (*Board) UnmarshalText

func (b *Board) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnarshaler interface and takes a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

type CastleRights

type CastleRights string

CastleRights holds the state of both sides castling abilities.

func (CastleRights) CanCastle

func (cr CastleRights) CanCastle(c Color, side Side) bool

CanCastle returns true if the given color and side combination can castle, otherwise returns false.

func (CastleRights) String

func (cr CastleRights) String() string

String implements the fmt.Stringer interface and returns a FEN compatible string. Ex. KQq

type Color

type Color int8

Color represents the color of a chess piece.

const (
	// NoColor represents no color
	NoColor Color = iota
	// White represents the color white
	White
	// Black represents the color black
	Black
)

func (Color) Name

func (c Color) Name() string

Name returns a display friendly name.

func (Color) Other

func (c Color) Other() Color

Other returns the opposie color of the receiver.

func (Color) String

func (c Color) String() string

String implements the fmt.Stringer interface and returns the color's FEN compatible notation.

type Decoder

type Decoder interface {
	Decode(pos *Position, s string) (*Move, error)
}

Decoder is the interface implemented by objects that can decode a string into a move given the position. It is not the decoders responsibility to validate the move. An error is returned if the string could not be decoded.

type Encoder

type Encoder interface {
	Encode(pos *Position, m *Move) string
}

Encoder is the interface implemented by objects that can encode a move into a string given the position. It is not the encoders responsibility to validate the move.

type File

type File int8

A File is the file of a square.

const (
	FileA File = iota
	FileB
	FileC
	FileD
	FileE
	FileF
	FileG
	FileH
)

func (File) String

func (f File) String() string

type Game

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

A Game represents a single chess game.

func GamesFromPGN

func GamesFromPGN(r io.Reader) ([]*Game, error)

GamesFromPGN returns all PGN decoding games from the reader. It is designed to be used decoding multiple PGNs in the same file. An error is returned if there is an issue parsing the PGNs.

func NewGame

func NewGame(options ...func(*Game)) *Game

NewGame defaults to returning a game in the standard opening position. Options can be given to configure the game's initial state.

func (*Game) AddTagPair

func (g *Game) AddTagPair(k, v string) bool

AddTagPair adds or updates a tag pair with the given key and value and returns true if the value is overwritten.

func (*Game) Clone

func (g *Game) Clone() *Game

func (*Game) Draw

func (g *Game) Draw(method Method) error

Draw attempts to draw the game by the given method. If the method is valid, then the game is updated to a draw by that method. If the method isn't valid then an error is returned.

func (*Game) EligibleDraws

func (g *Game) EligibleDraws() []Method

EligibleDraws returns valid inputs for the Draw() method.

func (*Game) FEN

func (g *Game) FEN() string

FEN returns the FEN notation of the current position.

func (*Game) GetTagPair

func (g *Game) GetTagPair(k string) *TagPair

GetTagPair returns the tag pair for the given key or nil if it is not present.

func (*Game) MarshalText

func (g *Game) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface and encodes the game's PGN.

func (*Game) Method

func (g *Game) Method() Method

Method returns the method in which the outcome occurred.

func (*Game) Move

func (g *Game) Move(m *Move) error

Move updates the game with the given move. An error is returned if the move is invalid or the game has already been completed.

func (*Game) MoveStr

func (g *Game) MoveStr(s string) error

MoveStr decodes the given string in game's notation and calls the Move function. An error is returned if the move can't be decoded or the move is invalid.

func (*Game) Moves

func (g *Game) Moves() []*Move

Moves returns the move history of the game.

func (*Game) Outcome

func (g *Game) Outcome() Outcome

Outcome returns the game outcome.

func (*Game) Position

func (g *Game) Position() *Position

Position returns the game's current position.

func (*Game) Positions

func (g *Game) Positions() []*Position

Positions returns the position history of the game.

func (*Game) RemoveTagPair

func (g *Game) RemoveTagPair(k string) bool

RemoveTagPair removes the tag pair for the given key and returns true if a tag pair was removed.

func (*Game) Resign

func (g *Game) Resign(color Color)

Resign resigns the game for the given color. If the game has already been completed then the game is not updated.

func (*Game) String

func (g *Game) String() string

String implements the fmt.Stringer interface and returns the game's PGN.

func (*Game) TagPairs

func (g *Game) TagPairs() []*TagPair

TagPairs returns the game's tag pairs.

func (*Game) UnmarshalText

func (g *Game) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnarshaler interface and assumes the data is in the PGN format.

func (*Game) ValidMoves

func (g *Game) ValidMoves() []*Move

ValidMoves returns a list of valid moves in the current position.

type LongAlgebraicNotation

type LongAlgebraicNotation struct{}

LongAlgebraicNotation is a more computer friendly alternative to algebraic notation. This notation uses the same format as the UCI (Universal Chess Interface). Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion)

func (LongAlgebraicNotation) Decode

func (_ LongAlgebraicNotation) Decode(pos *Position, s string) (*Move, error)

Decode implements the Decoder interface.

func (LongAlgebraicNotation) Encode

func (_ LongAlgebraicNotation) Encode(pos *Position, m *Move) string

Encode implements the Encoder interface.

func (LongAlgebraicNotation) String

func (_ LongAlgebraicNotation) String() string

String implements the fmt.Stringer interface and returns the notation's name.

type Method

type Method uint8

A Method is the method that generated the outcome.

const (
	// NoMethod indicates that an outcome hasn't occurred or that the method can't be determined.
	NoMethod Method = iota
	// Checkmate indicates that the game was won checkmate.
	Checkmate
	// Resignation indicates that the game was won by resignation.
	Resignation
	// DrawOffer indicates that the game was drawn by a draw offer.
	DrawOffer
	// Stalemate indicates that the game was drawn by stalemate.
	Stalemate
	// ThreefoldRepetition indicates that the game was drawn when the game
	// state was repeated three times and a player requested a draw.
	ThreefoldRepetition
	// FivefoldRepetition indicates that the game was automatically drawn
	// by the game state being repeated five times.
	FivefoldRepetition
	// FiftyMoveRule indicates that the game was drawn by the half
	// move clock being one hundred or greater when a player requested a draw.
	FiftyMoveRule
	// SeventyFiveMoveRule indicates that the game was automatically drawn
	// when the half move clock was one hundred and fifty or greater.
	SeventyFiveMoveRule
	// InsufficientMaterial indicates that the game was automatically drawn
	// because there was insufficient material for checkmate.
	InsufficientMaterial
)

func (Method) String

func (i Method) String() string

type Move

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

A Move is the movement of a piece from one square to another.

func (*Move) HasTag

func (m *Move) HasTag(tag MoveTag) bool

HasTag returns true if the move contains the MoveTag given.

func (*Move) Promo

func (m *Move) Promo() PieceType

Promo returns promotion piece type of the move.

func (*Move) S1

func (m *Move) S1() Square

S1 returns the origin square of the move.

func (*Move) S2

func (m *Move) S2() Square

S2 returns the destination square of the move.

func (*Move) String

func (m *Move) String() string

String returns a string useful for debugging. String doesn't return algebraic notation.

type MoveTag

type MoveTag uint16

A MoveTag represents a notable consequence of a move.

const (
	// KingSideCastle indicates that the move is a king side castle.
	KingSideCastle MoveTag = 1 << iota
	// QueenSideCastle indicates that the move is a queen side castle.
	QueenSideCastle
	// Capture indicates that the move captures a piece.
	Capture
	// EnPassant indicates that the move captures via en passant.
	EnPassant
	// Check indicates that the move puts the opposing player in check.
	Check
)

type Notation

type Notation interface {
	Encoder
	Decoder
}

Notation is the interface implemented by objects that can encode and decode moves.

type Outcome

type Outcome string

A Outcome is the result of a game.

const (
	// NoOutcome indicates that a game is in progress or ended without a result.
	NoOutcome Outcome = "*"
	// WhiteWon indicates that white won the game.
	WhiteWon Outcome = "1-0"
	// BlackWon indicates that black won the game.
	BlackWon Outcome = "0-1"
	// Draw indicates that game was a draw.
	Draw Outcome = "1/2-1/2"
)

func (Outcome) String

func (o Outcome) String() string

String implements the fmt.Stringer interface

type Piece

type Piece int8

Piece is a piece type with a color.

const (
	// NoPiece represents no piece
	NoPiece Piece = iota
	// WhiteKing is a white king
	WhiteKing
	// WhiteQueen is a white queen
	WhiteQueen
	// WhiteRook is a white rook
	WhiteRook
	// WhiteBishop is a white bishop
	WhiteBishop
	// WhiteKnight is a white knight
	WhiteKnight
	// WhitePawn is a white pawn
	WhitePawn
	// BlackKing is a black king
	BlackKing
	// BlackQueen is a black queen
	BlackQueen
	// BlackRook is a black rook
	BlackRook
	// BlackBishop is a black bishop
	BlackBishop
	// BlackKnight is a black knight
	BlackKnight
	// BlackPawn is a black pawn
	BlackPawn
)

func (Piece) Color

func (p Piece) Color() Color

Color returns the color of the piece.

func (Piece) String

func (p Piece) String() string

String implements the fmt.Stringer interface

func (Piece) Type

func (p Piece) Type() PieceType

Type returns the type of the piece.

type PieceType

type PieceType int8

PieceType is the type of a piece.

const (
	// NoPieceType represents a lack of piece type
	NoPieceType PieceType = iota
	// King represents a king
	King
	// Queen represents a queen
	Queen
	// Rook represents a rook
	Rook
	// Bishop represents a bishop
	Bishop
	// Knight represents a knight
	Knight
	// Pawn represents a pawn
	Pawn
)

func PieceTypes

func PieceTypes() [6]PieceType

PieceTypes returns a slice of all piece types.

func (PieceType) String

func (p PieceType) String() string

type Position

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

Position represents the state of the game without reguard to its outcome. Position is translatable to FEN notation.

func (*Position) Board

func (pos *Position) Board() *Board

Board returns the position's board.

func (*Position) CastleRights

func (pos *Position) CastleRights() CastleRights

CastleRights returns the castling rights of the position.

func (*Position) Hash

func (pos *Position) Hash() [16]byte

Hash returns a unique hash of the position

func (*Position) MarshalText

func (pos *Position) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface and encodes the position's FEN.

func (*Position) Status

func (pos *Position) Status() Method

Status returns the position's status as one of the outcome methods. Possible returns values include Checkmate, Stalemate, and NoMethod.

func (*Position) String

func (pos *Position) String() string

String implements the fmt.Stringer interface and returns a string with the FEN format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1

func (*Position) Turn

func (pos *Position) Turn() Color

Turn returns the color to move next.

func (*Position) UnmarshalText

func (pos *Position) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnarshaler interface and assumes the data is in the FEN format.

func (*Position) Update

func (pos *Position) Update(m *Move) *Position

Update returns a new position resulting from the given move. The move itself isn't validated, if validation is needed use Game's Move method. This method is more performant for bots that rely on the ValidMoves because it skips redundant validation.

func (*Position) ValidMoves

func (pos *Position) ValidMoves() []*Move

ValidMoves returns a list of valid moves for the position.

type Rank

type Rank int8

A Rank is the rank of a square.

const (
	Rank1 Rank = iota
	Rank2
	Rank3
	Rank4
	Rank5
	Rank6
	Rank7
	Rank8
)

func (Rank) String

func (r Rank) String() string

type Side

type Side int

Side represents a side of the board.

const (
	// KingSide is the right side of the board from white's perspective.
	KingSide Side = iota + 1
	// QueenSide is the left side of the board from white's perspective.
	QueenSide
)

type Square

type Square int8

A Square is one of the 64 rank and file combinations that make up a chess board.

const (
	NoSquare Square = iota - 1
	A1
	B1
	C1
	D1
	E1
	F1
	G1
	H1
	A2
	B2
	C2
	D2
	E2
	F2
	G2
	H2
	A3
	B3
	C3
	D3
	E3
	F3
	G3
	H3
	A4
	B4
	C4
	D4
	E4
	F4
	G4
	H4
	A5
	B5
	C5
	D5
	E5
	F5
	G5
	H5
	A6
	B6
	C6
	D6
	E6
	F6
	G6
	H6
	A7
	B7
	C7
	D7
	E7
	F7
	G7
	H7
	A8
	B8
	C8
	D8
	E8
	F8
	G8
	H8
)

func (Square) File

func (sq Square) File() File

File returns the square's file.

func (Square) Rank

func (sq Square) Rank() Rank

Rank returns the square's rank.

func (Square) String

func (sq Square) String() string

type TagPair

type TagPair struct {
	Key   string
	Value string
}

TagPair represents metadata in a key value pairing used in the PGN format.

Jump to

Keyboard shortcuts

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