繁体   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();         
            }       
        }
    }
}

我想要的是让玩家选择一个动作,如果有效,则进行该动作,如果不采取该动作。

如果选择的每一步都有效,那么游戏会进行得很好,玩家轮流交替出现。

如果一个玩家做出了无效的动作,那么即使他们之后做出了有效的动作,游戏也会停留在该处,直到他们做出另一次无效的动作。

我的while循环有问题吗? (无限循环目前仅用于测试)。

您对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
        }   

由于您已经在循环的条件中调用了makeMove() ,因此无需在循环的主体中再次调用它。

暂无
暂无

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

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