我正在嘗試模擬康威的生活游戲。我做的演算法不起作用,但我不知道如何。
如果我有這樣的情況:
|.........|
|....x....|
|....x....|
|....x....|
|.........|
一種 。是死細胞,x 是活細胞
預計垂直條會翻轉為水平條,但這不會發生。相反,它只洗掉底部的一個,再次運行它只會洗掉底部,所以剩下 1 個。
顯然演算法有問題,但我不知道是什么。我一直在網上尋找但其他人遇到的所有問題,解決方案對我不起作用。
那么這個演算法的錯誤是什么?
這是我的代碼:
void new_generation() {
// Create one new generation
// double for loop -> iterates every cell
for (int i=0; i<worldHeight; i ){
for (int j=0; j<WorldWidth; j ) {
// find the amount of living neighbours, stored in count
// dubbele for loop -> iterates every neighbour of the current cell
count = 0;
for (int y=0; y<2; y ) {
for (int x=0; x<2; x ){
if (i != 0 and j!= 0) { // the cell itself doesnt count
if (world[i y][j x]) count ;
}
}
}
if (world[i][j]) { // current cell is alive
if (count<2 or count>3) new_world[i][j] = false;
else new_world[i][j] = true;
}
else { // current cell is dead
if (count==3) new_world[i][j] = true;
else new_world[i][j] = false;
}
}
}
// copy every value from the newly generated world to the current
// double foor loop -> iterates every cell
for (int i=0; i<worldHeight; i ){
for (int j=0; j<WorldWidth; j ) {
world[i][j] = new_world[i][j];
}
}
worldHeight 和 worldWidth 是表示世界有多大的整數。
world 和 new_world 是包含布林值的二維陣列,其中 true 是活細胞, false 是死細胞
uj5u.com熱心網友回復:
你算錯了鄰居細胞
x 和 y 都從 0 到 2,而不是從 -1 到 2。
for (int y=0; y<2; y ) {//should be int y=-1; y<2; y
for (int x=0; x<2; x ){//should be int x=-1; x<2; x
if (i != 0 and j!= 0) { // shold be x!=0 or y!=0
if (world[i y][j x]) count ;
}
}
}
您還必須檢查是否world[i y][j x]有效(坐標在 0,大小范圍內)
第三個問題是,當您不想計入時,word[i][j]您可以檢查if (i!=0 and j!=0)不x!=0 或 y!=0i 和 j 是檢查單元格的坐標,x 和 y 是坐標的差值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325429.html
下一篇:如何正確多載流運算子?
