octad

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: MIT Imports: 13 Imported by: 0

README

octad

GoDoc Go Report Card License

octad is a set of go packages which provide common octad chess variant utilities such as move generation, turn management, checkmate detection, a basic engine, PGN encoding, image generation, and others.

Repo Structure

Package Docs Link Description
octad dechristopher/octad Move generation, serialization / deserialization, turn management, checkmate detection
image dechristopher/octad/image SVG octad board image generation
liad dechristopher/octad/liad Li(bre oct)ad test harness and sample self play implementation

Installation

octad can be installed using "go get".

go get -u github.com/dechristopher/octad

Octad Game

Octad was conceived by Andrew DeChristopher in 2018. Rules and information about the game can be found below. Octad is thought to be a solved, deterministic game but needs formal verification to prove that. This repository exists as an effort towards that goal.

Board Layout

Each player begins with four pieces: a knight, their king, and two pawns placed in that order from left to right relative to them. An example of this can be seen in the board diagrams below:

Octad Board 1. c2 1. c2 b3 1. c2 b3 2. cxb3! ...
Octad board Octad board Octad board Octad board
Rules

All standard chess rules apply:

  • En passant is allowed
  • Pawn promotion to any piece
  • Stalemates are a draw

The only catch, however, is that castling is possible between the king and any of its pieces on the starting rank before movement. The king will simply switch spaces with the castling piece in all cases except the far pawn, in which case the king will travel one space to the right, and the pawn will lie where the king was before. An example of white castling with their far pawn can be expressed as [ 1. c2 b3 2. O-O-O ... ] with the resulting structure leaving the knight on a1, a pawn on b1, the king on c1, and the other pawn on c2. Here is what that would look like on the board:

Octad board

Castling Notation
  • Knight castle: O
  • Close pawn castle: O-O
  • Far pawn castle: O-O-O
OFEN Notation

OFEN is a derivation of FEN to support the features of Octad. Read more here.

Sample Games
1.O-O a3
2.Nc2 a2
3.b3+ Nxb3+
4.Kb2 a1=Q+
5.Nxa1 Nxa1
6.Kxa1 Kc3
7.Ka2 b3+
8.Ka1 b2+
9.Kb1 Kb3
10.d3 Kc3
11.d4=Q+ Kxd4
12.Kxb2 1/2-1/2

Drawn by Insufficient Material
1.c2 b3
2.Kb2 O-O-O
3.cxb3 cxb3
4.d2 Nc2
5.d3 Nxa1
6.d4=Q# 1-0

White wins by Checkmate

Performance

octad has been performance tuned, using pprof, with the goal of being fast enough for use by octad bots and engines. This implementation relies heavily on the use of bitboards, resulting in very solid computational performance.

Benchmarks

The benchmarks can be run with the following command:

go test -bench=.

Results from the baseline 2019 16" MBP:

BenchmarkBitboardReverse-12           	1000000000     0.000016 ns/op
BenchmarkStalemateStatus-12           	971688	       1220 ns/op
BenchmarkInvalidStalemateStatus-12    	1387780	       857 ns/op
BenchmarkPositionHash-12              	1429471	       841 ns/op
BenchmarkValidMoves-12                	235640	       4992 ns/op

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func OFEN

func OFEN(ofen string) (func(*Game), error)

OFEN takes a string and returns a function that updates the game to reflect the OFEN data. Since OFEN 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 OFEN 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 octad notation used by FIDE. Examples: c2, b3, O-O (short castling), d4=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 octad 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) Flip

func (b *Board) Flip(fd FlipDirection) *Board

Flip flips the board over the vertical or horizontal center line.

func (*Board) MarshalBinary

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

MarshalBinary implements the encoding.BinaryMarshaller interface and returns the bitboard representations as a array of bytes. Bitboards 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.TextMarshaller interface and returns a string in the OFEN board format: ppkn/4/4/NKPP

func (*Board) Piece

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

Piece returns the piece for the given square.

func (*Board) Rotate

func (b *Board) Rotate() *Board

Rotate rotates the board 90 degrees clockwise.

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 OFEN board format: ppkn/4/4/NKPP

func (*Board) Transpose

func (b *Board) Transpose() *Board

Transpose flips the board over the A8 to H1 diagonal.

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. Bitboards 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.TextUnmarshaller interface and takes a string in the OFEN board format: ppkn/4/4/NKPP

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

type Color

type Color int8

Color represents the color of a octad 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 opposite 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 is the A file, index 0
	FileA File = iota
	// FileB is the B file, index 1
	FileB
	// FileC is the C file, index 2
	FileC
	// FileD is the D file, index 3
	FileD
)

func (File) String

func (f File) String() string

String returns the string representation of the the current file

type FlipDirection

type FlipDirection int

FlipDirection is the direction for the Board.Flip method

const (
	// UpDown flips the board's rank values
	UpDown FlipDirection = iota
	// LeftRight flips the board's file values
	LeftRight
)

type Game

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

A Game represents a single octad 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. Deprecated: Use Scanner instead.

func NewGame

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

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

Clone returns a duplicate instance of the current 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) 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.TextMarshaller 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) OFEN

func (g *Game) OFEN() string

OFEN returns the OFEN notation of the current position.

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) UndoMove added in v1.0.6

