api

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct{}

API represents the cheesse API. All cheesse API methods are exported methods of this struct.

func New

func New() API

New constructs an API.

func (API) AIMove

func (a API) AIMove(game InputGame, mode string) (OutputGame, OutputAction, bool, error)

AIMove selects a move for the side to move in the given game.

`mode` must be one of: `{random|easy|medium|hard}` (case-insensitive).

  • `random`: uniformly random legal action (non-resign).
  • `easy`: iterative-deepening search with a 50ms budget.
  • `medium`: iterative-deepening search with a 200ms budget.
  • `hard`: iterative-deepening search with a 1s budget.

Returns the resulting game AFTER the action is applied, the chosen action, and whether a move was available (false = game is already over).

An error is only returned if the input game itself is invalid or mode is unknown.

func (API) ConvertNotation

func (a API) ConvertNotation(game InputGame, notationString string, targetNotation string) (OutputGame, OutputParseResult, error)

ConvertNotation takes any valid input game and a string representing a match in some notation, auto-detects the source notation, and re-renders every move in the target notation.

`targetNotation` must be one of: `{Algebraic|Figurine|Descriptive|Coordinate|ICCF|Smith|PGN}` (case-insensitive).

Partial input still converts the valid prefix: the result reports the detected source notation, whether the whole input parsed, how many actions were valid, and one OutputGameStep per valid action whose `actionString` is rendered in the target notation.

An error is only returned if the input game itself is invalid or the target notation is unknown.

Please refer to InputGame's, OutputGame's, OutputGameStep's and OutputParseResult's docs for format details.

func (API) DefaultGame

func (a API) DefaultGame() OutputGame

DefaultGame returns the initial game of chess, with all pieces on their default positions and before any action has taken place.

Example
var (
	a    = New()
	game = a.DefaultGame()
)
fmt.Println(game.Board.Board[0])
fmt.Println(game.Board.Board[1])
fmt.Println(game.Board.Board[6])
fmt.Println(game.Board.Board[7])
Output:
♜♞♝♛♚♝♞♜
♟♟♟♟♟♟♟♟
♙♙♙♙♙♙♙♙
♖♘♗♕♔♗♘♖

func (API) DoAction

func (a API) DoAction(game InputGame, action InputAction) (OutputGame, OutputAction, error)

DoAction takes any valid input game and any valid input action, parses them and attempts to apply the action on the given game. If parsing any of the entities fails or applying the action on the parsed game fails an error will be returned.

If applying the action succeeds, it returns the parsed action and the resulting game AFTER applying the action.

Please refer to InputGame's, InputAction's, OutputGame's and OutputAction's docs for format details.

func (API) ParseGame

func (a API) ParseGame(game InputGame) (OutputGame, error)

ParseGame takes any valid input game and parses it, returning an OutputGame, which contains a lot of useful information about it, like possible actions, locations of pieces, game state in terms of threats, is the game over, etc.

If the input game is invalid, an error will be returned with a description of the problem.

Please refer to InputGame's and OutputGame's docs for format details.

Example (Board)
var (
	a       = New()
	game, _ = a.ParseGame(InputGame{Board: Board{
		Board: []string{
			"♜♞♝♛♚♝♞♜",
			"♟♟♟    ♟",
			"       ♟",
			"       ♟",
			"       ♟",
			"       ♟",
			"♙♙♙♙♙♙♙♙",
			"♖♘♗♕♔♗♘♖",
		},
		CanWhiteKingsideCastle:  true,
		CanWhiteQueensideCastle: true,
		CanBlackKingsideCastle:  true,
		CanBlackQueensideCastle: true,
		HalfMoveClock:           0,
		FullMoveNumber:          1,
		EnPassantTargetSquare:   "",
		Turn:                    "White",
	}})
)
for _, line := range game.Board.Board {
	fmt.Println(line)
}
Output:
♜♞♝♛♚♝♞♜
♟♟♟    ♟
       ♟
       ♟
       ♟
       ♟
