Drag & Drop
Moving pieces via Drag & Drop has been successfully implemented. In react-dnd jargon, I decided to make <Piece /> a DragSource and <Square /> a DragTarget.
When a Piece is dropped on a Square, a MOVE action is dispatched to update the game position:
As you might have noticed in the previous screenshot, the MOVE action is actually only dispatched if the index of the destination square is included in the props legalMoves, which is an array of all legal (valid) index moves.
I decided that those legalMoves would be calculated at the square level and passed to each piece as a prop. This way, we always know where a piece can move before it is actually moved by the user, improving the speed and the overall UX. This will also be helpful if we decide to help the user by highlighting the possible moves when a piece is being dragged.
To do so, the <Square /> container gets the legalMoves from the redux store via a selector, getLegalMoves. But since the moves are specific to a square index, I had to pass the square index to the selector. To be sure that everything was correctly memoized, I followed ideas from this article: Computing Derived Data.
Then the fun began with writing the logic of the findLegalMoves function. After quite a few Jest tests and calculations, the basic chess rules have been implemented. The code of the chess logic is not completely DRY for now: it would be good to refactor some parts. But at least it is tested, which will facilitates a lot the implementation of more advanced chess rules and the refactoring work.
There is one part of the code that I was quite satisfied with: the function to find the valid queen moves reuses the functions to find bishop and rook moves. This represents nicely the fact that a queen in chess has the combined abilities of a bishop and a rook:
Still, there are some simple ways to improve this app:
- Complete the chess logic
- Add basic user actions (start a new game, go to previous / next move)
I’m not that far from completing all the TODOs to achieve the simple vision I had for this pet app. I’ll make an update in the future when significant progress is done. Cheers!