我正在使用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
如何像选择列表一样选择举动?然后,我将如何使用选择作为动作?
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')
从生成器生成列表。
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')]