2015-11-03 160 views
-2

我想爲我的CS課程構建一個康威的生命遊戲程序,並且我被困在其中一種方法上。以下是我迄今爲止:康威的生命遊戲方法

public class GameOfLifeFunctions { 
    public static void toggleCell(int row, int col, int[][] board) { 
     // TODO: This next line crashes the program, so delete it when you start coding 
     //throw new UnsupportedOperationException("DELETE THIS LINE WHEN YOU START CODING"); 
     board[row][col]=board[row][col]==0?1:0; 
    } 

    public static void resetCells(int[][] board) { 
     // TODO: This next line crashes the program, so delete it when you start coding 
     //throw new UnsupportedOperationException("DELETE THIS LINE WHEN YOU START CODING"); 
     for (int j=0; j<board.length; j++) { 
      for (int i=0; i<board.length; i++) { 
       board[j][i]=0; 
      } 
     } 
    } 

    public static int[][] copyCells(int[][] board) { 
     int[][] copy=new int[board.length][board[0].length]; 

     // TODO: This next line crashes the program, so delete it when you start coding 
     //throw new UnsupportedOperationException("DELETE THIS LINE WHEN YOU START CODING"); 
     for (int j=0; j<board.length; j++) { 
      for (int i=0; i<board.length; i++) { 
       copy[j][i]=board[j][i]; 
      }    
     } 
     return copy; 
    } 

    public static int getNumLiveNeighbors(int[][] cells, int row, int col) { 
     int h=cells.length; 
     int w=cells[0].length; 
     int count=0; 

     // TODO: This next line crashes the program, so delete it when you start coding 
     //throw new UnsupportedOperationException("DELETE THIS LINE WHEN YOU START CODING"); 
     for (int j=row-1; j<=row+1; j++) { 
      for (int i=col-1; i<=col+1; i++) { 
       //Something broken in this if statement 
       //OutOfBounds problem 
       if (j==row && i==col) { 
        continue; 
       } 
       if (j<0 || j>h-1 || 1<0 || i>w-1) { 
        ; 
       }  
       else if (cells[j][i]==1) { 
        count++; 
       }     
      } 
     } 
     return count; 
    } 

    public static int[][] calcualteNextGeneration(int[][] cells) { 
     // TODO: Calculate the next generation by calling getNumLiveNeighbors for each 
     // cell in the grid. Put the results of the new generation into the 2D array result. 
     int[][] result=new int[cells.length][cells[0].length]; 
     int living; 

     // TODO: This next line crashes the program, so delete it when you start coding 
     for (int j; j<cells.length; j++) { 
      for (int i; i<cells[0].length; i++) { 

      } 
     } 
     throw new UnsupportedOperationException("DELETE THIS LINE WHEN YOU START CODING"); 
    } 

我被困在getNumLiveNeighbors方法。如果你能幫我解釋,那就太棒了!

+0

選擇您的代碼,然後按CTL + K – 2015-11-03 02:58:43

+0

我試圖返回每個單元格鄰居的數目,以判斷它是活着的(bool = 1)還是死亡(bool = 0)。我想爲下一代計算,並開始研究這種方法是我遇到麻煩的地方。對不起,我的問題含糊不清。 – TheWoerbler

回答

1

if (j<0 || j>h-1 || 1<0 || i>w-1)我認爲你的意思是i<0作爲第三個測試,而不是1<0