0

我正在通过一个练习来重现康威的生命游戏,我有一个基本的策略,而且我仍然处于“让它发挥作用”的阶段,所以我知道这看起来很有趣。

我现在遇到的问题是我正在尝试遍历二维数组,并且每次都调用确定细胞是生还是死的函数。这是为 '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);
        }
    }                            
4

1 回答 1

1

您的代码存在一些问题:

  • 整个代码中的几个调用引用了未声明的变量rowcol.
  • 循环声明row为全局(不是“错误”,但不是好的做法)
  • 方法调用输入deadCellsLiveOrDie错误。
  • getNeighbors方法不进行边界检查,因此您将超出范围。

可以在此处找到(快速)固定版本:http: //jsfiddle.net/Eakcm/

于 2013-09-01T20:55:49.667 回答