簡體   English   中英

康威的生命游戲算法不起作用

[英]Conway's game of life algoritm is not working

我正在嘗試模擬康威的生活游戲。 我做的算法不起作用,但我不知道如何。
如果我有這樣的情況:
|.........|
|....x....|
|....x....|
|....x....|
|.........|
一種 。 是死細胞,x 是活細胞

預計垂直條會翻轉為水平條,但這不會發生。 相反,它只刪除底部的一個,再次運行它只會刪除底部,所以剩下 1 個。

顯然算法有問題,但我不知道是什么。 我一直在網上尋找但其他人遇到的所有問題,解決方案對我不起作用。

那么這個算法的錯誤是什么?

這是我的代碼:

void new_generation() {
        // Create one new generation

        // double for loop -> iterates every cell
        for (int i=0; i<worldHeight; i++){
            for (int j=0; j<WorldWidth; j++) {

                // find the amount of living neighbours, stored in count
                // dubbele for loop -> iterates every neighbour of the current cell
                count = 0;
                for (int y=0; y<2; y++) {
                    for (int x=0; x<2; x++){
                        if (i != 0 and j!= 0) { // the cell itself doesnt count
                            if (world[i+y][j+x]) count++;
                        }
                    }
                }

                if (world[i][j]) { // current cell is alive
                    if (count<2 or count>3) new_world[i][j] = false;
                    else new_world[i][j] = true;
                }
                else { // current cell is dead
                    if (count==3) new_world[i][j] = true;
                    else new_world[i][j] = false;
                }   
            }
        }

        // copy every value from the newly generated world to the current
        // double foor loop -> iterates every cell
        for (int i=0; i<worldHeight; i++){
            for (int j=0; j<WorldWidth; j++) {
                world[i][j] = new_world[i][j]; 
            }
        }

worldHeight 和 worldWidth 是表示世界有多大的整數。
world 和 new_world 是包含布爾值的二維數組,其中 true 是活細胞, false 是死細胞

你算錯了鄰居細胞

x 和 y 都從 0 到 2,而不是從 -1 到 2。

for (int y=0; y<2; y++) {//should be int y=-1; y<2; y++
    for (int x=0; x<2; x++){//should be int x=-1; x<2; x++
        if (i != 0 and j!= 0) { // shold be x!=0 or y!=0
            if (world[i+y][j+x]) count++;
        }
     }
 }

您還必須檢查world[i+y][j+x]是否有效(坐標在 0,大小范圍內)

第三個問題是,當你不想在word[i][j]計數時,你檢查if (i!=0 and j!=0) not x!=0 or y!=0 i 和 j 是坐標檢查單元格的 x 和 y 是坐標的差值。

暫無
暫無

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

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