如何从未嵌套的棋盘列表中获取 FEN

how to get the FEN out of unNested chess board List

我下了一个国际象棋 Program.py,但效果不佳;

我想从如下所示的板列表中生成 FEN

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"
]

我构建的算法很糟糕,它只适用于显示列表中的初始情况

对于最后一个,它生成这个

rnbkqbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR/

但不是这个例子(4 步之后) 它只是生成这样的东西

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'
        ]

我想要一种算法,可以为最后一块板和任何其他板生成正确的 FEN, 正确的是

r1bqkb1r/ppp2ppp/2n2n2/3pp3/3PP3/PPP2PPP/R1BKQB1R/

... & 我想要 python

中的答案

试试这个。

代码

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}') 

输出

board pieces: r1bqkb1r/ppp2ppp/2n2n2/3pp3/3PP3/2N2N2/PPP2PPP/R1BQKB1R/