Search code examples
javascriptchess

Waiting for user input inside of JS using chess


I'm unsure where to go next with my chess programming project, I have reached the point where I have the pieces laid out on the board and each piece has an ID with a location so I can call each piece and do logic that way.

I am just so confused as to how I should go about user input, so I want to have a listener of some sort to wait until the user clicks onto a table element, after they click on a certain element I want the board to highlight certain areas in which the pieces can go (its own function, i'm not asking help with this function but help with user input), and if the user clicks on one of the highlighted spots then the piece moves there.

I just don't know how this type of input works, do I have a listener until a certain function is called? Any help would be great appreciated.

Here is an example of what an element looks like, this is at [2][3] on the board array and the piece is black pawn symbolized by Pb.

<td class="black" id="23" onclick="divClickInfo(this)"></td>

So when the divClickInfo(this) is ran in the JS, I want certain actions to happen and inside that function I want to wait to see if the user , clicks on another piece, or clicks on a highlighted piece which the piece then moves to , or the user clicks on the same piece again and it just refreshes pretty much.

I'm just lost on the waiting to see if the user does a certain action, I have heard of listeners but I did some research and couldn't really find what I needed. If anyone can help me it would mean so much and it would further my project by so much, thanks for reading my post.

Here is code if you want to look at things further https://codepen.io/anon/pen/WaxXMj


Solution

  • You don't need listeners (other than the divClickInfo you already have). If you don't want to use drag/drop, simply store a variable when they click, like pieceMoving with the piece they're attempting to move. When they then click on another square, attempt to move that piece to the new square. Do something like this:

    var pieceInfo = null;
    function divClickInfo(this) {
        if (pieceInfo === null) {
            //They clicked on a piece they're intending to move
            //Set cell red
            pieceInfo = this.id
        } else {
            //They clicked on another square, and are attempting to move.
            if (this.id == pieceInfo) {
                //Clicked on same square
                //Set cell not red
            } else {
                //Logic here, see if piece can be moved to this square
                //If it can, move the piece (Take any other piece that may be here)
                //Otherwise, show an error?
            }
            //No longer moving a piece
            pieceInfo = null
        }
    }