public static boolean[][] calculate(boolean cellState[][])//imports cell patern(in the form of a graph)
{
int x = 0, y = 0;
int alive = 0;
boolean newCellState[][] = new boolean[50][50];//what the next generation is stored in
while(x < 50 && y < 50)//calculation loop
{
try//each adjacent cell
{
if(cellState[x-1][y] == true)
alive++; //if the adjacent cell is alive the alive variable gets + 1
}catch(IndexOutOfBoundsException e) {}
try
{
if (cellState[x-1][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if(cellState[x-1][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if (cellState[x][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if (cellState[x][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if(cellState[x+1][y] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if(cellState[x+1][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
try
{
if(cellState[x+1][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }
if(cellState[x][y] = true) //determines if the cell should be alive in the next generation
{
if(alive < 2)
newCellState[x][y] = false;
else if(alive > 3)
newCellState[x][y] = false;
else if(alive == 2)
newCellState[x][y] = true;//stores in new cell state for next gen
else
newCellState[x][y] = true;
} else
{
newCellState[x][y] = false;
}
alive = 0; //resets alive
if(x == 49)//counter for graph
{
y++;
x=0;
}else
{
x++;
}
}
return newCellState;
}
这是我的方法,用于计算下一代康威的生命游戏。每次运行时,无论模式是什么,它都会打印出每个单元格,除了网格的边缘以外都是死的。
这是主要方法:
public static void main(String Args[])
{
int x = 0;
int y = 0;
boolean cellState[][] = new boolean[50][50];
String answer;
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("\n Type anything for next generation, 'new' for new grid, or 'stop' to end>> ");
answer = input.nextLine();
if(answer.equals("new"))
{
cellState = newCells();
}else if(answer.equals("stop"))
{
break;
}else
{
cellState = calculate(cellState);
print(cellState);
}
}
}
我已经测试了打印方法,因此它没有问题。我无法弄清楚为什么会这样做。所有帮助表示赞赏!谢谢!
答案 0 :(得分:1)
使用==
进行测试而非=
。
=如果条件不符合您的目的。
答案 1 :(得分:0)
if(cellState[x][y] = true)
您忘了使用==
这个。否则,您的代码看起来很好。