Published
Edited
Dec 17, 2018
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function draw(grid, data){
// Enter rows
const rows = d3.select(grid).selectAll('.row').data(data)
.enter().append('div').classed('row', true);
// Update
rows.each((row, rIdx) => console.log(`Update row ${rIdx}: ${row}`));

// Enter cells
const cells = rows.selectAll('.cell').data((row, r) => data[r])
.enter().append('div').classed('cell', true);
rows.each(function(row, rIdx) {
let cells = d3.select(this).selectAll('.cell');

cells.text((d, i) => gol._checkNeighbors(i, rIdx));
});

// Update
cells.style('background-color', (d, i) => d > 0 ? 'gold' : 'white');
}
Insert cell
Insert cell
Insert cell
class GameOfLife {
constructor(cells){
// Clone the cells
this.cells = cells.concat([]).map(row => row.concat([]));
this.newCells = [];
for (let y = 0; y < this.cells.length; y++) {
this.newCells[y] = [];
for (let x = 0; x < this.cells[y].length; x++) {
this.newCells[y][x] = this.cells[y][x];
}
}
this.WIDTH = this.cells[0].length;
this.HEIGHT = this.cells.length;
this.gen = 1;
}
next() {
this.gen++;
for (let y = 0; y < this.cells.length; y++) {
for (let x = 0; x < this.cells[y].length; x++) {
let numNeighbors = this._checkNeighbors(x, y);
if (this._isAlive(x, y)) {
switch (numNeighbors) {
case 3:
case 2:
this.on(x, y);
break;
default:
this.off(x, y);
}
} else {
switch (numNeighbors) {
case 3:
this.on(x, y);
break;
default:
this.off(x, y);
}
}
}
}
let aux = this.cells;
this.cells = this.newCells;
this.newCells = aux;
}
on(x, y) {
this._set(x, y, 1);
}
off(x, y) {
this._set(x, y, 0);
}
toggle(x, y) {
this._set(x, y, 1 - this._check(x, y));
}
_isAlive(x, y) {
return this._check(x, y) > 0;
}
_isDead(x, y) {
return this._check(x, y) === 0;
}
_check(x, y) {
return this.cells[y][x];
}
_set(x, y, v) {
this.newCells[y][x] = v;
}
_checkNeighbors(x, y) {
let count = 0;
for (let j = y - 1; j <= y + 1; j++) {
for (let i = x - 1; i <= x + 1; i++) {
if (i === x && j === y) continue;
count += this._check((this.WIDTH + i) % this.WIDTH, (this.HEIGHT + j) % this.HEIGHT);
}
}
return count;
}
}
Insert cell
Insert cell
Insert cell
styles = {
const styles = html`<style>
.row {
display: block;
width: auto;
margin: -1px;
padding: 0;
line-height: 1.8em;
}
.row .cell {
display: inline-block;
width: 2em;
height: 2em;
border: 1px solid rgba(0,0,0,.4);
box-sizing: border-box;
margin: -1px;
padding: 0;
text-align: center;
font-family: monospace;
}
</style>`;

const wrapper = DOM.element('div');
wrapper.append(md`### CSS Styles`);
wrapper.append(styles);
return wrapper;
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more