Search code examples
javajavafxconways-game-of-life

counting neighbors method in game of life


I know that it was many questions about game of life, but still I can't understand how to write this method correctly in javafx. here is my code which doesn't work, because I don't understand how to implement algorithm for counting neighbors.

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;
}

and here is my draw method

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);
            }
        }
    }

}

Solution

  • Your error

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

    is a runtime error - not compilation error. It says you index (i.e. stuff from [x-1] etc) has gone OutOfBounds.

    You need to add even more conditions in the ifs and elses, for example

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

    will be a problem is x or y is 0, so

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

    You need to check against the upper bound too further down.

    Decide what to do at the edges of the board. Wrap round? Make itthe edge of the world? Up to you.