屏幕在 C++ 中包装一个二维数组

Screen wrap a 2-D array in C++

我正在完成康威的生命游戏作业。我创建了一个函数来生成 1 和 0 的随机数组; 1 代表活细胞,0 代表空细胞 space.

我创建了一个单独的函数来检查邻域并进行计数以确定游戏的进展情况。

规则:如果一个单元格有 2 个或 3 个邻居,它就会存活,超过 3 个或少于 2 个就会死亡,如果一个空 space 有 3 个邻居,它就是 "born"。我的 "planet" 是 79 x 24 个字符,但在我包裹屏幕之前它还不是一个真正的星球。

函数如下:

void life (int master[24][79]) //generates/kills cells based on neighborhood
{
    int temp[24][79]; //temporary array for manipulating data
    copy (master, temp); //copy array onto temp
    for(int j = 0; j < h; j++) //height loop
    {

        for (int i = 0; i < w; i++) //width loop
        {
            int count = 0; //intialize neighbor count variable
            count = master[j-1][i] + //searches down
            master[j-1][i-1] + //down left
            master[j][i-1] + //left
            master[j+1][i-1] + //up left
            master[j+1][i] + //up
            master[j+1][i+1] + //up right
            master[j][i+1] + //right
            master[j-1][i+1]; //down right
            //cell dies if count falls below 2 or rises above 3
            if(count < 2 || count > 3)
                temp[j][i] = 0;
            //cell stays alive if it has two neighbors
            if(count == 2)
                temp[j][i] = master[j][i];
            //cell either stays alive or gets born if three neighbors
            if(count == 3)
                temp[j][i] = 1;
        } //end width loop
    }//end height loop
    copy(temp, master); //copy temp back to main array
} //end life function

我确定我应该使用 modulus,但我尝试的任何方法似乎都不起作用。我曾尝试使用 while 循环将最大值归零,但我可以看出它具有逐渐向下缠绕的效果,类似于螺纹缠绕螺钉的方式。我应该 mod-ify(抱歉)搜索部分代码看起来像这样吗?

int count = 0; //intialize neighbor count variable
            count = master[(j-1)%h][i%w] + //searches down
            master[(j-1)%h][(i-1)%w] + //down left
            master[j%h][(i-1)%w] + //left
            master[(j+1)%h][(i-1)%w] + //up left
            master[(j+1)%h][i%w] + //up
            master[(j+1)%h][(i+1)%w] + //up right
            master[j%h][(i+1)%w] + //right
            master[(j-1)%h][(i+1)%w]; //down right

要保持​​在 [0-w[ 范围内,您必须使用模数并确保您的数字是正数,因此,类似于

master[(j - 1 + h) % h][i % w]
+ master[(j - 1 + h) % h][(i - 1 + w) % w]
// ...

等等。

我建议添加一个访问函数,比如

int& get(int master[24][79], int i, int j)
{
    return master[(j - 1 + 24) % 24][(i - 1 + 79) % 79]
}

然后简单地使用

get(master, i, j - 1)
+ get(master, i - 1, j - 1)
// ...

我建议将您的数据包装在 class:

class WorldMap
{
public:
    int  get(int i, int j) const { return cells[(i + 24) % 24][(j + 79) % 79]; }
    int& get(int i, int j)       { return cells[(i + 24) % 24][(j + 79) % 79]; }
private:
    int cells[24][79] = {};
};

然后

void life (WorldMap& worldMap)
{
    WorldMap next;
    // ... initialize next according to rules of life
    worldMap = next;
}