在openframeworks中使用c ++向量的生命游戏细胞自动机

时间:2013-03-15 18:18:41

标签: c++ openframeworks cellular-automata

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

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

1 个答案:

答案 0 :(得分:0)

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

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)”表示“将值附加到此向量的末尾”,请参阅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));
  }

}

这是你在向量中访问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 * rows + y而不是x * cols + y