Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using the python chess module. 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. 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? Then, how would I use the selection as a move?

like image 243
Justin Cheng Avatar asked Dec 11 '22 00:12

Justin Cheng


1 Answers

The board.legal_moves object is a generator, or more specifically a LegalMoveGenerator. You can iterate over that object and it will yield something with each iteration. You can convert it to a list with list(board.legal_moves) and then index it as normal.

import chess
board = chess.Board()
legal_moves = list(board.legal_moves)
legal_moves[0]  # Move.from_uci('g1h3')
like image 141
jakub Avatar answered May 20 '23 18:05

jakub