用C ++封装二维数组

问题描述 投票:0回答:1

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

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

规则:如果一个单元有2个或3个邻居它存活,超过3个或少于2它死亡,如果一个空的空间有3个邻居则它是“天生的”。我的“星球”是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

我确定我应该使用模数,但我尝试的任何东西似乎都工作。我已经尝试使用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
c++ arrays screen modulus
1个回答
0
投票

要留在[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 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.