【问题标题】:Cellular automata implemented in JavaScript and HTML5 Canvas用 JavaScript 和 HTML5 Canvas 实现的元胞自动机
【发布时间】:2012-01-24 16:38:11
【问题描述】:

我在 JavaScript 中实现了 Conway 的生命游戏,但我没有看到与 Gosper 的 Glider Gun 相同的模式。我按照 Wikipedia 文章中描述的方式为网格播种,但枪从未发生过。

有人会查看我的代码,看看它是否有什么问题,对实现有什么建议吗?

https://github.com/DiegoSalazar/ConwaysGameOfLife

【问题讨论】:

  • 一些通用的建议是使用===,事实上x ? true : false可以是!!x。除此之外,我不认为这是一个非常具体的问题。
  • 我在想可能是一些小的差异(测试相等性,或减 1 或其他东西)可能会影响算法的行为。我会尝试使用===,您在哪里看到我应该专门使用它?
  • 一般来说,=== 应该和== 一起使用,如果真的需要的话。只是更强大的编码风格的问题;它可能不会明确修复错误。
  • 代码应以minimal sample 的形式呈现(完整、简洁且具有代表性)。如果您必须链接到其他地方,请链接到实时页面。两者都减少了检查和运行代码的障碍。

标签: javascript html5-canvas cellular-automata


【解决方案1】:

您不是同时更新所有单元格,而是按顺序更新。在第一代出生的细胞不会在第一代其他细胞的计算中显得活着(它仍然算作死亡)。

创建一个名为 willBeAlive 的新属性,并使用它来保存单元格的新计算活动状态。完成该代的所有计算后,将每个单元格的 alive 属性设置为其 willBeAlive 属性并重绘。

以下是更改:

Automaton.prototype.update = function() {
  for (var x = 0; x < this.w; x++) {
    for (var y = 0; y < this.h; y++) {
      this.grid[x][y].killYourselfMaybe();
    }
  }
  // set the alive property to willBeAlive
  for (var x = 0; x < this.w; x++) {
    for (var y = 0; y < this.h; y++) {
            this.grid[x][y].alive = this.grid[x][y].willBeAlive;
        }
    }  
}


Cell.prototype.killYourselfMaybe = function(grid) {
  var num = this.numLiveNeighbors();

  this.willBeAlive = false;

  if (this.alive) {
    // 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
    if (num < 2) this.willBeAlive = false;
    // 2. Any live cell with two or three live neighbours lives on to the next generation.
    if (num == 2 || num == 3) { this.willBeAlive = true}
    // 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
    if (num > 3) this.willBeAlive = false;
  } else {
    // 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
    if (num == 3) this.willBeAlive = true;
  }
}

这是“Gosper's Glider Gun”的种子数组:

[[2,6],[2,7],[3,6],[3,7],[12,6],[12,7],[12,8],[13,5],[13,9],[14,4],[14,10],[15,4],[15,10],[16,7],[17,5],[17,9],[18,6],[18,7],[18,8],[19,7],[22,4],[22,5],[22,6],[23,4],[23,5],[23,6],[24,3],[24,7],[26,2],[26,3],[26,7],[26,8],[36,4],[36,5],[37,4],[37,5]]

【讨论】:

  • 太棒了,当我意识到问题时,我收到了一封来自 Stackoverflow 的电子邮件,其中包含您的正确解决方案!大声笑,我很高兴我发现了它并且你验证了它。感谢 Gosper 种子阵列!如果您想查看并发表评论,我将我的更改上传到github.com/DiegoSalazar/ConwaysGameOfLife。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2011-07-08
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多