Home > Software engineering >  Why pieces are moving in opposite direction in python-chess
Why pieces are moving in opposite direction in python-chess

Time:01-01

I have the following fen RNBK1B1R/PPPPQPPP/5N2/3pP3/4p1p1/2n2n2/ppp2p1p/r1bkqb1r b which is generated from a image recognition technique. This fen is based on a flipped board such that the black pieces are at the bottom. When I check the legal_moves, seems like the trajectory of my pieces are backwards. Is there any way to control the direction of my pieces?

Here's the image of the board along with legal moves -

enter image description here

Quick snippet to print all legal moves -

import chess


def legalMoves(board):
    
    legMovesDict = {}
    for lm in board.legal_moves:
        src, des = lm.from_square, lm.to_square
        src, des = chess.square_name(src).upper(), chess.square_name(des).upper()

        if src not in legMovesDict.keys():
            legMovesDict[src] = [des]

        else:
            if des not in legMovesDict[src]:
                legMovesDict[src].append(des)
        # print(src, des)

    return legMovesDict

board = chess.Board('RNBK1B1R/PPPPQPPP/5N2/3pP3/4p1p1/2n2n2/ppp2p1p/r1bkqb1r b')

print(legalMoves(board))

CodePudding user response:

According to this answer, you can reverse the first field of the FEN notation of the board to correct for the inversion.

So, this:

fen = 'RNBK1B1R/PPPPQPPP/5N2/3pP3/4p1p1/2n2n2/ppp2p1p/r1bkqb1r b'
fields = fen.split(' ')
fields[0] = fields[0][::-1]
flipped_fen = ' '.join(fields)

board = chess.Board(flipped_fen)
print(legalMoves(board))

will produce the desired output.

  • Related