Chess

UI-less framework for playing and analyzing chess

Website: github.com
Date: November 10, 2020
Frameworks: Swift
:

Story

Chess is an attempt at building a framework for playing – you guessed it – the game of chess. A year after starting to play chess I thought about building an app to help me memorize chess openings. Building a chess framework was the first step of this ongoing project. It is a dependency of my other package chess-related package ChessKit which provides a UI interface for the chess board. Chess is current still under development.

Features

The framework provides a public API allowing you to create a chess board which you are able to interact with in the following way:

  • Play moves (using algebraic notation or origin and destination squares)
  • Load PGNs
  • Navigate through loaded PGN

At any time the chess board can also provide you with data which can prove to be relevant for building another system around it (e.g. ChessKit) such as:

  • List of moves already played
  • List of squares
  • PGN
  • List of legal moves (move + capture) for a piece at a certain square
  • King in check? King check mate?

Sample

Below is a code sample featuring the line C42: Petrov’s Defence: Classical, Stafford Gambit

import Chess

let board = ChessBoard()

// Load PGN: C42: Petrov's Defense: Classical, Stafford Gambit
let pgn = "1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. Nc3 Bc5 6. d3 Ng4"
try! board.load(pgn: pgn)
board.loadAllMoves()

print(board.gui)
// ♖   ♗ ♕ ♔     ♖
// ♙ ♙ ♙     ♙ ♙ ♙
//     ♙
//     ♗
//        ♟   ♘
//     ♞ ♟
// ♟ ♟ ♟     ♟ ♟ ♟
// ♜   ♝ ♛ ♚ ♝   ♜

// Play Move: White blunders
try! board.play(move: "Be2")

// Play Move: Black attacks
try! board.play(move: "Bxf2+")

print(board.isKingInCheck(for: .white))
// true

let e1 = board.square(withNotation: "e1")!
let d2 = board.square(withNotation: "d2")!
try! board.playMove(from: e1, to: d2)

let d8 = board.square(withNotation: "d8")!
let g5 = board.square(withNotation: "g5")!
try! board.playMove(from: d8, to: g5)

print(board.isKingCheckMate(for: .white))
// true

print(board.pgn)
// 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. Nc3 Bc5 6. d3 Ng4
// 7. Be2 Bxf2+ 8. Kd2 Qg5#

Leave a Reply

Your email address will not be published.