How can I make chessboardjs (frontend) work with python-chess (backend)?

53 Views Asked by At

Beware, new to javascript!

I am trying to make a simple app which uses chessboardjs to display and animate a chess board in the browser and flask with python-chess in the backend to enforce the chess rules. I have the chessboard set up and displayed on the browser and can communicate with the backend. I now want to enforce legal only moves. My idea is when a move is made on the frontend, the frontend sends a request to the backend and the response would contain information if the move is legal or not.

Chessboardjs has a function called onDrop (https://chessboardjs.com/examples#4004) which can be passed when creating the chessboard

var config = {
    draggable: true,
    position: 'start',
    onDrop: onDrop
    };

var board = Chessboard('board', config);

I dont have experience with asynchronous programming and its driving me crazy.

// If move is illegal, initiate snapback which doesnt let the user make the move
// If move is legal, update board status

async function fetchData(move) {
    const response = await fetch('/move', {
        method: 'POST', 
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(move)
    });
    const data = await response.json();
    return data; 
};

// Call the function to start fetching data and processing it
async function processData(move){
    const responseData = await fetchData(move);

    if (responseData.move == "valid_move"){
        return null;
    }
    
    return 'snapback';
}

function onDrop(source, target){
    
    const move = source + target;
    const valid = processData(move)
    .then(data => {
        console.log("inside then", data);
        return data;
    })
    .catch(error => {
        console.error("Error occurred:", error);
        return null;
    }
    
    );

    return valid;
}

The console prints out the correct values for data but snapback functionality is not getting implemented. I think because valid is a promise object whereas I need it to be either null or 'snapback'. Is this possible to do?

I tried to add async to function onDrop but that did not work as well.

0

There are 0 best solutions below