Justin Cheng
Justin Cheng

Reputation: 253

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?

Upvotes: 5

Views: 11386

Answers (4)

tehnik-tehnolog
tehnik-tehnolog

Reputation: 11

If you want the output as a simple list:

legal_moves_lst = [
    board.san(move)
    for move in board.legal_moves
]
print(legal_moves_lst)

Output:

['Nh3', 'Nf3', 'Nc3', 'Na3', 'h3', 'g3', 'f3', 'e3', 'd3', 'c3', 'b3', 'a3', 'h4', 'g4', 'f4', 'e4', 'd4', 'c4', 'b4', 'a4']

Upvotes: 1

Hacker 827
Hacker 827

Reputation: 9

Just use editing and eval 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.

Upvotes: -1

DarrylG
DarrylG

Reputation: 17176

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

Upvotes: 9

jkr
jkr

Reputation: 19320

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

Upvotes: 10

Related Questions