<p>另一种方法是使用已经存在的内容,而不是添加额外的元素。在</p>
<p>我最近用javascript写了一个<em>Life</em>的副本,但是想法是一样的。每个单元由其坐标标识,并用其相邻坐标的对象(Python:dictionary)初始化。在</p>
<pre><code>makeCell(x, y) {
let div = $('<div></div>');
let id = "x" + x + "y" + y;
let neighbors = this.getNeighbors(x, y);
let attributes = {
"id": id,
"data-entity": _entity.id
}
$("#grid").append(div);
}
function getNeighbors(x, y) {
let leftX = x - 1;
let rightX = x + 1;
let topY = y - 1;
let bottomY = y + 1;
// neighbor positions
let neighbors = [
"#x" + leftX + "y" + topY,
"#x" + x + "y" + topY,
"#x" + rightX + "y" + topY,
"#x" + leftX + "y" + y,
"#x" + rightX + "y" + y,
"#x" + leftX + "y" + bottomY,
"#x" + x + "y" + bottomY,
"#x" + rightX + "y" + bottomY,
];
return neighbors;
}
</code></pre>
<p>最后,所有的活细胞都被存储在一个列表中。每一个活细胞和它的每一个邻居都被检查来计算它各自的活邻居细胞。在</p>
^{pr2}$
<p>以及生命的检查条件:</p>
<pre><code>this.setNextLife = function(_count) {
if (this.alive) {
if (_count == 2 || _count == 3) {
return this.age++;
} else {
changes.push(this);
return;
}
} else {
changes.push(this);
}
}
</code></pre>
<p>其中<code>changes</code>是要切换的单元格列表<code>bool</code>活动/死亡。在</p>