首页 > 解决方案 > 如何获取 python-chess 模块中所有合法移动的列表?

问题描述

我正在使用 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

如何像使用列表一样选择移动?那么,我将如何将选择用作移动?

标签: pythonpython-3.xlistpython-chess

解决方案


board.legal_moves对象是一个生成器,或者更具体地说是一个LegalMoveGenerator. 您可以迭代该对象,并且每次迭代都会产生一些东西。您可以将其转换为列表,list(board.legal_moves)然后正常索引。

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

推荐阅读