Created
May 4, 2024 19:38
-
-
Save matteoredaelli/a269d3c95e1be4c16a2abce93e7f7b93 to your computer and use it in GitHub Desktop.
Prolog parser for Chess FEN notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
black_piece('k', king). | |
black_piece('q', queen). | |
black_piece('r', rook). | |
black_piece('b', bishop). | |
black_piece('n', knight). | |
black_piece('p', pawn). | |
white_piece('K', king). | |
white_piece('Q', queen). | |
white_piece('R', rook). | |
white_piece('B', bishop). | |
white_piece('N', knight). | |
white_piece('P', pawn). | |
fen_num('1'). | |
fen_num('2'). | |
fen_num('3'). | |
fen_num('4'). | |
fen_num('5'). | |
fen_num('6'). | |
fen_num('7'). | |
fen_num('8'). | |
piece(Short, Piece, black):- black_piece(Short, Piece). | |
piece(Short, Piece, white):- white_piece(Short, Piece). | |
parse_fen_row([], [], _R, _C). | |
parse_fen_row([Atom|Rest], Pieces, R, C):- | |
fen_num(Atom), | |
atom_number(Atom, Num), | |
C2 is C + Num, | |
parse_fen_row(Rest, Pieces, R, C2). | |
parse_fen_row([Short|Rest], [[C,R,Piece,Color]|Pieces], R, C):- | |
piece(Short, Piece, Color), | |
C2 is C + 1, | |
parse_fen_row(Rest, Pieces, R, C2). | |
parse_fen_board(Pieces, Board):- | |
parse_fen_board(Pieces, Board, 8). | |
parse_fen_board([], [], _N). | |
parse_fen_board([Row|Rows], Board, N):- | |
string_chars(Row, Chars), | |
parse_fen_row(Chars, Pieces, N, 1), | |
N1 is N - 1, | |
parse_fen_board(Rows, OtherPieces, N1), | |
append(Pieces, OtherPieces, Board). | |
parse_fen(String, [Board, Color, Castling, EnPassant, HalfMove, FullMove]):- | |
split_string(String, " ", "\s\t\n", [PiecesString, Color, Castling, EnPassant, HalfMove, FullMove]), | |
split_string(PiecesString, "/", "\s\t\n", Pieces), | |
parse_fen_board(Pieces, Board). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment