【发布时间】:2017-03-23 16:18:47
【问题描述】:
我知道这是关于生命游戏的很多问题,但我仍然无法理解如何在 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);
}
}
}
}
【问题讨论】:
-
我认为
x-1或x+1可能会超出边缘(y也是如此)。究竟出了什么问题? -
不行,按这个step方法的时候,编译的时候有错误,但是不知道到底是什么问题
-
分享编译中的错误信息然后:-)
-
通过“分享错误消息”是为了让您edit 您的问题并包含整个错误消息。你有read the error message and tried to understand it吗? (顺便说一句,这不是编译错误:如果您有编译错误,您将无法运行该应用程序。)
-
顺便说一句:一些代码可以缩短:
nextGeneration[x][y] = (neighbors == 3);在stepMethod的 for 循环体中。此外,所有else{ neighbours+=0; }都可以删除,这些语句没有任何效果。另外要计算值,您可以简单地使用循环并再次减去“中心”的值:int neighbors = (neighbors[x][y] ? -1 : 0); for(int i = -1; i <= 1; i++) { for (int j=-1; j <= 1; j++) { if (board[x+i][y+j]) { neighbors++;}}}
标签: java javafx conways-game-of-life