use*_*873 1 java arrays conways-game-of-life
我正在写一个基于John Conway的生命游戏的程序.我得到它编译,甚至在经过几天不间断的工作后运行.但是,打印出来的结果是错误的......
这是我的代码(不包括主要方法)
//clears the grid
public static void clearGrid ( boolean[][] grid )
{
for(int row = 0; row < 18; row++){
for(int col = 0; col < 18; col++){
grid[row][col]= false;
}
}
//set all index in array to false
}
//generate the next generation
public static void genNextGrid ( boolean[][] grid )
{
int n; //number of neighbors
boolean[][] TempGrid = grid;// a temporary array
for(int row = 0; row < 18; row++)
{
for(int col = 0; col < 18; col++)
{
TempGrid[row][col] = grid[row][col];
n = countNeighbors(grid, row, col);
if(grid[row][col] == true)
{
if(n != 2 && n != 3)
{
TempGrid[row][col] = false;
}
else
TempGrid[row][col] = true;
}
else
{
if(n == 3)
{
TempGrid[row][col] = true;
}
else
TempGrid[row][col] = false;
}
grid[row][col] = TempGrid[row][col];
}
}
}
//count how many neighbors surrounding any speicific cell
public static int countNeighbors ( final boolean[][] grid, final int row, final int col )
{
int n = 0;
for (int TempRow = row - 1; TempRow <= row + 1; TempRow++)
{
if (TempRow >= 0 && TempRow < 18)
{
for (int TempCol = col - 1; TempCol <= col + 1; TempCol++)
{
if (TempCol >= 0 && TempCol < 18 && (TempRow != row || TempCol != col))
{
if (grid[TempRow][TempCol])
{
n++;
}
}
}
}
}
return n;
}
Run Code Online (Sandbox Code Playgroud)
我很确定我的genNextGrid方法中出现了问题.
包括分配表
public static void genNextGrid (boolean[][] grid);
Run Code Online (Sandbox Code Playgroud)
该方法实际上将生成下一代模拟.它应该使用传递给它的二维数组网格作为"当前"代.它应该创建一个第二个临时二维数组,它将保存"下一代".您需要创建此临时矩阵才能使用,因为您无法更改当前矩阵,因为您可能会失去成功创建下一代所需的所有信息."
所以我不确定我做错了什么.
现在已经快到凌晨3点了,从中午开始就一直盯着我的Vim屏幕.任何帮助都会受到极大的关注.
boolean[][] TempGrid = grid;
Run Code Online (Sandbox Code Playgroud)
将使用相同的数组,只是使用不同的名称.你必须分配一些新的内存.看看你的代码,这应该可以解决问题:
boolean TempGrid = new boolean[18][18];
Run Code Online (Sandbox Code Playgroud)
(如果你用18常数替换那些s 会好得多)