gpt4 book ai didi

java - while 循环的行为不符合预期?

转载 作者:行者123 更新时间:2023-12-02 04:49:22 25 4
gpt4 key购买 nike

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

我想要的是玩家选择一个 Action ,如果有效则进行该 Action ,如果无效则重新进行该 Action 。

如果选择的每一步都有效,则游戏会顺利进行,玩家轮流轮流进行。

如果一名玩家做出了无效的举动,则游戏将继续该回合,即使他们之后做出了有效的举动,直到他们做出了另一次无效的举动。

我的 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(),因此无需在循环主体中再次调用它。

关于java - while 循环的行为不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com