我是Java新手,现在我正在解决这个问题。我得到了一个游戏板(AxA),所以它的二维数组和每个盒子里都需要有关于行和列的信息,而且还有大约8个对象,围绕着这个盒子。这是现在它做Java玩家板初始化
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
Field neighbours[] = new Field[8];
neighbours[0] = x-1 >= 0 && x-1 < 8 ? this.playBoard[x-1][y] : null;
neighbours[1] = x-1 >= 0 && x-1 < 8 && y+1 >= 0 && y+1 < 8 ? this.playBoard[x-1][y+1] : null;
neighbours[2] = y+1 >= 0 && y+1 < 8 ? this.playBoard[x][y+1] : null;
neighbours[3] = x+1 >= 0 && x+1 < 8 && y+1 >= 0 && y+1 < 8 ? this.playBoard[x+1][y+1] : null;
neighbours[4] = x+1 >= 0 && x+1 < 8 ? this.playBoard[x+1][y] : null;
neighbours[5] = x+1 >= 0 && x+1 < 8 && y-1 >= 0 && y-1 < 8 ? this.playBoard[x+1][y-1] : null;
neighbours[6] = y-1 >= 0 && y-1 < 8 ? this.playBoard[x][y-1] : null;
neighbours[7] = x-1 >= 0 && x-1 < 8 && y-1 >= 0 && y-1 < 8 ? this.playBoard[x-1][y-1] : null;
System.out.println("X: "+x+", Y: "+y);
for(int i = 0; i < neighbours.length; i++)
System.out.println(" "+neighbours[i]);
this.playBoard[x][y] = new FieldClass(x, y, neighbours);
}
}
唯一问题是,如果我试图挽救一些箱子作为邻居,我还没有遍历,所以没有对象,我得到空,这是合乎逻辑的,因为这个对象是没有初始化,所以我不能在那里。 我怎么能这样做,它会工作的财产?
分两步进行 - 初始化电路板,然后遍历它以找到邻居。 – TDG