[英]Game Of Life Java - Counting neighbors with 2D arrays and for loops
[英]counting neighbors method in game of life
我知道关于生活游戏的问题很多,但我仍然不明白如何在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
。
您需要在if和else中添加更多条件,例如
if (board [x-1][y-1]){
是一个问题是x
或y
为0,所以
if (x>0 && y>0 && board [x-1][y-1]){
您需要检查下限是否太高。
决定在电路板边缘做什么。 包好吗? 成为世界的边缘? 由你决定。
在您的第一次迭代中,您将拥有x=0 and y=0
。 因此,评估board[x-1][y-1]
将为您提供board [-1] [-1],这将引发ArrayOutOfBoundsException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.