繁体   English   中英

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

[英]How to get a list of all the legal moves in the python-chess module?

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

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

board.legal_moves object 是一个生成器,或者更具体地说是一个LegalMoveGenerator 您可以迭代该 object 并且每次迭代都会产生一些结果。 您可以使用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')]

只需使用编辑和评估 function:

import chess # Import chess

board = chess.Board() # Create chess board

moves_t = str(board.legal_moves)[37:-1] # Get the tuple as string
moves_t = moves_t.replace(", ", "', '") # Converting all the SAN names into strings
moves_t = moves_t.replace("(", "('")
moves_t = moves_t.replace(")", "')")
moves_t = eval(moves_t) # Using eval function to turn into tuple
moves = [] # Creates list to store values
for i in moves_t: # Go through all values
    moves.append(i) # Add them to empty list

虽然这可能很糟糕,但这是可能的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM