我怎样才能用 python 操纵这个国际象棋符号?

How can I manipulate this chess notation with python?

我正在尝试在 python 中使用一些与国际象棋相关的库(例如 chessnut 和 chess),它们使用以下表示法

r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4

我已经搜索过了,但没有找到任何东西。我如何操作它以及如何将标准代数符号(例如“d4 Nc6 e4 e5 f4 f6 dxe5 fxe5”)转换为这个新符号?

那个符号叫做 FEN (Forsyth–Edwards Notation),看起来 python-chess 知道它并且可以解析它。

此表示法实际上并不等同于移动列表 - 这是用于指定位置,也可能是起始位置。没有关于游戏如何达到这一点的完整记录。

Python-国际象棋可以将您加载到其中的任何棋盘位置(例如使用 PGN 表示法)转换为这种表示法。

您可以使用 python-chess 来完成这项工作。这是采用 SAN 字符串并在棋盘上进行这些移动的代码:

import chess
san = 'd4 Nc6 e4 e5 f4 f6 dxe5 fxe5'
board = chess.Board()
for move_san in san.split(' '):
    board.push_san(move_san)

FEN 信息:https://en.wikipedia.org/wiki/Forsyth–Edwards_Notation

有两种方法可以从 python 中的 san 获取 FEN: 使用 .pgn 文件:

import chess
import chess.pgn

pgn = open("your_pgn_file.pgn")
game = chess.pgn.read_game(pgn)
board = game.board()

for move in game.mainline_moves():
    board.push(move)
print(board.fen())

或来自单个 san 主线:

import chess

board = chess.Board()
san_mainline = "d4 Nc6 e4 e5 f4 f6 dxe5 fxe5"

for move in san_mainline.split():
    board.push_san(move)
print(board.fen())