1

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

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

1 回答 1

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 参考 执行此操作后,您访问 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

于 2013-04-23T21:45:35.177 回答