2016-03-04 64 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語句。