Search code examples
javaloopsdo-whilechess

Do-While loop is exiting prematurely


I tried writing a PvP Chess program. However, when an invalid move is played, it ends the turn.

        do
        {
            boolean q = askMove(board, white , in);
            if (q == true){
                white.move = false;
                break;
            }
            else
                continue;
        } while (white.move == true);
        do
        {
            //boardDisplay (board);
            boolean w = askMove(board, black, in);
            if (w == true){
                black.move = false;
                break;
            }
            else
                continue;
        }while (black.move == true);
    }

In the code, q takes true, if the initial and final co-ordinates of a piece are not the same.

    if (x1 != x2 || y1 != y2)
            return true;
        return false;

When I execute this code,

First move is made

So, if I play the 2nd invalid, the 2nd move should replay, because (q == false) However,

The code should only trigger 'you can't move an enemy piece' only when it is the wrong player's turn. However, it triggers when I try to play a valid move as well.

It says that I'm using an enemy piece!

Even though I wrote:

   player p
    if (board[x1][y1].initPiece.name.charAt(0) != p.colour)
        System.out.println ("you cannot move an enemy piece");

Help is appreciated.


Solution

  • Much as it could be improved, I don't think your error is in the first block of code you've shown.

    If it's really needed, askMove() could to set white/black.move to false. Then you could simplify the first block of code as:

    while(!askMove(board, white, in));
    while(!askMove(board, black, in));
    

    Which doesn't come close to explaining your error.

    However, I think you will find your error quite quickly if you change this code:

        if (board[x1][y1].initPiece.name.charAt(0) != p.colour)
            System.out.println ("you cannot move an enemy piece");
    

    To this code:

        if (board[x1][y1].initPiece.name.charAt(0) != p.colour)
            System.out.println ("You cannot move the enemy piece " 
                + board[x1][y1].initPiece.name + " at " 
                + x1 + "," + y1 + " when playing as "
                + p.colour);
    

    I'd have to see the rest of your code but I wouldn't be surprised if the indexing is being reversed as players are switched.