澄清一下,我只想要一两个 for 循环来帮助我,最好是与我在垂直领域使用的风格相同:)
我正在使用 2D 数组制作游戏,我需要一个检查来测试在当前位置(由绿色方 block 表示)字符是否存在“l”更多字符的对角序列的一部分.
最佳答案
public static boolean diagonals(char[][] b, int row, int col, int l) {
int counter = 1; // because we start from the current position
char charAtPosition = b[row][col];
int numRows = b.length;
int numCols = b[0].length;
int topleft = 0;
int topright = 0;
int bottomleft = 0;
int bottomright = 0;
for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--) {
if (b[i][j]==charAtPosition) {
topleft++;
} else {
break;
}
}
for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
if (b[i][j]==charAtPosition) {
topright++;
} else {
break;
}
}
for (int i=row+1,j=col-1;i<=numRows && j>=0;i++,j--) {
if (b[i][j]==charAtPosition) {
bottomleft++;
} else {
break;
}
}
for (int i=row+1,j=col+1;i<=numRows && j<=numCols;i++,j++) {
if (b[i][j]==charAtPosition) {
bottomright++;
} else {
break;
}
}
return topleft + bottomright + 1 >= l || topright + bottomleft + 1 >= l; //in this case l is 5
}
我们的想法是,我们朝四个方向行走并计算步数。这可能不是最有效的实现,但至少它看起来整洁且易于理解。
关于游戏的 Java 2D 数组对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705431/