简体   繁体   中英

Conway's game of life: checking neighbours not working properly (c++)

I've been trying to figure out the problem behind this for a few days. I think it's counting the neighbours incorrectly because when I print the counts, the numbers are mostly 1s and 2s and my output board is completely blank. X ('X') means alive and ' ' means dead.

void NextGen(char lifeBoard[][MAX_ARRAY_SIZE], int numRowsInBoard, int numColsInBoard) {
    char nexGenBoard[MAX_ARRAY_SIZE][MAX_ARRAY_SIZE];

    // initialize nexGenBoard to blanks spaces
    for(int i = 0; i < numRowsInBoard; i++) {
        for(int j = 0; j < numColsInBoard; j++) {
            nexGenBoard[i][j] = {' '};
        }
    }
    // start from i = 1 and j = 1 to ignore the edge of the board
    for(int i = 1; i < numRowsInBoard-1; i++) {
        for(int j = 1; j < numColsInBoard-1; j++) {
            int count = 0;
            for(int y = -1; y < 2; y++) {
                for(int x = -1; x < 2; x++) {
                    if(!(x == 0 || y == 0)) {
                        if(lifeBoard[i+y][j+x] == X) //X is a global constant of 'X'. 
                        {
                            count++;
                        }
                    }
                }
            }

            if(lifeBoard[i][j] == X) {
                if(count == 2 || count == 3) {
                    nexGenBoard[i][j] = X;
                }
            }
            else if(lifeBoard[i][j] == ' ') {
                if(count == 3) {
                    nexGenBoard[i][j] = X;
                }
            }
        }
    }
    for(int i = 0; i < numRowsInBoard; i++) {
        for(int j = 0; j < numColsInBoard; j++) {
            lifeBoard[i][j] = nexGenBoard[i][j];
        }
    }
}

Your check during counting (!(x == 0 || y == 0)) is wrong. This will not check the square if either x or y is zero. You want to not count if both x and y are zero.

if (!(x == 0 && y == 0))

or

if (x != 0 || y != 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM