Documentation
¶
Overview ¶
Package chessongo provides chess rules, legal move generation, FEN loading, PGN import/export, undo support, and search-oriented traversal helpers.
Standard chess is the default rule set. Chess960, King of the Hill, and Three-check are available through explicit variant constructors or LoadFENWithVariant.
The stable method API includes Game.FEN, Game.SideToMove, Game.BoardView, Game.Snapshot, Game.LegalMovesInto, Game.DrawStatus, Game.PositionKey, Game.TryMoveUCI, Game.TryMoveSAN, Game.Clone, and Game.Status. Prefer ParseSquare and PieceFromRune over the package-level lookup maps.
Index ¶
- Constants
- Variables
- func Chess960BackRank(position int) (string, error)
- func Chess960StartingFEN(position int) (string, error)
- func CoordsToIndex(rank, file int) uint
- func IsCoordsOutofBoard(rank, file int) bool
- func PrintBitboard(bb Bitboard, title string)
- func ValidateChess960BackRank(rank string) error
- type Bitboard
- type BoardView
- type CastlingRights
- type Color
- type Direction
- type DrawStatus
- type EPDRecord
- type FENError
- type FENField
- type Game
- func (g *Game) Board() [64]Piece
- func (g *Game) BoardView() BoardView
- func (g *Game) CanClaimFiftyMoveRule() bool
- func (g *Game) CanClaimThreefoldRepetition() bool
- func (g *Game) CanMove(m Move) bool
- func (g *Game) CastlingRights() CastlingRights
- func (g *Game) Clone() *Game
- func (g *Game) ComputeIsCheck() bool
- func (g *Game) CopyLegalMoves(dst []Move) []Move
- func (g *Game) DrawStatus() DrawStatus
- func (g *Game) EnPassantSquare() Square
- func (g *Game) FEN() string
- func (g *Game) FullMoveNumber() int
- func (g *Game) GenerateLegalMoves()
- func (g *Game) GenerateLegalMovesFast()
- func (g *Game) GeneratePseudoMoves()
- func (g *Game) GetColors() (Color, Color)
- func (g *Game) GetMoveSan(m Move) string
- func (g *Game) GetMoveSanWithoutSuffix(m Move) string
- func (g *Game) GetOthersOfSameKindMovingToSameTargetCounts(themove Move) (otherOfSameKind int, onSameFileCount int, onSameRankCount int)
- func (g *Game) GetPawns() (Bitboard, Bitboard)
- func (g *Game) HalfMoveClock() int
- func (g *Game) IsFivefoldRepetition() bool
- func (g *Game) IsFivefoldRepetitionDraw() bool
- func (g *Game) IsSeventyFiveMoveRuleDraw() bool
- func (g *Game) IsStalemate() bool
- func (g *Game) IsTerminal() bool
- func (g *Game) IsToPromotionRank(to Square) bool
- func (g *Game) LegalMovesInto(dst []Move) []Move
- func (g *Game) LegalMovesList() []Move
- func (g *Game) LoadFEN(fen string) error
- func (g *Game) LoadFENWithVariant(fen string, variant Variant) error
- func (g *Game) LoadPGN(pgn string) error
- func (g *Game) MakeMove(m Move)
- func (g *Game) MakeMoveFast(m Move)
- func (g *Game) MarshalBinary() ([]byte, error)
- func (g *Game) OccupiedSquares() Bitboard
- func (g *Game) PGN() string
- func (g *Game) PGNResult() string
- func (g *Game) PGNTags() map[string]string
- func (g *Game) ParseMoveSAN(san string) (Move, error)
- func (g *Game) ParseMoveUCI(uci string) (Move, error)
- func (g *Game) PieceAt(square Square) (Piece, bool)
- func (g *Game) Pieces(color Color) Bitboard
- func (g *Game) PiecesOfKind(color Color, kind Piece) Bitboard
- func (g *Game) PositionKey() uint64
- func (g *Game) PrintBoard(title string)
- func (g *Game) Reset()
- func (g *Game) SEE(from, to Square) int
- func (g *Game) SeedPositionHistory(keys []uint64)
- func (g *Game) ShouldIncFullMoves(m Move) bool
- func (g *Game) ShouldResetHalfMoves(m Move) bool
- func (g *Game) SideToMove() Color
- func (g *Game) Snapshot() GameSnapshot
- func (g *Game) Status() GameStatus
- func (g *Game) ToFEN() string
- func (g *Game) TryMove(m Move) error
- func (g *Game) TryMoveFromCoords(from, to string, promotion ...Piece) error
- func (g *Game) TryMoveSAN(san string) error
- func (g *Game) TryMoveUCI(uci string) error
- func (g *Game) UndoMove(m Move)
- func (g *Game) UndoMoveFast(m Move)
- func (g *Game) UnmarshalBinary(data []byte) error
- func (g *Game) Variant() Variant
- func (g *Game) WillMoveCauseCheck(m Move) bool
- func (g *Game) Winner() Color
- type GameSnapshot
- type GameState
- type GameStatus
- type IllegalMoveError
- type IllegalMoveReason
- type Move
- func NewCastlingMove(from, to Square) Move
- func NewEnPassantMove(from, to Square, captured Piece) Move
- func NewMove(from, to Square, captured Piece) Move
- func NewMoveFromCoords(from, to string) (Move, error)
- func NewMoveFromUCI(uci string) (Move, error)
- func NewPromotionMove(from, to Square, captured Piece, promotionTo Piece) Move
- func (m Move) From() Square
- func (m Move) GetCapturedPiece() Piece
- func (m Move) GetPromotionTo() Piece
- func (m Move) IsCastlingMove() bool
- func (m Move) IsEnPassant() bool
- func (m Move) IsPromotingTo(promotingTo string) bool
- func (m Move) IsPromotionMove() bool
- func (m Move) To() Square
- func (m Move) ToFromToStrings() (string, string)
- func (m Move) ToString() string
- func (m Move) UCI() string
- type Piece
- type Ray
- type SearchBoard
- type Square
- type Variant
Examples ¶
Constants ¶
const ( CASTLE_WKS = 1 //White king side castling 0001 CASTLE_WQS = 2 //White queen side castling 0010 CASTLE_BKS = 4 //Black king side castling 0100 CASTLE_BQS = 8 //Black queen side castling 1000 )
Castling permissions
const ( W_KING_INIT_SQUARE = 60 // e1 B_KING_INIT_SQUARE = 4 // e8 WKS_KING_TO_SQUARE = 62 // g1 WQS_KING_TO_SQUARE = 58 // c1 BKS_KING_TO_SQUARE = 6 // g8 BQS_KING_TO_SQUARE = 2 // c8 WKS_ROOK_ORIGINAL_SQUARE = 63 // h1 WQS_ROOK_ORIGINAL_SQUARE = 56 // a1 BKS_ROOK_ORIGINAL_SQUARE = 7 // h8 BQS_ROOK_ORIGINAL_SQUARE = 0 // a8 )
castling squares
const ( DIRECTION_N = iota DIRECTION_S DIRECTION_E DIRECTION_W DIRECTION_NE DIRECTION_NW DIRECTION_SE DIRECTION_SW )
Directions of movement
const ( LSB = iota MSB )
Significant bit type
const ( RANK1_MASK Bitboard = 0xFF00000000000000 //1111111100000000000000000000000000000000000000000000000000000000 RANK2_MASK Bitboard = 0xFF000000000000 //0000000011111111000000000000000000000000000000000000000000000000 RANK3_MASK Bitboard = 0xFF0000000000 RANK4_MASK Bitboard = 0xFF00000000 RANK5_MASK Bitboard = 0xFF000000 RANK6_MASK Bitboard = 0xFF0000 RANK7_MASK Bitboard = 0xFF00 RANK8_MASK Bitboard = 0xFF //0000000000000000000000000000000000000000000000000000000011111111 FILE_A_MASK = 0x0101010101010101 //00000000000100000001000000010000000100000001000000010000000100000001 FILE_B_MASK = 0x0202020202020202 FILE_C_MASK = 0x0404040404040404 FILE_D_MASK = 0x0808080808080808 FILE_E_MASK = 0x1010101010101010 FILE_F_MASK = 0x2020202020202020 FILE_G_MASK = 0x4040404040404040 FILE_H_MASK = 0x8080808080808080 //1000000010000000100000001000000010000000100000001000000010000000 )
const ( MOVE_TO_BIT = 6 MOVE_ENPASSANT_BIT = 12 MOVE_CASTLING_BIT = 13 MOVE_PROMOTION_BIT = 14 MOVE_CAPTURE_BIT = 17 MOVE_TO_FROM_MASK = 0x3F MOVE_CAPTURED_MASK = 0x1F MOVE_PROMOTION_MASK = 0x7 )
const ( WHITE = 8 //White 0000 1000 BLACK = 16 //BLACK 0001 0000 NO_COLOR = 0 )
const ( EMPTY = iota // 000 PAWN // 001 KNIGHT // 010 BISHOP // 011 ROOK // 100 QUEEN // 101 KING // 110 )
const ( W_PAWN = WHITE | PAWN // 01001 W_KNIGHT = WHITE | KNIGHT // 01010 W_BISHOP = WHITE | BISHOP // 01011 W_ROOK = WHITE | ROOK // 01100 W_QUEEN = WHITE | QUEEN // 01101 W_KING = WHITE | KING // 01110 B_PAWN = BLACK | PAWN // 10001 B_KNIGHT = BLACK | KNIGHT // 10010 B_BISHOP = BLACK | BISHOP // 10011 B_ROOK = BLACK | ROOK // 10100 B_QUEEN = BLACK | QUEEN // 10101 B_KING = BLACK | KING // 10110 )
const BLACK_MASK = 0x10
const STARTING_POSITION_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
STARTING_POSITION_FEN is the standard chess initial position.
const WHITE_MASK = 0x8
Variables ¶
var ( // ErrInvalidFEN identifies invalid FEN input. ErrInvalidFEN = errors.New("invalid fen") // ErrIllegalMove identifies legal move rejection. ErrIllegalMove = errors.New("illegal move") // ErrInvalidMoveNotation identifies malformed move notation. ErrInvalidMoveNotation = errors.New("invalid move notation") )
var ALL_DIRECTIONS = [8]Direction{ DIRECTION_N, DIRECTION_S, DIRECTION_E, DIRECTION_W, DIRECTION_NE, DIRECTION_NW, DIRECTION_SE, DIRECTION_SW, }
ALL_DIRECTIONS lists all ray directions.
Compatibility: this low-level table is retained for older callers.
var ATTACKS_TO = [64]Bitboard{}
ATTACKS_TO contains ray attacks to each square on an empty board.
Compatibility: this low-level table is retained for older callers.
var BISHOP_DIRECTIONS = [4]Direction{ DIRECTION_NE, DIRECTION_NW, DIRECTION_SE, DIRECTION_SW, }
BISHOP_DIRECTIONS lists the diagonal ray directions.
Compatibility: this low-level table is retained for older callers.
var COORDS_TO_SQUARE = map[string]Square{ "a8": Square(0), "b8": Square(1), "c8": Square(2), "d8": Square(3), "e8": Square(4), "f8": Square(5), "g8": Square(6), "h8": Square(7), "a7": Square(8), "b7": Square(9), "c7": Square(10), "d7": Square(11), "e7": Square(12), "f7": Square(13), "g7": Square(14), "h7": Square(15), "a6": Square(16), "b6": Square(17), "c6": Square(18), "d6": Square(19), "e6": Square(20), "f6": Square(21), "g6": Square(22), "h6": Square(23), "a5": Square(24), "b5": Square(25), "c5": Square(26), "d5": Square(27), "e5": Square(28), "f5": Square(29), "g5": Square(30), "h5": Square(31), "a4": Square(32), "b4": Square(33), "c4": Square(34), "d4": Square(35), "e4": Square(36), "f4": Square(37), "g4": Square(38), "h4": Square(39), "a3": Square(40), "b3": Square(41), "c3": Square(42), "d3": Square(43), "e3": Square(44), "f3": Square(45), "g3": Square(46), "h3": Square(47), "a2": Square(48), "b2": Square(49), "c2": Square(50), "d2": Square(51), "e2": Square(52), "f2": Square(53), "g2": Square(54), "h2": Square(55), "a1": Square(56), "b1": Square(57), "c1": Square(58), "d1": Square(59), "e1": Square(60), "f1": Square(61), "g1": Square(62), "h1": Square(63), }
COORDS_TO_SQUARE maps algebraic coordinates to square indexes.
Compatibility: prefer ParseSquare or ParseUCISquare in new code.
var DIRECTION_LSB_MSP = [8]uint{}
DIRECTION_LSB_MSP identifies the blocking-bit side for each direction.
Compatibility: this low-level table is retained for older callers.
var DIRECTION_SHIFT = [8][2]int{}
DIRECTION_SHIFT contains rank/file deltas for each direction.
Compatibility: this low-level table is retained for older callers.
var FILE_TO_STRING = map[int]string{0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h"}
FILE_TO_STRING maps zero-based file indexes to file strings.
Compatibility: prefer Square.FileLetter in new code.
var KING_ATTACKS_FROM = [64]Bitboard{}
KING_ATTACKS_FROM contains king attacks from each square on an empty board.
Compatibility: this low-level table is retained for older callers.
var KING_RANK_FILE_SHIFTS = [8][2]int{
{-1, -1}, {0, -1}, {1, -1}, {-1, 0},
{1, 0}, {-1, 1}, {0, 1}, {1, 1},
}
KING_RANK_FILE_SHIFTS lists king move rank/file offsets.
Compatibility: this low-level table is retained for older callers.
var KNIGHT_ATTACKS_FROM = [64]Bitboard{}
KNIGHT_ATTACKS_FROM contains knight attacks from each square on an empty board.
Compatibility: this low-level table is retained for older callers.
var KNIGHT_RANK_FILE_SHIFTS = [8][2]int{
{-2, -1}, {-2, 1}, {2, -1}, {2, 1},
{-1, -2}, {-1, 2}, {1, -2}, {1, 2},
}
KNIGHT_RANK_FILE_SHIFTS lists knight move rank/file offsets.
Compatibility: this low-level table is retained for older callers.
var PIECE_TO_RUNE = map[Piece]rune{
W_PAWN: 'P', W_KNIGHT: 'N', W_BISHOP: 'B', W_ROOK: 'R', W_QUEEN: 'Q', W_KING: 'K',
B_PAWN: 'p', B_KNIGHT: 'n', B_BISHOP: 'b', B_ROOK: 'r', B_QUEEN: 'q', B_KING: 'k',
}
PIECE_TO_RUNE maps pieces to FEN runes.
Compatibility: prefer Piece.ToRune in new code.
var RANK_TO_STRING = map[int]string{0: "8", 1: "7", 2: "6", 3: "5", 4: "4", 5: "3", 6: "2", 7: "1"}
RANK_TO_STRING maps zero-based rank indexes to rank strings.
Compatibility: prefer Square.RankDigit in new code.
var RAY_MASKS = [8][64]Bitboard{}
RAY_MASKS contains ray masks for each direction and square.
Compatibility: this low-level table is retained for older callers.
var ROOK_DIRECTIONS = [4]Direction{ DIRECTION_N, DIRECTION_S, DIRECTION_E, DIRECTION_W, }
ROOK_DIRECTIONS lists the orthogonal ray directions.
Compatibility: this low-level table is retained for older callers.
var RUNE_TO_PIECE = map[rune]Piece{ 'P': W_PAWN, 'N': W_KNIGHT, 'B': W_BISHOP, 'R': W_ROOK, 'Q': W_QUEEN, 'K': W_KING, 'p': B_PAWN, 'n': B_KNIGHT, 'b': B_BISHOP, 'r': B_ROOK, 'q': B_QUEEN, 'k': B_KING, }
RUNE_TO_PIECE maps FEN piece runes to pieces.
Compatibility: prefer PieceFromRune in new code.
var SQUARE_TO_COORDS = [64]string{
"a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
"a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
"a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
"a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
"a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
"a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
"a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
"a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1",
}
SQUARE_TO_COORDS maps square indexes to algebraic coordinates.
Compatibility: prefer Square.String or Square.UCI in new code.
var STRING_TO_KIND = map[string]uint{ "P": PAWN, "N": KNIGHT, "B": BISHOP, "R": ROOK, "Q": QUEEN, "K": KING, "p": PAWN, "n": KNIGHT, "b": BISHOP, "r": ROOK, "q": QUEEN, "k": KING, }
STRING_TO_KIND maps piece letters to piece kinds.
Compatibility: this low-level lookup table is retained for older callers.
Functions ¶
func Chess960BackRank ¶
Chess960BackRank returns the white back rank for a Chess960 position ID.
func Chess960StartingFEN ¶
Chess960StartingFEN returns the initial Shredder-FEN position for a Chess960 position ID.
func CoordsToIndex ¶
Convert rank, file coordinates to a 64 based index
func IsCoordsOutofBoard ¶
Tells whether coords are out of board or not
func PrintBitboard ¶
func ValidateChess960BackRank ¶
ValidateChess960BackRank verifies that rank is a legal white Chess960 back rank.
Types ¶
type BoardView ¶
type BoardView struct {
// contains filtered or unexported fields
}
BoardView wraps board internals with read-only accessor methods.
func (BoardView) OccupiedSquares ¶
OccupiedSquares returns the occupied-square bitboard.
func (BoardView) PieceAt ¶
PieceAt returns the piece on square. The bool is false for out-of-range squares.
func (BoardView) PiecesOfKind ¶
PiecesOfKind returns all occupied squares for color and piece kind.
type CastlingRights ¶
type CastlingRights uint8
CastlingRights is a bitset of available castling rights.
const ( // CastlingWhiteKingSide allows white to castle king side. CastlingWhiteKingSide CastlingRights = CASTLE_WKS // CastlingWhiteQueenSide allows white to castle queen side. CastlingWhiteQueenSide CastlingRights = CASTLE_WQS // CastlingBlackKingSide allows black to castle king side. CastlingBlackKingSide CastlingRights = CASTLE_BKS // CastlingBlackQueenSide allows black to castle queen side. CastlingBlackQueenSide CastlingRights = CASTLE_BQS )
func (CastlingRights) Has ¶
func (r CastlingRights) Has(rights CastlingRights) bool
Has reports whether all requested castling rights are present.
func (CastlingRights) String ¶
func (r CastlingRights) String() string
String returns the FEN castling-rights field.
type DrawStatus ¶
type DrawStatus struct {
InsufficientMaterial bool
CanClaimThreefoldRepetition bool
CanClaimFiftyMoveRule bool
FivefoldRepetition bool
SeventyFiveMoveRule bool
}
DrawStatus describes claimable and automatic draw state.
type EPDRecord ¶
EPDRecord is one Extended Position Description record.
func LoadEPDRecords ¶
LoadEPDRecords parses multiple EPD records, skipping blank and comment lines.
func ParseEPD ¶
ParseEPD parses one Extended Position Description record.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
record, err := chessongo.ParseEPD(`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - bm e4 d4; id "initial"; perft 1 20;`)
if err != nil {
panic(err)
}
id, _ := record.ID()
perft, _ := record.PerftExpectations()
fmt.Println(id)
fmt.Println(record.BestMoves())
fmt.Println(perft[1])
}
Output: initial [e4 d4] 20
func (EPDRecord) AvoidMoves ¶
AvoidMoves returns the `am` operands.
type FENError ¶
FENError provides structured context for FEN validation failures.
Example ¶
package main
import (
"errors"
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := &chessongo.Game{}
err := game.LoadFEN("8/8/8/8/8/8/8/8 w - - 0 1")
var fenErr *chessongo.FENError
fmt.Println(errors.Is(err, chessongo.ErrInvalidFEN))
fmt.Println(errors.As(err, &fenErr), fenErr.Field)
}
Output: true true piece placement
type FENField ¶
type FENField string
FENField identifies the FEN field that failed validation.
const ( FENFieldFormat FENField = "format" FENFieldPiecePlacement FENField = "piece placement" FENFieldSideToMove FENField = "side to move" FENFieldCastling FENField = "castling" FENFieldEnPassant FENField = "en passant" FENFieldHalfMoveClock FENField = "halfmove clock" FENFieldFullMoveNumber FENField = "fullmove number" FENFieldVariantState FENField = "variant state" FENFieldLegality FENField = "legality" )
type Game ¶
type Game struct {
// contains filtered or unexported fields
}
func LoadPGNGame ¶
LoadPGNGame is a helper that constructs a fresh board, loads the PGN, and returns the populated board.
func NewChess960Game ¶
NewChess960Game creates a Chess960 game from a position ID in [0, 959].
func NewGameFromFEN ¶
NewGameFromFEN creates a game initialized from FEN.
func NewGameFromFENWithVariant ¶
NewGameFromFENWithVariant creates a game initialized from FEN under a specific variant.
func (*Game) Board ¶
Board returns a copy of the board squares.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := chessongo.NewGame()
board := game.Board()
e1, err := chessongo.ParseSquare("e1")
if err != nil {
panic(err)
}
fmt.Println(board[e1])
fmt.Println(game.CastlingRights().String())
}
Output: wK KQkq
func (*Game) BoardView ¶
BoardView returns a read-only view of the current board internals.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := chessongo.NewGame()
view := game.BoardView()
e1, err := chessongo.ParseSquare("e1")
if err != nil {
panic(err)
}
piece, ok := view.PieceAt(e1)
fmt.Println(ok, piece)
fmt.Println(view.Pieces(chessongo.WHITE).NumberOfSetBits())
}
Output: true wK 16
func (*Game) CanClaimFiftyMoveRule ¶
CanClaimFiftyMoveRule reports whether the halfmove clock allows a 50-move-rule claim.
func (*Game) CanClaimThreefoldRepetition ¶
CanClaimThreefoldRepetition reports whether the current position has occurred at least three times.
func (*Game) CastlingRights ¶
func (g *Game) CastlingRights() CastlingRights
CastlingRights returns the current castling rights bitset.
func (*Game) Clone ¶
Clone returns a deep copy of the game.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := chessongo.NewGame()
analysis := game.Clone()
if err := analysis.TryMoveSAN("e4"); err != nil {
panic(err)
}
fmt.Println(game.FEN())
fmt.Println(analysis.FEN())
}
Output: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1
func (*Game) ComputeIsCheck ¶
Checks whether our king is in check or not
func (*Game) CopyLegalMoves ¶
CopyLegalMoves copies the current legal moves into dst and returns the resulting slice.
It lets search code reuse a caller-owned buffer instead of allocating a fresh slice at each node.
func (*Game) DrawStatus ¶
func (g *Game) DrawStatus() DrawStatus
DrawStatus returns the current draw rule state without exposing mutable fields.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := &chessongo.Game{}
if err := game.LoadFEN("4k3/8/8/8/8/8/6R1/4K3 w - - 99 1"); err != nil {
panic(err)
}
if err := game.TryMoveUCI("g2g3"); err != nil {
panic(err)
}
draw := game.DrawStatus()
fmt.Println(draw.CanClaimFiftyMoveRule)
fmt.Println(draw.SeventyFiveMoveRule)
}
Output: true false
func (*Game) EnPassantSquare ¶
EnPassantSquare returns the current en-passant target square, or 0 if none.
func (*Game) FullMoveNumber ¶
FullMoveNumber returns the fullmove number.
func (*Game) GenerateLegalMovesFast ¶
func (g *Game) GenerateLegalMovesFast()
GenerateLegalMovesFast generates legal moves using check and pin masks.
func (*Game) GetMoveSan ¶
- moving piece letter(exclude pawn) 1.1 originating file letter of the moving piece 1.2 OR: the originating rank digit of the moving piece 1.3 OR: originating square
- if capturing pawn -> include originating file
- x for caputures
- destination square
- PawnPromotion -> "=" followed by promoted piece rune in uppercase
func (*Game) GetMoveSanWithoutSuffix ¶
GetMoveSanWithoutSuffix returns the SAN notation for a move without checking for check (+) or checkmate (#). This prevents expensive board cloning and is sufficient for PGN parsing matching.
func (*Game) GetOthersOfSameKindMovingToSameTargetCounts ¶
func (*Game) HalfMoveClock ¶
HalfMoveClock returns the halfmove clock used by the fifty/seventy-five move rules.
func (*Game) IsFivefoldRepetition ¶
func (*Game) IsFivefoldRepetitionDraw ¶
IsFivefoldRepetitionDraw reports whether fivefold repetition makes the game automatically drawn.
func (*Game) IsSeventyFiveMoveRuleDraw ¶
IsSeventyFiveMoveRuleDraw reports whether the 75-move rule makes the game automatically drawn.
func (*Game) IsStalemate ¶
IsStalemate reports whether the current side to move has no legal moves and is not in check.
func (*Game) IsTerminal ¶
IsTerminal reports whether the game is finished.
func (*Game) IsToPromotionRank ¶
func (*Game) LegalMovesInto ¶
LegalMovesInto copies legal moves into dst and returns the resulting slice.
func (*Game) LegalMovesList ¶
LegalMovesList returns a copy of the currently legal moves.
func (*Game) LoadFEN ¶
LoadFEN initializes the game from a FEN string and refreshes legal moves and status flags.
func (*Game) LoadFENWithVariant ¶
LoadFENWithVariant initializes the game from FEN using variant-specific parsing and rules.
func (*Game) LoadPGN ¶
LoadPGN loads a PGN string into the board, playing all main-line moves and recording position history via Zobrist hashing. Variations and comments are ignored; only the main line is applied.
func (*Game) MakeMoveFast ¶
MakeMoveFast applies a legal move and regenerates legal moves without updating repetition or game-over status.
It is intended for search/perft-style traversal where callers only need the next legal move list and will undo the move before observing public status flags. Use MakeMove for normal game play.
func (*Game) MarshalBinary ¶
MarshalBinary encodes the board state into a byte slice.
func (*Game) OccupiedSquares ¶
OccupiedSquares returns the occupied-square bitboard.
func (*Game) PGN ¶
PGN exports the game as a PGN with tag pairs and main-line movetext.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := chessongo.NewGame()
for _, uci := range []string{"e2e4", "e7e5", "g1f3"} {
if err := game.TryMoveUCI(uci); err != nil {
panic(err)
}
}
fmt.Println(game.PGN())
}
Output: [Event "?"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] 1. e4 e5 2. Nf3 *
func (*Game) ParseMoveSAN ¶
ParseMoveSAN parses SAN by matching against the current legal move list.
func (*Game) ParseMoveUCI ¶
ParseMoveUCI parses a UCI move string into a move request.
func (*Game) PieceAt ¶
PieceAt returns the piece on square. The bool is false for out-of-range squares.
func (*Game) PiecesOfKind ¶
PiecesOfKind returns all occupied squares for color and piece kind.
func (*Game) PositionKey ¶
PositionKey returns the current Zobrist position key.
The key is useful for hash tables and same-version position comparisons. Use FEN when persisting positions across package versions.
func (*Game) PrintBoard ¶
func (*Game) SEE ¶
SEE returns the static exchange evaluation of capturing on `to` with the piece currently on `from`, in centipawns from the moving side's perspective. Positive values mean the moving side gains material; negative values mean it loses material after optimal recaptures.
SEE is square-based, not move-based: it derives the moving side's color from the piece on `from`, not from g.SideToMove. Callers passing promotion or en-passant moves supply the move's from/to squares; SEE detects both from the source piece and engine state (g.enPassant, the rank of `to`).
SEE assumes both sides recapture with their cheapest legal attacker until continuing would lose material. It honors absolute pins (precomputed once at entry) and reveals x-ray attackers as front pieces are removed from a working occupancy. Mid-sequence pawn captures that reach the promotion rank receive the Q-P bonus; promotions are always to queen.
SEE does not validate move legality: it does not check that the initial capture is a real legal move, nor does it filter en-passant discovered checks. Callers should only pass moves the engine considers legal in the current position.
Returns 0 (no error, no panic) when either square is out of range or the piece on `from` is empty.
func (*Game) SeedPositionHistory ¶
SeedPositionHistory appends each Zobrist key in `keys` to the position-history counter, then refreshes the cached game status so any repetition draw triggered by the seeded history is reflected in Status and IsTerminal.
Use it after constructing a Game from FEN to provide the prior position keys needed for threefold and fivefold repetition detection in applications that persist position keys per game (instead of replaying the full PGN on every load).
The current position's key (PositionKey()) is already recorded during the FEN load; pass only the keys of PRIOR positions, in chronological order. Passing an empty or nil slice is a no-op. The halfmove clock and every other board field are untouched — only positionHistory and the derived isThreefoldRepetition / isFinished flags change.
Typical usage:
g, _ := chessongo.NewGameFromFEN(currentFEN) g.SeedPositionHistory(priorKeysFromDB) // g.CanClaimThreefoldRepetition() / g.Status() now reflect repetitions // across the entire game history, not just positions reached on *g.
func (*Game) ShouldIncFullMoves ¶
func (*Game) ShouldResetHalfMoves ¶
func (*Game) SideToMove ¶
SideToMove returns the side whose turn it is.
func (*Game) Snapshot ¶
func (g *Game) Snapshot() GameSnapshot
Snapshot returns a defensive value copy of the current game state.
func (*Game) TryMoveFromCoords ¶
TryMoveFromCoords applies a legal move from algebraic coordinates like "e2", "e4".
func (*Game) TryMoveSAN ¶
TryMoveSAN parses and applies a legal move in standard algebraic notation.
func (*Game) TryMoveUCI ¶
TryMoveUCI parses and applies a legal move in UCI coordinate notation.
Examples: "e2e4", "e1g1", "a7a8q".
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
game := chessongo.NewGame()
if err := game.TryMoveUCI("e2e4"); err != nil {
panic(err)
}
fmt.Println(game.SideToMove())
fmt.Println(game.FEN())
}
Output: black rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1
func (*Game) UndoMoveFast ¶
UndoMoveFast reverses a move made by MakeMoveFast.
func (*Game) UnmarshalBinary ¶
UnmarshalBinary decodes the board state from a byte slice.
func (*Game) WillMoveCauseCheck ¶
type GameSnapshot ¶
type GameSnapshot struct {
FEN string
Variant Variant
SideToMove Color
Board [64]Piece
WhitePieces Bitboard
BlackPieces Bitboard
WhiteByKind [7]Bitboard
BlackByKind [7]Bitboard
Occupied Bitboard
EnPassant Square
Castling CastlingRights
HalfMoveClock int
FullMoveNumber int
PositionKey uint64
LegalMoves []Move
Status GameStatus
Terminal bool
Draw DrawStatus
}
GameSnapshot is a defensive value copy of the public game state.
type GameStatus ¶
type GameStatus uint8
GameStatus describes the current terminal/check state of a game.
const ( GameStatusOngoing GameStatus = iota GameStatusCheck GameStatusCheckmate GameStatusStalemate GameStatusDrawInsufficientMaterial GameStatusDrawFivefoldRepetition GameStatusDrawSeventyFiveMoveRule GameStatusVariantWin )
func (GameStatus) String ¶
func (s GameStatus) String() string
String returns a stable machine-readable status name.
type IllegalMoveError ¶
type IllegalMoveError struct {
Move Move
Notation string
Reason IllegalMoveReason
}
IllegalMoveError provides structured context for legal move rejection.
func (*IllegalMoveError) Error ¶
func (e *IllegalMoveError) Error() string
func (*IllegalMoveError) Unwrap ¶
func (e *IllegalMoveError) Unwrap() error
type IllegalMoveReason ¶
type IllegalMoveReason string
IllegalMoveReason identifies why a move request was rejected.
const ( IllegalMoveReasonNotLegal IllegalMoveReason = "not legal" IllegalMoveReasonNoMatchingLegalMove IllegalMoveReason = "no matching legal move" )
type Move ¶
type Move uint32
* FROM bits 0-5 * TO bits 6-11 * EnPassant bit 12 * Castling bit 13 * Promotion bits 14 - 16 * CapturedPieceKind bits 17 - 20
func NewCastlingMove ¶
func NewEnPassantMove ¶
func NewMoveFromCoords ¶
NewMoveFromCoords creates a basic move from algebraic coordinates.
func NewMoveFromUCI ¶
NewMoveFromUCI creates a move request from UCI coordinate notation.
func NewPromotionMove ¶
func (Move) GetCapturedPiece ¶
func (Move) GetPromotionTo ¶
func (Move) IsCastlingMove ¶
func (Move) IsEnPassant ¶
func (Move) IsPromotingTo ¶
func (Move) IsPromotionMove ¶
func (Move) ToFromToStrings ¶
type Piece ¶
type Piece uint8
func PieceFromRune ¶
PieceFromRune converts a FEN piece rune into a Piece.
type SearchBoard ¶
type SearchBoard struct {
// contains filtered or unexported fields
}
SearchBoard is a lightweight wrapper around Game for search and perft traversal.
It uses fast make/unmake operations and caller-owned move buffers. Status flags such as repetition, checkmate, and draw state are not refreshed during traversal.
func NewSearchBoard ¶
func NewSearchBoard(fen string) (*SearchBoard, error)
NewSearchBoard creates a search board from FEN.
func (*SearchBoard) FEN ¶
func (b *SearchBoard) FEN() string
FEN returns the current board position as FEN.
func (*SearchBoard) LegalMoves ¶
func (b *SearchBoard) LegalMoves(dst []Move) []Move
LegalMoves copies legal moves into dst and returns the resulting slice.
func (*SearchBoard) MakeMove ¶
func (b *SearchBoard) MakeMove(move Move)
MakeMove applies a legal move without refreshing game-over status.
func (*SearchBoard) Perft ¶
func (b *SearchBoard) Perft(depth int) uint64
Perft returns the legal move tree node count at depth.
Example ¶
package main
import (
"fmt"
chessongo "github.com/chesshere-com/chess-on-go"
)
func main() {
board, err := chessongo.NewSearchBoard(chessongo.STARTING_POSITION_FEN)
if err != nil {
panic(err)
}
fmt.Println(board.Perft(2))
}
Output: 400
func (*SearchBoard) UndoMove ¶
func (b *SearchBoard) UndoMove(move Move)
UndoMove reverses a move made by MakeMove.
type Square ¶
type Square uint8
func CoordsToSquare ¶
Convert rank, file coordinates to a 64 based square
func ParseSquare ¶
ParseSquare converts algebraic coordinates like "e4" into a Square.
func ParseUCISquare ¶
ParseUCISquare converts a UCI square like "e4" into a Square.
func (Square) FileLetter ¶
Source Files
¶
- api.go
- binary.go
- bitboard.go
- board.go
- castling.go
- chess960.go
- coords.go
- direction.go
- doc.go
- draw.go
- epd.go
- errors.go
- fen.go
- legal_fast.go
- masks.go
- move-logic.go
- move.go
- notation.go
- notation_san.go
- pgn.go
- piece.go
- pseudo_moves.go
- ray.go
- search.go
- see.go
- sliding_attacks.go
- square.go
- status.go
- undo.go
- util.go
- variant.go
- variant_chess960.go
- variant_kingofthehill.go
- variant_rules.go
- variant_standard.go
- variant_threecheck.go
- zobrist.go