John Sumner
John Sumner

Reputation: 95

while loop not behaving as expected?

package uk.ac.sheffield.aca14js;

public class Chess {
    public static void main(String[] arg) {

        Board chessBoard = new Board();
        Pieces white = new Pieces(chessBoard,1);
        Pieces black = new Pieces(chessBoard,0);
        Display board = new TextDisplay();
        Player one,two = null;
        one = new HumanPlayer("John",white,chessBoard,two);
        two = new HumanPlayer("opponent",black,chessBoard,one);
        one.setOpponent(two);

        int x = 0;


        while (x == 0){
            board.showPiecesOnBoard(chessBoard.getData());
            while (one.makeMove() != true){
                System.out.println("Choose a valid move");
                board.showPiecesOnBoard(chessBoard.getData());          
                one.makeMove();         
            }   
            board.showPiecesOnBoard(chessBoard.getData());  
            while (two.makeMove() != true){
                System.out.println("Choose a valid move");
                board.showPiecesOnBoard(chessBoard.getData());          
                two.makeMove();         
            }       
        }
    }
}

What I want is for the player to select a move and if it is valid make the move and if not retake the move.

If every move selected is valid the game goes fine with players alternating there turns.

If one player makes an invalid move the game then stays on there turn even if they make a valid move after until they make another invalid move.

Is there something wrong with my while loops? (the infinite loop is just for testing at the moment).

Upvotes: 0

Views: 97

Answers (1)

Eran
Eran

Reputation: 394156

You have too many calls to makeMove() :

        while (one.makeMove() != true){
            System.out.println("Choose a valid move");
            board.showPiecesOnBoard(chessBoard.getData());          
            one.makeMove(); // remove this     
        }   
        board.showPiecesOnBoard(chessBoard.getData());  
        while (two.makeMove() != true){
            System.out.println("Choose a valid move");
            board.showPiecesOnBoard(chessBoard.getData());          
            two.makeMove(); // remove this
        }   

Since you are already calling makeMove() in the loop's condition, there's no need to call it again in the loop's body.

Upvotes: 2

Related Questions