c++ - 在 openframeworks 中使用 c++ vector 的生命元胞自动机游戏

标签 c++ openframeworks cellular-automata

我正在用 C++ (openFrameworks) 构建一个生命游戏 CA。由于我是 C++ 的新手,我想知道是否有人可以让我知道我是否在以下代码中正确设置了 vector 。 CA 不会绘制到屏幕上,我不确定这是否是我设置 vector 的结果。我必须使用一维 vector ,因为我打算将数据发送到仅处理一维结构的纯数据。

GOL::GOL() {
    init();
}


void GOL::init() {
  for (int i =1;i < cols-1;i++) {
    for (int j =1;j < rows-1;j++) {
        board.push_back(rows * cols);
        board[i * cols + j] = ofRandom(2);
    }
  } 
}


void GOL::generate() {
  vector<int> next(rows * cols);

  // Loop through every spot in our 2D array and check spots neighbors
  for (int x = 0; x < cols; x++) {
    for (int y = 0; y < rows; y++) {

      // Add up all the states in a 3x3 surrounding grid
      int neighbors = 0;
      for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
          neighbors += board[((x+i+cols)%cols) * cols + ((y+j+rows)%rows)];
        }
      }

      // A little trick to subtract the current cell's state since
      // we added it in the above loop
      neighbors -= board[x * cols + y];

      // Rules of Life
      if ((board[x * cols + y] == 1) && (neighbors <  2)) next[x * cols + y] = 0;        // Loneliness
      else if ((board[x * cols + y] == 1) && (neighbors >  3)) next[x * cols + y] = 0;        // Overpopulation
      else if ((board[x * cols + y] == 0) && (neighbors == 3)) next[x * cols + y] = 1;        // Reproduction
      else next[x * cols + y] = board[x * cols + y];  // Stasis
    }
  }

  // Next is now our board
  board = next;
}

最佳答案

这在您的代码中看起来很奇怪:

void GOL::init() {
  for (int i =1;i < cols-1;i++) {
    for (int j =1;j < rows-1;j++) {
        board.push_back(rows * cols);
        board[i * cols + j] = ofRandom(2);
    }
  } 
}

“vector.push_back( value )” 表示“将值附加到此 vector 的末尾”,请参阅 std::vector::push_back reference 这样做之后,您访问 board[i * cols + j] 的值并将其更改为随机值。我认为您正在尝试做的是:

void GOL::init() {
  // create the vector with cols * rows spaces:
  for(int i = 0; i < cols * rows; i++){
      board.push_back( ofRandom(2));
  }

}

这是访问 vector 中位置 x,y 处的每个元素的方式:

  for (int x = 0; x < cols; x++) { 
    for (int y =  0; y < rows; y++) {
        board[x * cols + y] = blabla;
    }
  } 

这意味着在 void GOL::generate() 中,您在执行此操作时没有访问正确的位置:

      neighbors += board[((x+i+cols)%cols) * cols + ((y+j+rows)%rows)];

我想你想这样做:

      neighbors += board[((x+i+cols)%cols) * rows + ((y+j+rows)%rows)];

所以 x * 行 + y 而不是 x * 列 + y

关于c++ - 在 openframeworks 中使用 c++ vector 的生命元胞自动机游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15439485/

相关文章:

c - 为什么我的滑翔机永远不会删除,而是保留在我的生命游戏模拟游戏的屏幕底部?

c++ - 有没有办法在本地范围内为单例分配名称?

C++ int 出现次数未知范围

c++ - 延迟函数使 openFrameworks 窗口卡住,直到指定的时间过去

opencv - 可以将 OpenCV 与 Processing 和 Openframeworks 一起使用吗?

java - 我如何画元胞自动机

c++ - 需要帮助理解 vector 如何以二进制表示 [C++]

c++ - (C++) 将 'this' 作为默认参数传递给静态方法

c++ - 如何在 iOS 的 openframeworks 中构建 3d 钻石

C++ - 静态数组的性能,启动时大小可变