如何获得python-chess模块 中所有合法举动的列表?

问题描述 投票:0回答:1

我正在使用python国际象棋模块。在网站上,它表明您可以通过使用

检查移动是否合法
import chess

board = chess.Board()
move = input("Enter a chess move: ")
if move in board.legal_moves:
    # Some code to do if the move is a legal move

但是,我希望能够从board.legal_moves取得成功。当我尝试这个:

print(board.legal_moves[0])

这将返回以下错误:

TypeError: 'LegalMoveGenerator' object is not subscriptable

如何像选择列表一样选择举动?然后,我将如何使用选择作为动作?

python python-3.x list python-chess
1个回答
2
投票

board.legal_moves对象是generator,或更具体地说是LegalMoveGenerator。您可以遍历该对象,并且每次迭代都会产生一些结果。您可以使用list(board.legal_moves)将其转换为列表,然后按常规将其编入索引。

import chess
board = chess.Board()
legal_moves = list(board.legal_moves)
legal_moves[0]  # Move.from_uci('g1h3')

1
投票

从生成器生成列表。

legal_moves = list(board.legal_moves)

法律动作现在是列表。

print(legal_moves)

[Move.from_uci('g1h3'), Move.from_uci('g1f3'), Move.from_uci('b1c3'),
 Move.from_uci('b1a3'), Move.from_uci('h2h3'), Move.from_uci('g2g3'), 
 Move.from_uci('f2f3'), Move.from_uci('e2e3'), Move.from_uci('d2d3'), 
 Move.from_uci('c2c3'), Move.from_uci('b2b3'), Move.from_uci('a2a3'), 
 Move.from_uci('h2h4'), Move.from_uci('g2g4'), Move.from_uci('f2f4'), 
 Move.from_uci('e2e4'), Move.from_uci('d2d4'), Move.from_uci('c2c4'), 
 Move.from_uci('b2b4'), Move.from_uci('a2a4')]
© www.soinside.com 2019 - 2024. All rights reserved.