以下是我现在的代码。
public class Knight1 {
public static void main(String[] args) {
int board[][] = new int[8][8];
int horizontal[] = new int[8];
int vertical[] = new int[8];
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
int moveNumber = 0;
int currentRow = 0;
int currentCol = 0;
int counter = 1;
int x = 0;
int y = 7;
int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
for (int i = 0; i < 8; i++) {
if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
currentRow = xOffset[i];
currentCol = yOffset[i];
Board[currentRow][currentCol] = counter;
counter++;
}
}
printBoard(board);
}
public static void printBoard(int[][] board) {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
System.out.print(" " + board[x][y]);
}
System.out.println();
}
}
}
答案 0 :(得分:0)
问题在于while条件,解决方案的提示是当currentRow / Column为0时必须排除-2和-1(如果为1则仅排除-2),当currentRow /时也排除+1和+2列是7(当它是6时只有+2)否则你的索引在[currentRow] [currentCol] = counter;将超出范围。
以下是骑士运动规则的外观:
int x = 0;
int y = 7;
int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
for (int i = 0; i < 8; i++) {
if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
// X and Y are currentRow and currentColumn in your example
// Code is copied from my java chess game and I was lazy to change variable everywhere
x = xOffset[i];
y = yOffset[i];
}
}