有没有办法将python国际象棋棋盘转换为整数列表?

问题描述 投票:2回答:2

我正在尝试创建一个神经网络下棋,但首先,我需要将国际象棋棋盘转换为整数列表。我正在使用python-chess模块进行国际象棋棋盘游戏。我目前有一个棋盘类,但找不到将其转换为列表的方法。

我试图使用chess_board.epd()方法,但返回一个难以转换的格式化方案。

这是我需要的代码:

board = chess.Board()  # Define board object
board.convert_to_int()  # Method I need

现在,使用.epd()方法我得到"rnbqkbnr/pppppppp/8/8/8/5P2/PPPPP1PP/RNBQKBNR b KQkq -"

如您所见,由于存在/8//5P2/,因此很难解析并转换为整数列表。

预期的输出是这样的(逐行):

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

例如,这些可以是整数映射到各个部分:

pawn - 1
knight - 2
bishop - 3
rook - 4
queen - 5
king - 6

白色可以是正整数,黑色可以是负整数。

python-3.x chess python-chess
2个回答
0
投票

我刚刚阅读了chess模块的文档,并根据需要创建了一个简单的抽象Class

import chess

class MyChess(chess.Board):

    mapped = {
        'P': 1,     # White Pawn
        'p': -1,    # Black Pawn
        'N': 2,     # White Knight
        'n': -2,    # Black Knight
        'B': 3,     # White Bishop
        'b': -3,    # Black Bishop
        'R': 4,     # White Rook
        'r': -4,    # Black Rook
        'Q': 5,     # White Queen
        'q': -5,    # Black Queen
        'K': 6,     # White King
        'k': -6     # Black King
        }

    def convert_to_int(self):
        epd_string = self.epd()
        list_int = []
        for i in epd_string:
            if i == " ":
                return list_int
            elif i != "/":
                if i in self.mapped:
                    list_int.append(self.mapped[i])
                else:
                    for counter in range(0, int(i)):
                        list_int.append(0)

注意:

大写字母用于白色部分,小写字母用于黑色部分。 0表示棋盘中的空白区域。


-1
投票

我在Github上发布了这个问题,我发现那里有一个更优雅的解决方案。它是以下内容:

>>> 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, ...]

注意上面的版本不包含底片,所以这里是改进版本:

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]
"""
© www.soinside.com 2019 - 2024. All rights reserved.