How do i get the played move by comparing two different fens?

981 Views Asked by At

So I have two fens. One gotten before the move and one after. How can I get the played move by comparing these 2 fens to each other and returning the answer in uci or any other format. I am using the python-chess library so maybe there is a way to get the played move by comparing two different board objects as well?

2

There are 2 best solutions below

2
On

I figured it out! I used the board objects that the chess python library makes and parsed those for the UCI of the move played.

nums = {1:"a", 2:"b", 3:"c", 4:"d", 5:"e", 6:"f", 7:"g", 8:"h"}
def get_uci(board1, board2, who_moved):
    str_board = str(board1).split("\n")
    str_board2 = str(board2).split("\n")
    move = ""
    flip = False
    if who_moved == "w":
        for i in range(8)[::-1]:
            for x in range(15)[::-1]:
                if str_board[i][x] != str_board2[i][x]:
                    if str_board[i][x] == "." and move == "":
                        flip = True
                    move+=str(nums.get(round(x/2)+1))+str(9-(i+1))
    else:
        for i in range(8):
            for x in range(15):
                if str_board[i][x] != str_board2[i][x]:
                    if str_board[i][x] == "." and move == "":
                        flip = True
                    move+=str(nums.get(round(x/2)+1))+str(9-(i+1))
    if flip:
        move = move[2]+move[3]+move[0]+move[1]
    return move
0
On

You can do it using the constructs provided by the Board object:

for move in board.legal_moves:
    board.push(move)
    if board.board_fen() == new_board.board_fen():
        break
    _ = board.pop()
else:
    throw an exception...

This is using chess.Board where board is the original board, and new_board is equal to board plus one move. The else on the for loop should handle the cases where none of the legal moves on board will yield new_board, or where there are no legal moves on board at all. After this runs, and assuming the else did not fire, a new Move object will be pushed to board.move_stack.