gpt4 book ai didi

javascript - Conways 生命游戏算法无法正常工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:10 27 4
gpt4 key购买 nike

我构建了 Conways 生命游戏,但算法运行不正常。我为此混合使用了 Js 和 Jquery。我的程序所做的是逐个单元格地遍历整个棋盘,检查单元格的邻居,并通过检查它的邻居将游戏规则应用于每个单元格。这是相关代码:

    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/

最佳答案

您需要保留旧板并根据规则生成新板(称为生成板)。

然后跳过旧板并使用新板。

只有一 block 板Conway's Game of Life不起作用,因为您在与邻居互动时破坏了棋盘的实际状态。

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.

关于javascript - Conways 生命游戏算法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com