Question

i am developing a chess game for college and i am having the following problem: if the player click in a certain region of the board i am able to detect which chess piece he selected using the x,y coordinates and converting these coordinates into indexes of a matrix(tabPieces) 8x8 which contains 32 pieces(just the reference to the vector Pieces[32]) and 32 null pointers. The problem is that i don't know how to move the piece to another place only if the player click a second time in a different x,y coordinates of the board, how do i detect this second click?

PS: I mean second click and not double-click of the mouse.

@Override
public void mouseClicked(MouseEvent e) {
    coordenadaReal(e.getX(), e.getY());

    try {
        // get NullPointerException if the player click in one of the 32 null positions(do not have any chess piece in these coordinates)
        if ((x > 0 && x < 512) && (y > 0 && y < 512)) { // if not clicked on the edge board
            int colorClicked = tabPecas[indLineTab][indColumnTab].getColor();

            tabPieces[indLineTab][indColumnTab].showPossiblePaths(x, y, colorClicked);

            // I do not know how to detect this second click to do this part.
            // if the player click a second time in a valid place for that piece then walk to a new position
            tabPieces[indLineTab][indColumnTab].walk(x, y);
            tabPieces[indLineTab][indColumnTab] = null; // this position is empty and i do not lose the piece because tabPieces just store the reference and not the object

        }
    } catch (Exception exc) {
    }
}
Was it helpful?

Solution

You need to maintain some kind of flag which indicates the state the game is in...

private boolean hasPiece = false;
//...

public void mouseClicked(MouseEvent e){
    if (hasPiece) {
        // Move the piece that the user previously selected...
        hasPiece = false;
    } else {
        // Select the piece that the user clicked on...
        hasPiece = true; // but only when the user clicked on a valid piece ;)
    }
}

OTHER TIPS

You can do it by checking the location as well when you clicked mouse second time.so if mouse clicks second time, make sure this click happens on the same coordinates. Hope this will help you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top