I made a chess Program.py that is not working fine;
I want to gen the FEN out of the board list that looks like this
board = [
"R", "N", "B", "K", "Q", "B", "N", "Q",
"P", "P", "P", "P", "P", "P", "P", "P",
" ", " ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " ", " ", " ", " ",
"p", "p", "p", "p", "p", "p", "p", "p",
"r", "n", "b", "q", "k", "b", "n", "r"
]
the algorithm I built is shitty and it is just working for the starting case like the list shown up
for the last one, it generates this
rnbkqbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR/
but not for this for example (after 4 moves) it just generates something like this
32/0/PP/2/
board = ['R', ' ', 'B', 'K', 'Q', 'B', ' ', 'R',
'P', 'P', 'P', ' ', ' ', 'P', 'P', 'P',
' ', ' ', 'N', ' ', ' ', 'N', ' ', ' ',
' ', ' ', ' ', 'P', 'P', ' ', ' ', ' ',
' ', ' ', ' ', 'p', 'p', ' ', ' ', ' ',
' ', ' ', 'n', ' ', ' ', 'n', ' ', ' ',
'p', 'p', 'p', ' ', ' ', 'p', 'p', 'p',
'r', ' ', 'b', 'k', 'q', 'b', ' ', 'r'
]
I want an algorithm that generates the right FEN for the last board and for any other ones, the right one will be
r1bqkb1r/ppp2ppp/2n2n2/3pp3/3PP3/PPP2PPP/R1BKQB1R/
... & and I want the answer in python
CodePudding user response:
Try this.
Code
def get_fen_pieces(board):
"""
Read board and return piece locations in fen format.
"""
ret = None
cnt = 0 # counter for successive empty cell along the row
save = [] # temp container
board = board[::-1] # reverse first
for i, v in enumerate(board):
if v == ' ':
cnt = 1
# sum up the successive empty cell and update save
if cnt > 1:
save[len(save)-1] = str(cnt)
else:
save.append(str(cnt)) # add
else:
save.append(v) # add
cnt = 0 # reset, there is no successive number
if (i 1)%8 == 0: # end of row
save.append('/')
cnt = 0
ret = ''.join(save) # convert list to string
# print(ret)
return ret
# start
board = ['R', ' ', 'B', 'K', 'Q', 'B', ' ', 'R',
'P', 'P', 'P', ' ', ' ', 'P', 'P', 'P',
' ', ' ', 'N', ' ', ' ', 'N', ' ', ' ',
' ', ' ', ' ', 'P', 'P', ' ', ' ', ' ',
' ', ' ', ' ', 'p', 'p', ' ', ' ', ' ',
' ', ' ', 'n', ' ', ' ', 'n', ' ', ' ',
'p', 'p', 'p', ' ', ' ', 'p', 'p', 'p',
'r', ' ', 'b', 'k', 'q', 'b', ' ', 'r'
]
board_pieces = get_fen_pieces(board)
print(f'board pieces: {board_pieces}')
Output
board pieces: r1bqkb1r/ppp2ppp/2n2n2/3pp3/3PP3/2N2N2/PPP2PPP/R1BQKB1R/