2015-10-14 101 views
1

我已經被賦予處理康威生命遊戲的任務。康威的生命遊戲(構造和更新遊戲)

我遇到了我的CellGrid方法和simulateStep方法的問題。活着的可能性似乎並沒有起作用,並且在simulateStep中,我得到了NullPointerException錯誤。

這裏是我的代碼:

public class CellGrid 
{ 
    private Cell[][] cells; 


/** 
* This populates the grid with cells that will be 
* either living or dead (with this probability given by lifeChance) 
* 
* @param size - grid size 
* @param lifeChance - probability of each cell starting out alive 
*/ 
public CellGrid(int size, double lifeChance) 
{ 
    cells = new Cell[size][size]; 
    Random r = new Random(); 

    for (int i = 0; i < cells.length; i++) 
    { 
     for (int j = 0; j < cells.length; j++) 
     { 
      Cell c = new Cell(); 
      double nextVal = r.nextDouble(); 
      if (nextVal < lifeChance) 
      { 
       c.setAlive(false); 
      } 
      else 
      { 
       c.setAlive(true); 
      } 
     } 
    } 
} 

/** 
* Iterates the simulation by one step (according to Game of Life rules) 
*/ 
public void simulateStep() 
{ 
    for (int y = 0; y < cells.length; y++) 
    { 
     for (int x = 0; x < cells.length; x++) 
     { 
      boolean living = cells[y][x].isAlive(); 
      int count = countNeighbours(y, x); 
      boolean result = false; 

      if (living && count <= 2) 
      { 
       result = false; 
      } 
      if (living && (count == 3 || count == 4)) 
      { 
       result = true; 
      } 
      if (living && count == 5) 
      { 
       result = false; 
      } 
      if (living == true && count > 5) 
      { 
       result = true; 
      } 
      if (living == false && count > 5) 
      { 
       result = true; 
      } 

      result = cells[y][x].isAlive(); 
     } 
    } 
} 

setAlive方法:

public void setAlive(boolean alive) 
{ 
    if (isAlive()== true) 
    { 
     this.alive = false; 
    } 

    if (isAlive() == false) 
    { 
     this.alive = true; 
    } 
} 

感謝您對您的幫助!

+1

你能發佈顯示NPE的堆棧跟蹤嗎? – MikeJ

+1

這段代碼應該做什麼:'double nextVal = r.nextDouble();'?通常在使用Random類時,您將設置一系列數字,以便Random類可以隨機選擇一個數字。還可以顯示setAlive()方法嗎? – ryekayo

+0

@ryekayo - 如果'lifeChance'是[0,1]範圍內的雙精度值,那麼這條線確定單元格的初始狀態。整個構造函數隨機化整個平面的狀態。 –

回答

4

您應該在構造函數中將Cell c = new Cell();更改爲cells[i][j] = new Cell();

+1

...或者至少添加'cells [i] [j] = c;' – Thomas