简体   繁体   English

while循环表现不正常?

[英]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? 我的while循环有问题吗? (the infinite loop is just for testing at the moment). (无限循环目前仅用于测试)。

You have too many calls to makeMove() : 您对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. 由于您已经在循环的条件中调用了makeMove() ,因此无需在循环的主体中再次调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM