I’m trying to create a chessboard with draggable and snapping on square function, I’m not into the pieces legal moves yet but I’m just trying to let the piece move.
I don’t link a CSS file to the html yet because I tried to keep thing simple
This is the link to download the pieces img that I used in my project
https://github.com/AlessandroVasta79/ChessWebsite
I tried to watch some tutorial but I still can’t understand a way to solve my problem
3
Answers
Have you tried using react-dnd you can make each price a drag component and each square a drop component.
Note: To use react-dnd run
npm install react-dnd
You should use
<div>
‘s instead of html table. This will eliminate lots of limitations first. Go through this code and take inspiration from this linkLet me know how you want to proceed then. I will try to be available.
HTML code preview:
You can use Canvas API to accomplish this. This is to common approach. I have seen other projects where they set-up the board using Grid Layout but I don’t know how it works with grid layout. I won’t give you the direct code implementation but I will provide you the general steps you can follow:
Create a JS file specifically to provide the game logic and canvas rendering.
To initialize the game and for general layout/appearance of the chess board, you need to paint the whole canvas with a specified color or you can use an imagine of chess board as background image and render it. Then you will have to draw horizontal and vertical lines to create cells. Each cell will have
canvasSize / 8
pixels of height and width. You can also have a padding from the edges of the board to make it look better. In that case, each cell will have(canvasSize - (2 * padding)) / 8
pixels in width and height.To store game state and render the board accordingly to the current state of the game, you need an object or array.
You will have to initially render the board accordingly to the current game state. At this point rendering will be all about showing images positioned at the center of cells accordingly to the cell data (
'black-caste'
,'black-pawn'
etc.).mouseDown
,mouseMove
,mouseUp
events. To detect where the user has clicked and wants to move which stone, you can use each of these event’sclientX
andclientY
oroffsetX
andoffsetY
data.