我已经构建了Conways的生活游戏,但算法运行不正常。我为此使用了Js和Jquery的组合。我的程序所做的是逐个单元格遍历整个棋盘,检查单元格的邻居,并通过检查它的邻居将游戏规则应用于每个单元格。下面是该代码:Conways游戏人生算法不能正常工作
function checkSquares() {
generation++;
document.getElementById('gen').innerHTML=generation;
for (var i = 100; i <= 6220; i++) {
if (squareArray[i][1] === 1) {
var total = squareArray[i + 81][1] + squareArray[i + 80][1] + squareArray[i + 79][1] + squareArray[i - 81][1] + squareArray[i - 80][1] + squareArray[i - 79][1] + squareArray[i + 1][1] + squareArray[i - 1][1];
switch (total) {
case 0:
case 1:
squareArray[i][1] = 0;
$('#square' + i).css("background-image", "url('http://www.fg-a.com/wallpapers/geo-shapes-black-1280.jpg')");
break;
case 4:
case 5:
case 6:
case 7:
case 8:
squareArray[i][1] = 0;
$('#square' + i).css("background-image", "url('http://www.fg-a.com/wallpapers/geo-shapes-black-1280.jpg')");
break;
}
}else{
var total = squareArray[i + 81][1] + squareArray[i + 80][1] + squareArray[i + 79][1] + squareArray[i - 81][1] + squareArray[i - 80][1] + squareArray[i - 79][1] + squareArray[i + 1][1] + squareArray[i - 1][1];
switch(total){
case 3:
squareArray[i][1] = 1;
$('#square' + i).css("background-image", "url('https://c1.staticflickr.com/3/2942/15323841455_6c64757dbd_b.jpg')");
break;
}
}
}
eliminate();
}
总之什么上面的代码做的就是把一个正方形,检查它的相邻小区,并使用if-else语句来决定细胞存活或死亡是否。
现在我知道问题是什么;例如以一个简单的模式,如这样的:
cell here dies ----> []
new cell born here --> [] <-- new cell born here
cell here dies ----> []
在我的代码会发生什么事是:
checks this cell, only one neighbour so it dies ---> []
When it comes to this cell it has only one neighbour because above -> []
neighbour died. Therefore it dies.
No neighbours, so this dies -----------------------> []
那么显而易见的解决方案是以某种方式检查整个图案,然后决定该细胞是否是生活或死亡。但是我怎样才能一次检查几个细胞?
另外,如果有帮助,这里是codepen链接到完整的程序:
http://codepen.io/Phantom-Intruder/pen/BLaBPG/