簡體   English   中英

康威的生活游戲:檢查鄰居工作不正常 (c++)

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

幾天來,我一直試圖找出這背后的問題。 我認為它對鄰居的計數不正確,因為當我打印計數時,數字主要是 1 和 2,而我的輸出板完全是空白的。 X ('X') 表示活着,' ' 表示死了。

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

您在計數時的檢查(!(x == 0 || y == 0))是錯誤的。 如果 x 或 y 為零,則不會檢查平方。 如果 x 和 y 都為零,您不想計數。

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

或者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM