0

我制作了一个无法正常工作的国际象棋 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中的答案

4

1 回答 1

1

尝试这个。

代码

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/
于 2022-01-03T02:57:24.890 回答