我想使用位板编程国际象棋引擎。因为我对位板不是很熟悉,所以我试图首先弄清楚如何使用它们。我写了一个小函数,应该打印位板。那是我偶然发现一个问题的地方。我的函数似乎可以正确打印出行列,但似乎不能正确打印出文件。
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
答案 0 :(得分:0)
bin
函数始终返回以0b
开头的二进制文字的有效Python表示形式。如果您不想要它,可以改用str.format
方法:
board = '{:064b}'.format(bitboard)
答案 1 :(得分:0)
您可以使用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