如何在 Python 中正确打印位板

How to print out bitboards correctly in Python

我想使用位板对国际象棋引擎进行编程。因为我对位板不是很熟悉,所以我想先弄清楚如何使用它们。我写了一个小函数来打印位板。那是我偶然发现问题的地方。我的函数似乎可以正确打印出排名,但似乎无法正确打印出文件。

def print_bitboard(bitboard):
    board = str(bin(bitboard)).zfill(64)
    for i in range(8):
    print(board[8*i+0] + " " + board[8*i+1] + " " + board[8*i+2] + " " + 
          board[8*i+3] + " " + board[8*i+4] + " " + board[8*i+5] + " " + 
          board[8*i+6] + " " + board[8*i+7])


bitboard1 = 
int("0000000000000000000000000000000000000000000000001111111100000000", 2)  
# 2nd rank
bitboard2 = 
int("1000000010000000100000001000000010000000100000001000000010000000", 2)  
# file A

print_bitboard(bitboard1)
print("")
print_bitboard(bitboard2)

结果:

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 b
1 1 1 1 1 1 1 1 
0 0 0 0 0 0 0 0

0 b 1 0 0 0 0 0     ----> wrong, should be: 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0

bin 函数总是 returns 以 0b 开头的二进制文字的有效 Python 表示。如果你不想要它,你可以使用 str.format 方法来代替:

board = '{:064b}'.format(bitboard)

您可以使用 wrap 将字符串拆分为子字符串列表,并使用 join 合并创建的列表:

from textwrap import wrap

                                       # |                           |
def print_bitboard(board):             # v split for spaces          v split for newlines
    print('\n'.join([' '.join(wrap(line, 1)) for line in wrap(board, 8)]))

bitboard1 = '0000000000000000000000000000000000000000000000001111111100000000'
print_bitboard(bitboard1)

# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 1 1 1 1 1 1 1 1
# 0 0 0 0 0 0 0 0

bitboard2 = '1000000010000000100000001000000010000000100000001000000010000000'
print_bitboard(bitboard2)

# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0