Life loop works in a generator
This commit is contained in:
parent
5e6ffbbb3b
commit
3dca57d2a9
@ -5,9 +5,65 @@
|
||||
const WIDTH = 800;
|
||||
const HEIGHT = 600;
|
||||
|
||||
const CELL = 10;
|
||||
const CELLW = 80;
|
||||
const CELLH = 60;
|
||||
const GEN_TIME = 1000;
|
||||
const INIT_PROB = 0.5
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
|
||||
function neighbours(i, j, id) {
|
||||
const VWRAP = CELLW * (CELLH - 1);
|
||||
const e = i > 0 ? id - 1 : id + CELLW - 1;
|
||||
const w = i < CELLW - 1 ? id + 1 : id - CELLW + 1;
|
||||
const n = [e, id, w].map((v) => j > 0 ? v - CELLW : v + VWRAP);
|
||||
const s = [e, id, w].map((v) => j < CELLH - 1 ? v + CELLW : v - VWRAP);
|
||||
return [...n, e, w, ...s];
|
||||
}
|
||||
|
||||
|
||||
const test_g = (async function* () {
|
||||
const grid = [];
|
||||
|
||||
for( let j = 0; j < CELLH; j++ ) {
|
||||
for ( let i = 0; i < CELLW; i++ ) {
|
||||
const id = j * CELLW + i;
|
||||
const cell = { id: id, x: (i + 0.5) * CELL, y: (j + 0.5) * CELL, live: Math.random() > INIT_PROB };
|
||||
cell["n"] = neighbours(i, j, id);
|
||||
grid.push(cell);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let i = 0;
|
||||
while ( true ) {
|
||||
yield grid.filter((d) => d.live);
|
||||
i++;
|
||||
const ngrid = [];
|
||||
for( const id in grid ) {
|
||||
const live_n = grid[id].n.filter((i) => grid[i].live).length;
|
||||
if( grid[id].live ) {
|
||||
ngrid[id] = ( live_n > 2 && live_n < 4 );
|
||||
} else {
|
||||
ngrid[id] = ( live_n === 3 );
|
||||
}
|
||||
}
|
||||
for( const id in grid ) {
|
||||
grid[id].live = ngrid[id];
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, GEN_TIME));
|
||||
}
|
||||
})();
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
Life
|
||||
|
||||
```js
|
||||
// Set up the svg canvas
|
||||
@ -41,21 +97,21 @@ bg_g.selectAll("rect")
|
||||
.attr("fill", (d) => d.bg)
|
||||
;
|
||||
|
||||
const dots = [ { x:20, y:20}, { x: 120, y:120 } ];
|
||||
|
||||
const dots_g = svg.append("g")
|
||||
.attr("id", "dots")
|
||||
const cells_g = svg.append("g")
|
||||
.attr("id", "cells")
|
||||
.attr("clip-path", "url(#clipRect)");
|
||||
|
||||
dots_g.selectAll("circle")
|
||||
.data(dots)
|
||||
cells_g.selectAll("circle")
|
||||
.data(test_g)
|
||||
.join("circle")
|
||||
.attr("cx", (d) => d.x)
|
||||
.attr("cy", (d) => d.y)
|
||||
.attr("r", (d) => d.live ? CELL * 0.4 : 0)
|
||||
.attr("fill", "blue");
|
||||
|
||||
display(svg.node());
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user