我编写了一个程序,在棋盘上检查其他工具上的工具的威胁。
我想写骑士能表演的动作。我想用两个选项来检查数学腹肌的距离--两个水平块和一个垂直或两个垂直块和一个水平块。我知道他有8个动作,但有没有办法缩短它,还是有其他方式写他的移动?我附加了代码,但问题在于骑士
// examines threats of tools on the chessboard
switch (first)
{
case 'r':
if ((row1 == row2) || (col1 == col2)){
System.out.println("rook threats " + (second == knight ? "knight" : "bishop"));
foundTreat = true;
}
break;
case 'b':
if(Math.abs(row1 - row2) == Math.abs(col1 - col2)){
System.out.println("bishop threats " + (second == rook ? "rook" : "knight"));
foundTreat = true;
}
break;
case 'k':
if((Math.abs(row1 + 1) == row2) && (Math.abs(col1 + 2) == col2)){
System.out.println("knight threats " + (second == rook ? "rook" : "bishop"));
foundTreat = true;
}
break;
}
switch (second)
{
case 'r':
if ((row1 == row2) || (col1 == col2)){
System.out.println("rook threats " + (first == knight ? "knight" : "bishop"));
foundTreat = true;
}
break;
case 'b':
if(Math.abs(row1 - row2) == Math.abs(col1 - col2)){
System.out.println("bishop threats " + (first == rook ? "rook" : "knight"));
foundTreat = true;
}
break;
case 'k':
if((Math.abs(row1 + 1) == row2) && (Math.abs(col1 + 2) == col2)){
System.out.println("knight threats " + (first == rook ? "rook" : "bishop"));
foundTreat = true;
}
break;
} 但是我不能正确地写代码,所以我很想得到帮助。
顺便说一句,我是Java的初学者,我只能用: if,否则,开关和没有: while,循环来编写代码。
谢谢。
发布于 2022-03-29 05:00:09
从你发布的代码来看,我认为你有一个2D的董事会代表。一个更干净的方法将是循环一个骑士可以从其当前位置的所有可能的移动,这将是一个国家的清单,例如。骑士有8种可能的动作,每一种都是水平方向和垂直方向上的两个方格和一个方格的组合,或者是两个正方形和一个方格的水平组合。
我不太熟悉java,所以这里有一些伪/C#代码。
knightMoves = [ [1, 2], [1, -2], ..., [-2, -1]]; // All 8 possible moves in all dircetions
foreach(List<int> move in knightMoves)
{
newPos = knightCurrentPosition + move;
// Check if knight is on board after move which means that the knights
// new position should be within 0-7.
if(newPos[0] < 0 || newPos[0] > 7 || newPos[1] < 0 || newPos[1] > 7) continue;
// Check if piece is not own piece (can't capture own piece)
if(board[newPos] == ownPiece) continue;
// If the criterias are fulfilled, add to the possible moves
possibleMoves.Add(newPos);
}然后,您还必须检查king是否处于检查状态,这可以在generate函数本身中完成,也可以在稍后阶段执行,具体取决于您的实现。
https://stackoverflow.com/questions/71594433
复制相似问题