澄清我只想要一两个for循环来帮助我,最好是和我在垂直方向上使用的风格相同:)
我正在使用2D数组制作游戏,我需要一个检查,测试当前位置(由绿色方块表示)角色是否有一部分对角线序列" l& #34;更多的角色。
答案 0 :(得分:1)
这是功能,它的工作原理。解释是在代码中的注释中,但如果您发现任何令人困惑的事情让我知道,我会解释它。
public static boolean diagonals(char[][] b, int row, int col, int l) {
int forwardCounter = 1; // this counts top right to bottom left
int backCounter = 1; // this counts top left to bottom right
int distance = 1;
// 0 = topleft, 1 = topright, 2 = bottomleft, 3 = bottomright
boolean[] checks = new boolean[]{true, true, true, true};
char charAtPosition = b[row][col];
while(checks[0] || checks[1] || checks[2] || checks[3]) {
for(int i = 0; i < 4; i++) {
if(checks[i]) {
// This looks confusing but it's simply just converting i into
// The four different directions
checks[i] = checkSquare(b, row + (i < 2 ? -distance : distance),
col + (i % 2 == 0 ? -distance : distance), charAtPosition);
if(checks[i]) {
// If top left or bottom right
if(i % 3 == 0) {
backCounter++;
} else {
forwardCounter++;
}
}
}
}
if (forwardCounter >= l || backCounter >= l) return true;
distance++;
}
return false;
}
private static boolean checkSquare(char[][] b, int row, int col, char check) {
if(row < 0 || row >= b.length) return false;
if(col < 0 || col >= b[0].length) return false;
return check == b[row][col];
}
答案 1 :(得分:1)
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
}
我们的想法是走向四个方向并计算步数。这可能不是最有效的实现,但至少它看起来整洁且易于理解。