2017-04-23 75 views
-4
int movedistance = 5; // Distance to move the board 

@Override 
public byte getLive(int x, int y) { 
    return board[y][x]; // Arraylist board.get(y).get(x) ? 
} 

public void patternRight(){ 
     byte[][] testBoard = new byte[getHeight()][getWidth()]; 
     // testBoard = new Arraylist<> ? 
     for (int x = 0; x < getHeight(); x++) { 
      for (int y = 0; y < getWidth(); y++){ 
       if (getLive(y, x) == 1) testBoard[x][y + movedistance] = 1; 
      } 
     } 
} 

我正在嘗試使我的遊戲模式在我的棋盤(人生遊戲)上移動。此移動方法我目前已與字節[]。我想要做與ArrayList完全相同的方法。如何將我的byte []方法轉換爲arraylist []方法?

+1

歡迎來到Stack Overflow!請[參觀](http://stackoverflow.com/tour)以查看網站的工作原理和問題,並相應地編輯您的問題。另請參閱:[爲什麼「有人可以幫我嗎?」不是一個實際的問題?](http://meta.stackoverflow.com/q/284236) –

+2

爲什麼你想用'ArrayList'來解決什麼? –

回答

0

List<List<Byte>>代替byte[][]沒什麼意義,但是這裏是如何去做的。

不過,首先你的代碼是與數組索引的順序不一致的:聲明爲x,y

  • getLive()參數,但你if (getLive(y, x) == 1)調用它。
  • getLive(),您使用board[y][x],但你用testBoard[x][y + movedistance] = 1;
  • 不過也可以使用getHeight()x,並getWidth()y,所以也許這(不小心?) 「增加了」。

我將假設方法應該總是x,y,陣列應[y][x],那x是「寬度」和y爲「高度」。

此外,[y + movedistance]將導致ArrayIndexOutOfBoundsException,因爲您的循環使用全範圍的值。我會假設你想在溢出時「環繞」。

public byte getLive(int x, int y) { 
    return board.get(y).get(x); 
} 

public void patternRight(){ 
    List<List<Byte>> testBoard = new ArrayList<>(); 
    for (int y = 0; y < getHeight(); y++) { 
     List<Byte> row = new ArrayList<>(); 
     for (int x = 0; x < getWidth(); x++) 
      row.add((byte) 0); 
     testBoard.add(row); 
    } 
    for (int x = 0; x < getWidth(); x++) { 
     for (int y = 0; y < getHeight(); y++) { 
      if (getLive(x, y) == 1) 
       testBoard.get((y + movedistance) % getHeight()).set(x, (byte) 1); 
     } 
    } 
}