首页 > 解决方案 > 如何检查表格中的相邻单元格以及它们是否应该着色

问题描述

如何检查相邻单元格?这些是细胞的规则

这是我到目前为止的代码JS Bin

function shouldBeAlive(row, col) {
  if (model[i][j] === true) {
    // check if it should stay alive or whether it should die
  }
  else {
    // check whether it should stay dead or come alive
  }
}

标签: javascript

解决方案


康威的生命游戏,做过一次,基本上我是这样做的:

function shouldBeAlive(row, col) {
  var neighbors_alive = 0;
  // first, calculate number of alive neighbors
  // 1. check if there is a top neighbor
  if (row > 0) {
    neighbors_alive += model[row - 1][col];
  }
  // 2. check if there is a bottom neighbor
  if (row < model.length - 1) {
    neighbors_alive += model[row + 1][col];
  }
  // 3. check if there is a left neighbor
  if (col > 0) {
    neighbors_alive += model[row][col - 1];
  }
  // 4. check if there is a right neighbor
  if (col < model[row].length - 1) {
    neighbors_alive += model[row][col + 1];
  }
  // 5. check if there is a top-right neighbor
  if (row > 0 && col < model[row].length - 1) {
    neighbors_alive += model[row - 1][col + 1];
  }
  // 6. check if there is a top-left neighbor
  if (row > 0 && col > 0) {
    neighbors_alive += model[row - 1][col - 1];
  }
  // 7. check if there is a bottom-right neighbor
  if (row < model.length - 1 && col < model[row].length - 1) {
    neighbors_alive += model[row + 1][col + 1];
  }
  // 8. check if there is a bottom-left neighbor
  if (row < model.length - 1 && col > 0) {
    neighbors_alive += model[row + 1][col - 1];
  }
  
  if (model[row][col] === true) {
    // check if it should stay alive or whether it should die
    if (neighbors_alive < 2 || neighbors_alive > 3) {
      return false;
    }
    return true;
  }
  else {
    // check whether it should stay dead or come alive
    if (neighbors_alive === 2) {
      return true;
    }
    return false;
  }
}

注意:将布尔值添加到整数时,它的值会自动转换,true变为1false变为0

编辑:对您的代码进行一些编辑:

首先,检查上面函数中的编辑,然后,你的evolve函数应该是这样的:

function evolve() {
  for (var i = 0; i < model.length; i++) {
    for (var j = 0; j < model[i].length; j++) {
      model[i][j] = shouldBeAlive(i, j); // before, it was shouldBeAlive()
    }
  }
  paintGrid();
}

推荐阅读