コンウェイのライフ ゲームを再現するための演習を行っています。基本的な戦略はありますが、まだ「機能させる」段階にあるので、これはかなりおかしなことだと思います。
私が今直面している問題は、2 次元配列を繰り返し処理し、そのたびに細胞が生きているか死んでいるかを判断する関数を呼び出そうとしていることです。これは、'col' に対して 'undefined' を返すコードの最後のブロックです。
関数は、ループの外側で呼び出されたときに機能します (行と列に変数が割り当てられています)。
ただし、ループ内で関数を呼び出そうとすると、未定義の値が返されます。これは範囲の問題だと思いますが、正確に修正する方法がわかりません。
コードは次のとおりです。
// this is the world that is being calculated
var world = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]
];
// this is where the new calculated values are stored until they are ready to
// be transferred back to the first array: world
var tempWorld = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
function getNeighbors(row, col) {
// variables that get the values of the 8 neighboring cells
var currentCell = world[row][col];
var upperLeftCorner = world[row - 1][col - 1];
var above = world[row - 1][col];
var upperRightCorner = world[row - 1][col + 1];
var left = world[row][col - 1];
var right = world[row][col + 1];
var bottomLeft = world[row + 1][col - 1];
var bottom = world[row + 1][col];
var bottomRight = world[row + 1][col + 1];
// this variable adds the neighboring cells together
var totalNumberOfNeighbors = upperLeftCorner + above + upperRightCorner + left + right + bottomLeft + bottom + bottomRight
return totalNumberOfNeighbors;
};
// test to confirm that getNeighbors is working
console.log("value of getNeighbors is: " + getNeighbors(row, col));
function deadCellsLiveOrDie (row, col) {
// Rule to make dead cells living
if (world[row][col] === 0) {
if (getNeighbors(row, col) === 3) {
tempWorld[row][col] = 1;
}
}
};
deadCellsLiveOrDie(row, col);
livingCellsLiveOrDie(row, col);
function livingCellsLiveOrDie (row, col) {
// Rule to determine if living cells die or live
if (world[row][col] === 1) {
if ((getNeighbors(row, col) === 2) || (getNeighbors(row, col) === 3)) {
tempWorld[row][col] = 1;
} else tempWorld[row][col] = 0
}
};
// test to confirm that rules of life work for a cell
console.log("tempWorld row, col is: " + tempWorld[row][col]);
// iterate over the 2-D array
for (row = 0; row < world.length; ++ row)
{
var col;
for (col = 0; col < world[row].length; ++ col) {
deadCellsLiverOrDie(row, col);
livingCellsLiveOrDie(row, col);
}
}