I am trying to create a neural network to play chess, but first, I need to convert the chess board to a list of integers. I am using the python-chess module for the chess board and game. I currently have a chess board class, but cannot find a method to convert it into a list.
I have tried to use the chess_board.epd()
method, but that returns a formatting scheme that is hard to convert.
Here is the code that I need:
board = chess.Board() # Define board object
board.convert_to_int() # Method I need
Right now, with the .epd()
method I get "rnbqkbnr/pppppppp/8/8/8/5P2/PPPPP1PP/RNBQKBNR b KQkq -"
As you can see, it is very difficult to parse and convert to a list of integers as there are /8/
's and /5P2/
.
The expected output is something like this (goes row by row):
[4, 2, 3, 5, 6, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, ... -1, -1, -1, -1,-1, -1,-1, -1, -4, -2, -3, -5, -6, -3, -2, -4]
For example, these can be what integers map to the peices:
pawn - 1
knight - 2
bishop - 3
rook - 4
queen - 5
king - 6
And white can be positive integers and black can be negative integers.
I have posted the question on Github, and I found I got a more elegant solution there. It was the following:
>>> import chess
>>> board = chess.Board()
>>> [board.piece_type_at(sq) for sq in chess.SQUARES] # Get Type of piece
[4, 2, 3, 5, 6, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, ...]
Note the above version does not include negatives, so here is the imporved version:
def convert_to_int(board):
l = [None] * 64
for sq in chess.scan_reversed(board.occupied_co[chess.WHITE]): # Check if white
l[sq] = board.piece_type_at(sq)
for sq in chess.scan_reversed(board.occupied_co[chess.BLACK]): # Check if black
l[sq] = -board.piece_type_at(sq)
return [0 if v is None else v for v in l]
piece_type_list(chess.Board())
"""
Outpus:
[4, 2, 3, 5, 6, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, None, None, None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,
-1, -1, -1, -1, -1, -1, -1, -1, -4, -2, -3, -5, -6, -3, -2, -4]
"""