简体   繁体   English

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

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

I am using the python chess module.我正在使用 python 国际象棋模块。 On the website, it shows that you can check if a move is legal by using在网站上,它显示您可以通过使用来检查移动是否合法

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

However, I want to be able to get a move from board.legal_moves .但是,我希望能够从board.legal_moves When I try this:当我尝试这个时:

print(board.legal_moves[0])

This returns the following error:这将返回以下错误:

TypeError: 'LegalMoveGenerator' object is not subscriptable

How can I select a move as if I were using a list?我怎样才能像使用列表一样移动 select ? Then, how would I use the selection as a move?那么,我将如何将选择用作移动?

The board.legal_moves object is a generator , or more specifically a LegalMoveGenerator . board.legal_moves object 是一个生成器,或者更具体地说是一个LegalMoveGenerator You can iterate over that object and it will yield something with each iteration.您可以迭代该 object 并且每次迭代都会产生一些结果。 You can convert it to a list with list(board.legal_moves) and then index it as normal.您可以使用list(board.legal_moves)将其转换为列表,然后正常索引。

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

Generate a list from the generator.从生成器生成列表。

legal_moves = list(board.legal_moves)

Legal moves is now a list.合法动作现在是一个清单。

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')]

Just use editing and eval function:只需使用编辑和评估 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

Though this may be bad, it is possible.虽然这可能很糟糕,但这是可能的。

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

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