1

C++ (openFrameworks) でゲーム オブ ライフ CA を構築しています。私は C++ を初めて使用するので、次のコードでベクトルを正しく設定しているかどうかを誰かに教えてもらえないかと思っていました。CA は画面に描画しません。これがベクトルの設定方法の結果であるかどうかはわかりません。1D 構造のみを処理する Pure Data にデータを送信するつもりなので、1D ベクトルを使用する必要があります。

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 * cols + y の代わりに x * rows + y

于 2013-04-23T21:45:35.177 に答える