将您的表示转换为标准表示并不困难。例如,您可以使用如下函数转换为 FEN:
import io
def board_to_fen(board):
# Use StringIO to build string more efficiently than concatenating
with io.StringIO() as s:
for row in board:
empty = 0
for cell in row:
c = cell[0]
if c in ('w', 'b'):
if empty > 0:
s.write(str(empty))
empty = 0
s.write(cell[1].upper() if c == 'w' else cell[1].lower())
else:
empty += 1
if empty > 0:
s.write(str(empty))
s.write('/')
# Move one position back to overwrite last '/'
s.seek(s.tell() - 1)
# If you do not have the additional information choose what to put
s.write(' w KQkq - 0 1')
return s.getvalue()
在一些板数据上对其进行测试:
board = [
['bk', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
['em', 'bn', 'em', 'wr', 'em', 'wp', 'em', 'em'],
['br', 'em', 'bp', 'em', 'em', 'bn', 'wn', 'em'],
['em', 'em', 'bp', 'bp', 'bp', 'em', 'wp', 'bp'],
['bp', 'bp', 'em', 'bp', 'wn', 'em', 'wp', 'em'],
['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
['em', 'em', 'em', 'wk', 'em', 'em', 'em', 'em'],
['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
]
print(board_to_fen(board))
# k7/1n1R1P2/r1p2nN1/2ppp1Pp/pp1pN1P1/8/3K4/8 w KQkq - 0 1
例如,在Chess.com中可视化 FEN 字符串会产生: