我编写了 Conway 的快速 JS 实现。
为了计算与给定单元格相邻的“活”单元格的数量,我手动检查 8 个单元格中的每一个。
function getNeighbourCount(x, y){
var intCount = 0;
intCount = (getCell(x-1, y-1)? intCount+1 : intCount); //x-1, y-1
intCount = (getCell(x, y-1)? intCount+1 : intCount);//x, y-1
intCount = (getCell(x + 1, y-1)? intCount+1 : intCount);//x + 1, y-1
intCount = (getCell(x-1, y)? intCount+1 : intCount);//x-1, y
intCount = (getCell(x+1, y)? intCount+1 : intCount);//x+1, y
intCount = (getCell(x-1, y+1)? intCount+1 : intCount);//x-1, y+1
intCount = (getCell(x, y+1)? intCount+1 : intCount);//x, y+1
intCount = (getCell(x+1, y+1)? intCount+1 : intCount);//x-1, y+1
return intCount;
}
它可以工作,但看起来很笨重。是否有另一种更优雅的技术来实现同样的目标?优选地,一种适用于不同内核大小的技术。
这是一个带有工作示例的 fiddle : http://jsfiddle.net/3vpz14v7/
注释:
- 游戏的状态保存在二维 bool 数组中(本例中为 50*50)
- getCell(x,y) 返回坐标包裹的单元格的值。
最佳答案
您可以以更紧凑和可视化的格式存储内核,例如,
var kernel = [
"111",
"101",
"111"]
然后,您可以编写一个函数来将其解码为对 getCell 的调用,从而使您的内核易于读取和修改(“1”表示“如果该位置的单元还活着,则加 1”)。
关于javascript - 元胞自动机的相邻单元格计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32777682/