Search code examples
c++conways-game-of-life

Alive neighbour cells not correctly counted


I know my title isn't very specific but that's because I have no idea where the problem comes from. I'm stuck with this problem since 2 or 3 hours and in theory everything should be working, but it's not. This piece of code:

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {

        neighbour = coords(locX + x, locY + y, width);      //Get the cell index in the array

        if (existsInOrtho(ortho, neighbour)) {      //If the index exists in the array

            if (ortho[neighbour] == 0) {        //Cell is dead
                cnt--;      //Remove one from the number of alive neighbour cells
            }

        } else {        //Cell is not in the zone
            cnt--;      //Remove one from the number of alive neighbour cells
        }

    }
}

Iterates through all the neighbour cells to get their value in the array (1 for alive, 0 for dead). The "coords" function, shown here:

int coords(int locX, int locY, int width)
{
    int res = -1;

    locX = locX - 1;    //Remove one from both coordinates, since an index    starts at 0 (and the zone starts at (1;1) )
    locY = locY - 1;

    res = locX * width + locY;      //Small calculation to get the index of the pixel in the array

    return res;
}

Gets the index of the cell in the array. But when I run the code, it doesn't work, the number of neighbour cells is not correct (it's like a cell is not counted every time there's some alive in the neighborhood). I tried decomposing everything manually, and it works, so I don't know what ruins everything in the final code... Here is the complete code. Sorry if I made any English mistake, it's not my native language.


Solution

  • This code ...

    for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
        for ( int y = -1; y <= 1; y++ ) {
    

    Actually checks 9 cells. Perhaps you forgot that it checks (x,y) = (0,0). That would include the cell itself as well as its neighbours.

    A simple fix is:

    for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
        for ( int y = -1; y <= 1; y++ ) {
            if (x || y) {
    

    Also, the simulate function (from your link) makes the common mistake of updating the value of the cell in the same array before processing state changes required for the cells beside it. The easiest fix is to keep two arrays -- two complete copies of the grid (two ortho arrays, in your code). When reading from orthoA, update orthoB. And then on the next generation, flip. Read from orthoB and write to orthoA.