所以我想知道怎样才能把FEN ID转换成棋盘。
代码:
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 = [
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
]
print(board_to_fen(board))
board_to_fen(board)所以我们有上面的黑板,其中'--'代表黑板上的一个正方形,一个空白正方形。所以你可以这样使用符号:'w'代表白色,'b'代表黑色。对于这些片段:
R:车N:骑士B:毕晓普Q:王后K:国王p:兵
就像你想象的那样,你放置了这样的东西:'wK' in a '--' spot for white和其他的棋子。
可以看出,我已经为棋盘创建了FEN ID,但我想知道如何使用外部的FEN字符串在上面的空白棋盘上生成棋盘。
我很感激我得到的任何帮助。如果您需要更多信息,请让我知道。
发布于 2021-03-03 15:08:44
这基本上与你所做的相反。
fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
def fen_to_board(fen):
board = []
for row in fen.split('/'):
brow = []
for c in row:
if c == ' ':
break
elif c in '12345678':
brow.extend( ['--'] * int(c) )
elif c == 'p':
brow.append( 'bp' )
elif c == 'P':
brow.append( 'wp' )
elif c > 'Z':
brow.append( 'b'+c.upper() )
else:
brow.append( 'w'+c )
board.append( brow )
return board
from pprint import pprint
pprint( fen_to_board(fen) )[timr@Tims-Pro:~/src]$ python fen.py
[['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'],
['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'],
['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']]
[timr@Tims-Pro:~/src]$ https://stackoverflow.com/questions/66451525
复制相似问题