♙♙♙♙♙♙♙♙
♖♘♗♕♔♗♘♖
Example (Default_game)
var (
	a       = New()
	game, _ = a.ParseGame(InputGame{}) // Default game inferred
)
fmt.Println(game.Board.Board[0])
fmt.Println(game.Board.Board[1])
fmt.Println(game.Board.Board[6])
fmt.Println(game.Board.Board[7])
Output:
♜♞♝♛♚♝♞♜
♟♟♟♟♟♟♟♟
♙♙♙♙♙♙♙♙
♖♘♗♕♔♗♘♖
Example (Fen_string)
var (
	a       = New()
	game, _ = a.ParseGame(InputGame{FENString: "4k3/4p3/P2p4/7p/2bP4/p7/2P5/K2B4 w - - 0 1"})
)
for _, line := range game.Board.Board {
	// Sorry about the TrimRight. Example matches strings but trims spaces on the right.
	fmt.Println(strings.TrimRight(line, " "))
}
Output:
    ♚
    ♟
♙  ♟
       ♟
  ♝♙
♟
  ♙
♔  ♗

func (API) ParseNotation

func (a API) ParseNotation(game InputGame, notationString string) (OutputGame, OutputParseResult, error)

ParseNotation takes any valid input game and a string representing a match in some notation, auto-detects the notation and attempts to play the match starting from the supplied game.

The notation is auto-detected across all supported notations: Algebraic/SAN (including figurine and PGN), Coordinate, Descriptive, ICCF and Smith. All supported notations are attempted, and the attempt that parses the furthest wins.

Partial parses are supported: if the notation string stops being valid at some point, the result still contains the valid prefix of steps, the count of valid actions, the name of the most likely notation, and a description of the parse failure.

An example `notationString` (Scholar's mate):

`1. e4 e5\n2. Bc4 Nc6\n3. Qh5 Nf6??\n4. Qxf7#`

An error is only returned if the input game itself is invalid.

Please refer to InputGame's, OutputGame's, OutputGameStep's and OutputParseResult's docs for format details.

type Board

type Board struct {
	Board                   []string `json:"board"`
	CanWhiteKingsideCastle  bool     `json:"canWhiteKingsideCastle"`
	CanWhiteQueensideCastle bool     `json:"canWhiteQueensideCastle"`
	CanBlackKingsideCastle  bool     `json:"canBlackKingsideCastle"`
	CanBlackQueensideCastle bool     `json:"canBlackQueensideCastle"`
	HalfMoveClock           int      `json:"halfMoveClock"`
	FullMoveNumber          int      `json:"fullMoveNumber"`
	EnPassantTargetSquare   string   `json:"enPassantTargetSquare"` // in Algebraic notation, or empty string
	Turn                    string   `json:"turn"`                  // "Black" or "White"
}

Board is one of the input interfaces to supply a chess game.

The `board` struct member must consist of 8 strings of length 8, containing the representation of the chess board using unicode characters. For the empty cells, any character may be used, but the output board will use spaces.

The other struct members represent all required game state as described in the FEN notation.

- `enPassantTargetSquare` must be a board cell described in Algebraic Notation (e.g. `e2`). Note that `a1` is where the White Queen's Rook starts. If there's no en passant target square, it must be an empty string.

- `turn` must be one of: `{Black|White}`.

type InputAction

type InputAction struct {
	FromSquare         string `json:"fromSquare"`
	ToSquare           string `json:"toSquare"`
	PromotionPieceType string `json:"promotionPieceType"`
	IsResign           bool   `json:"isResign"`
	IsDraw             bool   `json:"isDraw"`
	ActionString       string `json:"actionString"`
}

InputAction is the input interface to supply a chess action.

- `fromSquare` and `toSquare` are required (unless `isResign`, `isDraw` or `actionString` is set), and must be board cells described in Algebraic Notation (e.g. `e2`). Note that `a1` is where the White Queen's Rook starts.

- `promotionPieceType` is only required if the action is a promotion.

- `promotionPieceType` must be one of: `{Queen|King|Bishop|Knight|Rook|Pawn}`.

- `isResign` resigns the game for the player to move; `isDraw` proposes a draw, which the engine assumes accepted. When either is set, the other fields are ignored.

- `actionString` supplies the action as a single move in any supported notation (e.g. `Nf3`, `♘f3`, `g1f3`, `N-KB3`, `7163`); the notation is auto-detected. When set, `fromSquare`/`toSquare`/`promotionPieceType` are ignored.

type InputGame

type InputGame struct {
	FENString       string   `json:"fenString"`
	Board           Board    `json:"board"`
	PositionHistory []string `json:"positionHistory"`
}

InputGame is the input interface to supply a chess game.

There are 3 different ways to supply the chess game:

1. via `fenString`: supply a FEN Notation string.

2. via `board`: supply the board, together with required aspects of the game state.

3. via empty struct: assumes the defaultGame.

If you supply both the `fenString` and the `board`, `board` is ignored silently.

`positionHistory` is optional: pass the `positionHistory` of a previous OutputGame to enable threefold/fivefold repetition detection across stateless API calls (the entries are opaque position hashes). Without it, repetitions cannot be detected.

type OutputAction

type OutputAction struct {
	FromPieceOwner     string `json:"fromPieceOwner"`
	FromPieceType      string `json:"fromPieceType"`
	FromPieceSquare    string `json:"fromPieceSquare"`
	ToSquare           string `json:"toSquare"`
	IsCapture          bool   `json:"isCapture"`
	IsResign           bool   `json:"isResign"`
	IsDraw             bool   `json:"isDraw"`
	IsPromotion        bool   `json:"isPromotion"`
	IsEnPassantCapture bool   `json:"isEnPassantCapture"`
	IsCastle           bool   `json:"isCastle"`
	IsKingsideCastle   bool   `json:"isKingsideCastle"`
	IsQueensideCastle  bool   `json:"isQueensideCastle"`
	PromotionPieceType string `json:"promotionPieceType"`
	CapturedPieceType  string `json:"capturedPieceType"`
	ActionString       string `json:"actionString"`
}

OutputAction is the output interface that describes a chess action. All API calls that return a chess action represent it with an OutputAction.

- `fromPieceOwner` is one of `{Black|White}`. The owner of the piece doing the action.

- `fromPieceType` is one of `{Queen|King|Bishop|Knight|Rook|Pawn}`.

- `fromPieceSquare` and `toSquare` are the source and destination board cells for the action, described in Algebraic Notation (e.g. `e2`). Note that `a1` is where the White Queen's Rook starts.

- `promotionPieceType` is one of `{Queen|King|Bishop|Knight|Rook|Pawn}`, and represents the piece that a Pawn promotes to, if the action is a promotion. If the action is not a promotion, it's an empty string.

- `capturedPieceType` is one of `{Queen|King|Bishop|Knight|Rook|Pawn}`, and represents the piece that was captured, if the action is a capture. If the action is not a capture, it's an empty string.

- `actionString` is the action rendered in Standard Algebraic Notation (e.g. `Nf3`). It is only populated by API calls that apply the action on a game (e.g. `DoAction`); otherwise it's an empty string.

type OutputGame

type OutputGame struct {
	FENString               string            `json:"fenString"`
	Board                   Board             `json:"board"`
	Actions                 []OutputAction    `json:"actions"`
	CanWhiteCastle          bool              `json:"canWhiteCastle"`
	CanWhiteKingsideCastle  bool              `json:"canWhiteKingsideCastle"`
	CanWhiteQueensideCastle bool              `json:"canWhiteQueensideCastle"`
	CanBlackCastle          bool              `json:"canBlackCastle"`
	CanBlackKingsideCastle  bool              `json:"canBlackKingsideCastle"`
	CanBlackQueensideCastle bool              `json:"canBlackQueensideCastle"`
	HalfMoveClock           int               `json:"halfMoveClock"`
	FullMoveNumber          int               `json:"fullMoveNumber"`
	IsLastMoveEnPassant     bool              `json:"isLastMoveEnPassant"`
	EnPassantTargetSquare   string            `json:"enPassantTargetSquare"`
	MoveNumber              int               `json:"moveNumber"`
	BlackPieces             map[string]string `json:"blackPieces"`
	WhitePieces             map[string]string `json:"whitePieces"`
	BlackKing               string            `json:"blackKing"`
	WhiteKing               string            `json:"whiteKing"`
	IsCheck                 bool              `json:"isCheck"`
	IsDoubleCheck           bool              `json:"isDoubleCheck"`
	IsDiscoverCheck         bool              `json:"isDiscoverCheck"`
	IsCheckmate             bool              `json:"isCheckmate"`
	IsStalemate             bool              `json:"isStalemate"`
	IsDraw                  bool              `json:"isDraw"`
	CanClaimDraw            bool              `json:"canClaimDraw"`
	IsGameOver              bool              `json:"isGameOver"`
	GameOverWinner          string            `json:"gameOverWinner"`
	InCheckBy               []string          `json:"inCheckBy"`
	PositionHistory         []string          `json:"positionHistory"`
}

OutputGame is the output interface that describes a chess game. All API calls that return a chess game represent it with an OutputGame.

- `fenString` represents the chess game as a FEN Notation string.

- `actions` is the exhaustive list of actions that can follow from this game.

- `enPassantTargetSquare` is a board cell described in Algebraic Notation (e.g. `e2`). Note that `a1` is where the White Queen's Rook starts. If there's no en passant target square, it's an empty string.

- `blackPieces` and `whitePieces` are maps from cells to piece names. The cells are represented in Algebraic Notation (e.g `e2`), and the piece names are one of `{Queen|King|Bishop|Knight|Rook|Pawn}`.

- `blackKing` and `whiteKing` are the cells where the Kings are located. The cells are represented in Algebraic Notation (e.g `e2`).

- `gameOverWinner` is one of `{Black|White|Unknown}`, and represents the winner of the game, when `isGameOver` is true. `Unknown` otherwise.

- `inCheckBy` is a list of cells whose pieces are threatening the player whose turn it is to move. `board.turn` dictates who this player is. The cells are represented in Algebraic Notation (e.g `e2`). To find out which piece is in a cell, inspect `blackPieces` and `whitePieces`.

Because OutputGame is a superset of InputGame, you may supply an OutputGame to any API call that expects an InputGame.

type OutputGameStep

type OutputGameStep struct {
	Game         OutputGame   `json:"game"`
	Action       OutputAction `json:"action"`
	ActionString string       `json:"actionString"`
}

OutputGameStep is the output interface that describes a step in a parsed or converted match in a given notation string.

A given notation string is parsed into a list of "action strings", each one representing each action in the match. There will be an OutputGameStep for each one of these "action strings".

Please refer to the docs for the OutputGame and OutputAction formats.

- `actionString` is a string representing a chess action as supplied by the client, so it could be in any of the supported notations, and is not modified by the API. It could be incorrectly sliced, though.

- `action` represents the action that the API inferred from the `actionString`.

- `game` represents the chess game AFTER applying the inferred action.

type OutputParseError

type OutputParseError struct {
	ReasonCode         string   `json:"reasonCode"`
	FailedAtMoveNumber int      `json:"failedAtMoveNumber"`
	FailedToken        string   `json:"failedToken,omitempty"`
	Message            string   `json:"message"`
	LegalMoves         []string `json:"legalMoves,omitempty"`
}

OutputParseError carries a structured breakdown of a parse failure.

- `reasonCode` is one of: unknown-token, illegal-move, ambiguous, no-moves-found.

- `failedAtMoveNumber` is the 1-based full-move number where the parse stopped (0 if the failure precedes the first move, e.g. garbage input).

- `failedToken` is the token text the parser attempted to match (empty for unknown-token / no-moves-found).

- `message` is a short, user-facing sentence describing the failure.

- `legalMoves` (bounded to 10 entries) lists the legal moves in the detected notation at the point of failure, so the UI can hint "did you mean…".

type OutputParseResult

type OutputParseResult struct {
	NotationName       string            `json:"notationName"`
	ParseWasSuccessful bool              `json:"parseWasSuccessful"`
	ValidActionCount   int               `json:"validActionCount"`
	Steps              []OutputGameStep  `json:"steps"`
	Metadata           map[string]string `json:"metadata,omitempty"` // e.g. PGN tag pairs
	Error              string            `json:"error,omitempty"`
	ErrorDetail        *OutputParseError `json:"errorDetail,omitempty"`
}

OutputParseResult is the output interface that describes the result of auto-detecting and parsing a match in some notation.

- `notationName` is the name of the notation that parsed the furthest (the most likely notation of the input), e.g. `Algebraic Notation`.

- `parseWasSuccessful` is true if the whole notation string was parsed.

- `validActionCount` is the number of valid actions parsed before either the end of the input or the first invalid action.

- `steps` contains one OutputGameStep per valid action, even if the parse failed midway: clients can render the valid prefix and flag the invalid tail.

- `error` describes why the parse stopped, when `parseWasSuccessful` is false.

- `errorDetail` carries a machine-readable breakdown of the parse failure (nil when the parse succeeded) so the UI can highlight the failure point and offer actionable guidance instead of echoing a raw internal string.

Jump to

Keyboard shortcuts

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