我知道这是很多关于生活游戏的问题,但我仍然不知道如何用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);
}
}
}
}发布于 2017-03-23 16:35:33
你的错误
java.lang.ArrayIndexOutOfBoundsException: -1 at
sample.Controller.countNeighbors(Controller.java:54) at
sample.Controller.stepMethod(Controller.java:118) 是运行时错误-而不是编译错误。它说你的索引(也就是来自[x-1]等的东西)已经消失了OutOfBounds。
您需要在ifs和else中添加更多的条件,例如
if (board [x-1][y-1]){问题是x或y是0,所以
if (x>0 && y>0 && board [x-1][y-1]){你需要检查的上限太低。
决定在董事会的边缘做些什么。绕一圈?让它成为世界的边缘?你说了算。
发布于 2017-03-23 16:38:06
在第一次迭代时,您将得到x=0 and y=0。因此,评估board[x-1][y-1]会给你一个董事会-1,这将提高ArrayOutOfBoundsException。
https://stackoverflow.com/questions/42981593
复制相似问题