2016-03-04 60 views
0

我是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); 
     } 
    } 

唯一问题是,如果我试图挽救一些箱子作为邻居,我还没有遍历,所以没有对象,我得到空,这是合乎逻辑的,因为这个对象是没有初始化,所以我不能在那里。 我怎么能这样做,它会工作的财产?

+2

分两步进行 - 初始化电路板,然后遍历它以找到邻居。 – TDG

回答

0
for (int x = 0; x < size; x++) { 
    for (int y = 0; y < size; y++) { 
     this.playBoard[x][y] = new FieldClass(x, y); 
    } 
} 

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].setNeighbours(neighbours)); 
    } 
} 
0

所以,当你添加[X,Y]作为邻居[U,V]请确保您添加[U,V]为[X,Y]的邻居

你将不得不拆分尽管如此,你的三元运算符转换为传统的if语句。