Binbo is a Chess representation written in pure Erlang using Bitboards. It is basically aimed to be used on game servers where people play chess online.
It’s called Binbo
because its ground is a binary board containing only zeros and ones (0
and 1
) since this is the main meaning of Bitboards as an internal chessboard representation.
Binbo also uses the Magic Bitboards approach for a blazing fast move generation of sliding pieces (rook, bishop, and queen).
Note: it’s not a chess engine but it could be a good starting point for it. It can play the role of a core (regarding move generation and validation) for multiple chess engines running on distributed Erlang nodes, since Binbo is an OTP application itself.
-
Blazing fast move generation and validation.
-
No bottlenecks. Every game is an Erlang process (
gen_server
) with its own game state. -
Ability to create as many concurrent games as many Erlang processes allowed in VM.
-
Unicode chess symbols support for the board visualization right in Erlang shell:
♙ ♘ ♗ ♖ ♕ ♔ ♟ ♞ ♝ ♜ ♛ ♚ -
Ready for use on game servers.
-
Erlang/OTP 19.0 or higher.
Run make shell
or rebar3 shell
and then:
%% Start Binbo application first:
binbo:start().
%% Start new process for the game:
{ok, Pid} = binbo:new_server().
%% Start new game in the process:
binbo:new_game(Pid).
%% Or start new game with a given FEN:
binbo:new_game(Pid, <<"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1">>).
%% Look at the board with ascii or unicode pieces:
binbo:print_board(Pid).
binbo:print_board(Pid, [unicode]).
%% Make move for White and Black:
binbo:move(Pid, <<"e2e4">>).
binbo:move(Pid, <<"e7e5">>).
%% Have a look at the board again:
binbo:print_board(Pid).
binbo:print_board(Pid, [unicode]).
There are three steps to be done before making game moves:
-
Start Binbo application.
-
Create process for the game.
-
Initialize game state in the process.
Note: process creation and game initialization are separated for the following reason: since Binbo is aimed to handle a number of concurrent games, the game process should be started as quick as possible leaving the supervisor doing the same job for another game. It’s important for high-load systems where game creation is very frequent event.
binbo:new_server() -> {ok, pid()}.
So, to start one or more game processes:
{ok, Pid1} = binbo:new_server(),
{ok, Pid2} = binbo:new_server(),
{ok, Pid3} = binbo:new_server().
binbo:new_game(Pid) -> {ok, GameStatus} | {error, Reason}.
binbo:new_game(Pid, Fen) -> {ok, GameStatus} | {error, Reason}.
where:
-
Pid
is thepid
of the process where the game is to be initialized; -
Fen
(string()
orbinary()
) is the Forsyth–Edwards Notation (FEN).
It is possible to reinitilize game in the same process. For example:
binbo:new_game(Pid),
binbo:new_game(Pid, Fen2),
binbo:new_game(Pid, Fen3).
Example:
%% In Erlang shell.
> {ok, Pid} = binbo:new_server().
{ok,<0.185.0>}
% New game from the starting position:
> binbo:new_game(Pid).
{ok,continue}
% New game with the given FEN:
> binbo:new_game(Pid, <<"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1">>).
{ok,continue}
binbo:move(Pid, Move) -> {ok, GameStatus} | {error, Reason}.
where:
-
Pid
is the pid of the game process; -
Move
is ofbinary()
orstring()
type.
Examples:
%% In Erlang shell.
% New game from the starting position:
> binbo:new_game(Pid).
{ok,continue}
% Start making moves
> binbo:move(Pid, <<"e2e4">>). % e4
{ok,continue}
> binbo:move(Pid, <<"e7e5">>). % e5
{ok,continue}
> binbo:move(Pid, <<"f1c4">>). % Bc4
{ok,continue}
> binbo:move(Pid, <<"d7d6">>). % d6
{ok,continue}
> binbo:move(Pid, <<"d1f3">>). % Qf3
{ok,continue}
> binbo:move(Pid, <<"b8c6">>). % Nc6
{ok,continue}
% And here is checkmate!
> binbo:move(Pid, <<"f3f7">>). % Qf7#
{ok,checkmate}
Binbo recognizes castling when:
-
White king moves from
E1
toG1
(O-O
); -
White king moves from
E1
toC1
(O-O-O
); -
Black king moves from
E8
toG8
(O-O
); -
Black king moves from
E8
toC8
(O-O-O
).
Binbo also checks whether castling allowed or not acording to the chess rules.
Castling examples:
% White castling kingside
binbo:move(Pid, <<"e1g1">>).
% White castling queenside
binbo:move(Pid, <<"e1c1">>).
% Black castling kingside
binbo:move(Pid, <<"e8g8">>).
% Black castling queenside
binbo:move(Pid, <<"e8c8">>).
Binbo recognizes promotion when:
-
White pawn moves from square of
rank 7
to square ofrank 8
; -
Black pawn moves from square of
rank 2
to square ofrank 1
.
Promotion examples:
% White pawn promoted to Queen:
binbo:move(Pid, <<"a7a8q">>).
% or just:
binbo:move(Pid, <<"a7a8">>).
% White pawn promoted to Knight:
binbo:move(Pid, <<"a7a8n">>).
% Black pawn promoted to Queen:
binbo:move(Pid, <<"a2a1q">>).
% or just:
binbo:move(Pid, <<"a2a1">>).
% Black pawn promoted to Knight:
binbo:move(Pid, <<"a2a1n">>).
Binbo also recognizes the en passant capture in strict accordance with the chess rules.
binbo:get_fen(Pid) -> {ok, Fen}.
Example:
> binbo:get_fen(Pid).
{ok, <<"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1">>}.
binbo:print_board(Pid) -> ok.
binbo:print_board(Pid, [unicode|ascii|flip]) -> ok.
You may want to see the current position right in Elang shell. To do it, call:
% With ascii pieces:
binbo:print_board(Pid).
% With unicode pieces:
binbo:print_board(Pid, [unicode]).
% Flipped board:
binbo:print_board(Pid, [flip]).
binbo:print_board(Pid, [unicode, flip]).
As mentioned above, Binbo uses Magic Bitboards, the fastest solution for move generation of sliding pieces (rook, bishop, and queen). Good explanations of this aproach can also be found here and here.
The main problem is to find the index which is then used to lookup legal moves of sliding pieces in a preinitialized move database. The formula for the index is:
in C/C++:
magic_index = ((occupied & mask) * magic_number) >> shift;
in Erlang:
MagicIndex = (((Occupied band Mask) * MagicNumber) bsr Shift).
where:
-
Occupied
is the bitboard of all pieces. -
Mask
is the attack mask of a piece for a given square. -
MagicNumber
is the magic number, see "Looking for Magics". -
Shift = (64 - Bits)
, whereBits
is the number of bits corresponding to attack mask of a given square.
All values for magic numbers and shifts are precalculated before and stored in binbo_magic.hrl
.
To be accurate, Binbo uses Fancy Magic Bitboards. It means that all moves are stored in a table of its own (individual) size for each square. In C/C++ such tables are actually two-dimensional arrays and any move can be accessed by a simple lookup:
move = global_move_table[square][magic_index]
If detailed:
moves_from = global_move_table[square];
move = moves_from[magic_index];
The size of moves_from
table depends on piece and square where it is placed on. For example:
-
for rook on
A1
the size ofmoves_from
is4096
(2^12 = 4096, 12 bits requred for the attack mask); -
for bishop on
A1
it is64
(2^6 = 64, 6 bits requred for the attack mask).
There are no two-dimensional arrays in Erlang, and no global variables which could help us to get the fast access to the move tables from everywhere.
So, how does Binbo beat this? Well, it’s simple :).
Erlang gives us the power of tuples and maps with their blazing fast lookup of elements/values by their index/key.
Since the number of squares on the chessboard is the constant value (it’s always 64, right?),
our global_move_table
can be constructed as a tuple of 64 elements, and each element of this tuple
is a map containing the key-value association as MagicIndex => Moves
.
If detailed, for moves:
GlobalMovesTable = { MoveMap1, ..., MoveMap64 }
where:
MoveMap1 = #{
MagicIndex_1_1 => Moves_1_1,
...
MagicIndex_1_K => Moves_1_K
},
MoveMap64 = #{
MagicIndex_64_1 => Moves_64_1, ...
...
MagicIndex_64_N => Moves_64_N
},
and then we lookup legal moves from a square, say, E4
(29th element of the tuple):
E4 = 29,
MoveMapE4 = erlang:element(E4, GlobalMovesTable),
MovesFromE4 = maps:get(MagicIndex, MovesMapE4).
To calculate magic index we also need the attack mask for a given square. Every attack mask generated is stored in a tuple of 64 elements:
GlobalMaskTable = {Mask1, Mask2, ..., Mask64}
where Mask1
, Mask2
, …, Mask64
are bitboards (integers).
Finally, if we need to get all moves from E4
:
E4 = 29,
Mask = erlang:element(E4, GlobalMaskTable),
MagicIndex = ((Occupied band Mask) * MagicNumber) bsr Shift,
MoveMapE4 = erlang:element(E4, GlobalMovesTable),
MovesFromE4 = maps:get(MagicIndex, MovesMapE4).
Next, no global variables? We make them global!
How do we get the fastest access to the move tables and to the atack masks from everywhere? ETS? No! Using ETS as a storage for static terms we get the overhead due to extra data copying during lookup.
And now we are coming to the fastest solution.
When Binbo starts up, all move tables are initialized.
Once these tables (tuples, actually) initialized, they are "injected" into dynamically generated
modules compiled at Binbo start. Then, to get the values, we just call a getter function
(binbo_global:get/1
) with the argument as the name of the corresponding dynamic module.
This awesome trick is used in MochiWeb library, see module mochiglobal.
Using persistent_term (since OTP 21.2) for storing static data is also a good idea.
But it doesn’t seem to be a better way for the following reason with respect to dynamic modules.
When Binbo stops, it gets them unloaded as they are not necessary anymore.
It should do the similar things for persistent_term
data, say, delete all unused terms to free memory.
In this case we run into the issue regarding scanning the heaps in all processes.
So, using global
dynamic modules with large static data seems to be more reasonable in spite of that fact that it significantly slows down the application startup due to the run-time compilation of these modules.
There are some chess rules that Binbo does not detect yet (regarding a draw):
-
Immediate draw when (insufficient material):
-
king versus king;
-
king and bishop versus king;
-
king and knight versus king;
-
king and bishop versus king and bishop with the bishops on the same color.
-