基本上,我有这个while循环,它检索按下按钮的坐标(这是一个棋子)并通过循环查看是否可以进行移动。
然而,同一棋子的坐标不断被馈送,所以如果棋子没有可用的动作,同样的信息会一直反复显示,直到按下不同的按钮,同样的事情发生了再次,如果那件没有动作。 如果每次单击一个片段,我将如何仅打印相同的消息?
我尝试使用do while循环,其中while循环中的条件仅检查如果坐标的值与正在输入的值不同,按钮是否可用。但这没有区别?
while(!correctMove){
do{
fromXCo = s.getFromXInt();
fromYCo = s.getFromYInt();
toXCo = s.getToXInt();
toYCo = s.getToYInt();
p = board.getPiece(fromXCo, fromYCo);
//checks if occupied co-ordinate, if not goes back out the loop and asks again.
if (!board.occupied(fromXCo, fromYCo)){
System.out.println("Please choose occupied co-ordinates \n");
correctMove = false;
}
//checks if the colour is the same as the player's. If not, asks for co-ordinates again.
if (p.getColour() != getPieces().getColour()){
System.out.println("Please move your own pieces \n");
correctMove = false;
}
//tells player their selected piece
System.out.println("Your selected piece is " + p.getChar());
//looks through available moves for piece
moves = p.availableMoves();
//if no moves available, asks for new co-ordinates.
if (moves == null){
System.out.println("No moves available for this piece \n");
correctMove = false;
}
else {
Move found = null;
for( Move m : moves){
//checks if move can be done
if (m.ToX() == toXCo && m.ToY() == toYCo){
//if move is allowed- exit loop
found = m;
correctMove = true;
}
}
if (found == null) {
//if move can't be, ask for new co-ordinates
System.out.println("This move is not legal \n");
correctMove = false;
}
}
}while(fromXCo != s.getFromXInt() && fromYCo != s.getFromYInt() && toXCo != s.getToXInt() && toYCo != s.getToYInt());
}
答案 0 :(得分:1)
如果我理解正确while
的目的是如果没有选择合法移动的合法作品,用户可以重复选择。您不需要有两个while
循环(内部while
似乎只是作为if
)。我就是这样做的(伪代码):
correctMove = false;
While(!correctMove) {
square = inputNewSquare();
if(isEmpty(square))
"click on a piece"
else if(pieceHasRightColor(square))
"you can only move your own piece"
else if(!pieceHasMove(square))
"this piece has no legal move"
else {
//move(s) found, do stuff
correctMove = true;
}
}