javascript - 如何检查表格中的相邻单元格以及它们是否应该着色
问题描述
如何检查相邻单元格?这些是细胞的规则
- 如果一个活细胞少于两个活着的邻居,它就会灭亡
- 如果一个活细胞有两个或三个活着的邻居,它会继续生活
- 如果一个活细胞有超过三个活着的邻居,它就会灭亡
- 如果一个死细胞恰好有三个活着的邻居,它就会形成
这是我到目前为止的代码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
}
}
解决方案
康威的生命游戏,做过一次,基本上我是这样做的:
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
变为1
,false
变为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();
}
推荐阅读
- powershell - 如何使用powershell写入没有换行符的csv文件?
- reactjs - 在材质ui reactJS中使用useAutoComplete时如何使用popperComponent Props
- html - 按条件角度改变伪元素样式
- python-3.x - 无法使用 fbchat 登录 Facebook
- node.js - 使用 Nodejs Lambda 从 S3 上的 .xlsx 文件中读取数据
- javascript - 如何通过 Fabric.js 中的选定项目获取 id
- python - 在我的基于文本的游戏中多次重复代码部分
- c# - 如何删除 FontEditor 标题栏
- kubernetes - 一段时间后 Pod 不可见
- c++ - 使用并行 for_each 组装数据