在人生游戏中计算邻居的方法



我知道这是关于生活游戏的许多问题,但我仍然无法理解如何在javafx中正确编写此方法。 这是我的代码不起作用,因为我不明白如何实现计算邻居的算法。

public void stepMethod(ActionEvent event){
for (int x = 0; x < cellSize; x++){
for (int y = 0; y < cellSize; y++){
int neighbours = countNeighbors(x, y);
nextGeneration[x][y] = board [x][y];
nextGeneration[x][y] = (neighbours == 3) ? true: nextGeneration[x][y];
nextGeneration[x][y] = ((neighbours < 2) || (neighbours > 3)) ? false : nextGeneration[x][y];
}
}
draw();
}
public int countNeighbors(int x, int y){
int neighbours = 0;
if (board [x-1][y-1]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x][y-1]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x+1][y-1]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x-1][y]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x+1][y]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x-1][y+1]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x][y+1]){
neighbours+=1;
}else{
neighbours+=0;
}
if (board[x+1][y+1]){
neighbours+=1;
}else{
neighbours+=0;
}
if(board[x][y]){
neighbours--;
}
return neighbours;
}

这是我的绘制方法

public void draw(){
initGraphics();
for(int x = 0; x < cellSize; x++){
for(int y = 0; y < cellSize; y++){
if(board[x][y] ){
gc.setFill(Color.CHOCOLATE);
gc.fillOval(x*cellSize,y*cellSize,cellSize,cellSize);
}
}
}
}

你的错误

java.lang.ArrayIndexOutOfBoundsException: -1 at
sample.Controller.countNeighbors(Controller.java:54) at
sample.Controller.stepMethod(Controller.java:118) 

是运行时错误 - 不是编译错误。它说你的索引(即来自[x-1]的东西等)已经OutOfBounds了。

例如,您需要在 ifs 和其他条件中添加更多条件

if (board [x-1][y-1]){

将是一个问题是xy是0,所以

if (x>0 && y>0 && board [x-1][y-1]){

您需要进一步检查上限。

决定在板的边缘做什么。绕圈?让它成为世界的边缘?轮到你了。

在第一次迭代时,您将有x=0 and y=0.因此,评估board[x-1][y-1]会给你一个板[-1][-1],这将提高ArrayOutOfBoundsException

最新更新