func (g *Game) UndoMove()

UndoMove will undo the last move played and revert the game to the position as it was before that move was played.

func (*Game) UnmarshalText

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

UnmarshalText implements the encoding.TextUnmarshaler 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 fully expanded version of algebraic notation in which the starting and ending squares are specified. Examples: e2e4, Rd3xd7, O-O (short castling), e7e8=Q (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 automatically drawn
	// by the game state being repeated three times.
	ThreefoldRepetition
	// TwentyFiveMoveRule indicates that the game was automatically drawn
	// when the half move clock was fifty or greater.
	TwentyFiveMoveRule
	// 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) Equals

func (m *Move) Equals(move *Move) bool

Equals returns whether or not the move in question is exactly the same as the current move

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 (
	// KnightCastle indicates that the move is a knight castle.
	KnightCastle MoveTag = 1 << iota
	// ClosePawnCastle indicates that the move is a close pawn castle.
	ClosePawnCastle
	// FarPawnCastle indicates that the move is a far pawn castle.
	FarPawnCastle
	// 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 regard to its outcome. Position is translatable to FEN notation.

func StartingPosition

func StartingPosition() (*Position, error)

StartingPosition returns the starting position ppkn/4/4/NKPP w NCFncf - 0 1

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) CheckSquare added in v1.0.1

func (pos *Position) CheckSquare() Square

CheckSquare returns the square containing the checked king.

func (*Position) EnPassantSquare

func (pos *Position) EnPassantSquare() Square

EnPassantSquare returns the position's active en passant square if any.

func (*Position) Hash

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

Hash returns a unique hash of the position

func (*Position) InCheck added in v1.0.1

func (pos *Position) InCheck() bool

InCheck returns true if the king is in check in the position.

func (*Position) MarshalBinary

func (pos *Position) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaller interface

func (*Position) MarshalText

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

MarshalText implements the encoding.TextMarshaller interface and encodes the position's OFEN.

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 OFEN format: ppkn/4/4/NKPP w NCFncf - 0 1

func (*Position) Turn

func (pos *Position) Turn() Color

Turn returns the color to move next.

func (*Position) UnmarshalBinary

func (pos *Position) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryMarshaller interface

func (*Position) UnmarshalText

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

UnmarshalText implements the encoding.TextUnmarshaler interface and assumes the data is in the OFEN 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 is the first rank, index 0
	Rank1 Rank = iota
	// Rank2 is the second rank, index 1
	Rank2
	// Rank3 is the third rank, index 2
	Rank3
	// Rank4 is the fourth rank, index 3
	Rank4
)

func (Rank) String

func (r Rank) String() string

String returns the string representation of the current rank

type Scanner

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

Scanner is modeled on the bufio.Scanner type but instead of reading lines, it reads octad games from concatenated PGN files. It is designed to replace GamesFromPGN in order to handle very large PGN database files such as https://database.lioctad.org/.

func NewScanner

func NewScanner(r io.Reader) *Scanner

NewScanner returns a new scanner.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns an error encountered during scanning. Typically this will be a PGN parsing error or an io.EOF.

func (*Scanner) Next

func (s *Scanner) Next() *Game

Next returns the game from the most recent Scan.

func (*Scanner) Scan

func (s *Scanner) Scan() bool

Scan returns false if there was an error parsing a game or EOF was reached. Running scan populates data for Next() and Err().

type Side

type Side int

Side represents a side to castle to. In octad, there are three types of castling allowed. Knight, close pawn, and far pawn

const (
	// KnightSide is castling with the knight
	KnightSide Side = iota + 1
	// CloseSide is castling with the close pawn
	CloseSide
	// FarSide is castling with the far pawn
	FarSide
)

type Square

type Square int8

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

const (
	// NoSquare represents an invalid square
	NoSquare Square = iota - 1
	// A1 square, index 0
	A1
	// B1 square, index 1
	B1
	// C1 square, index 2
	C1
	// D1 square, index 3
	D1
	// A2 square, index 4
	A2
	// B2 square, index 5
	B2
	// C2 square, index 6
	C2
	// D2 square, index 7
	D2
	// A3 square, index 8
	A3
	// B3 square, index 9
	B3
	// C3 square, index 10
	C3
	// D3 square, index 11
	D3
	// A4 square, index 12
	A4
	// B4 square, index 13
	B4
	// C4 square, index 14
	C4
	// D4 square, index 15
	D4
)

func (Square) Color

func (sq Square) Color() Color

Color returns the color of a given square

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

String returns the string representation of the current square

type TagPair

type TagPair struct {
	Key   string
	Value string
}

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

type UOINotation

type UOINotation struct{}

UOINotation is a more computer friendly alternative to algebraic notation. This notation uses the same format as the UOI (Universal Octad Interface). Example: d3d4q (for promotion)

func (UOINotation) Decode

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

Decode implements the Decoder interface.

func (UOINotation) Encode

func (UOINotation) Encode(pos *Position, m *Move) string

Encode implements the Encoder interface.

func (UOINotation) String

func (UOINotation) String() string

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

Directories

Path Synopsis
Package image is a go library that creates images from octad board positions
Package image is a go library that creates images from octad board positions

Jump to

Keyboard shortcuts

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