首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生命博弈中的邻域计数法

生命博弈中的邻域计数法
EN

Stack Overflow用户
提问于 2017-03-23 16:18:47
回答 2查看 1.5K关注 0票数 0

我知道这是很多关于生活游戏的问题,但我仍然不知道如何用javafx正确地编写这个方法。下面是我的代码,它不起作用,因为我不知道如何实现计算邻居的算法。

代码语言:javascript
复制
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;
}

这是我的抽签方法

代码语言:javascript
复制
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);
            }
        }
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-23 16:35:33

你的错误

代码语言:javascript
复制
 java.lang.ArrayIndexOutOfBoundsException: -1 at
 sample.Controller.countNeighbors(Controller.java:54) at
 sample.Controller.stepMethod(Controller.java:118) 

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

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

代码语言:javascript
复制
if (board [x-1][y-1]){

问题是xy是0,所以

代码语言:javascript
复制
if (x>0 && y>0 && board [x-1][y-1]){

你需要检查的上限太低。

决定在董事会的边缘做些什么。绕一圈?让它成为世界的边缘?你说了算。

票数 2
EN

Stack Overflow用户

发布于 2017-03-23 16:38:06

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42981593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档