我正在用 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/