Skip to content

Instantly share code, notes, and snippets.

@sarahmeyer
Last active August 14, 2018 22:17
Show Gist options
  • Save sarahmeyer/e80de1e7caeb7060afdc5a123cf4f27b to your computer and use it in GitHub Desktop.
Save sarahmeyer/e80de1e7caeb7060afdc5a123cf4f27b to your computer and use it in GitHub Desktop.
class Cell {
constructor(alive) {
this.alive = alive;
}
toggle() {
this.alive = !this.alive;
}
copy() {
return new Cell(this.alive);
}
}
class Universe {
constructor(width, height) {
this.width = width;
this.height = height;
this.cells = _.range(width * height).map((i) => {
return (i % 2 === 0 || i % 7 === 0)
? new Cell(true)
: new Cell(false);
});
}
index(row, col) {
return (row * this.height + col);
}
liveNeighborCount(row, col) {
let count = 0;
const rowDeltas = [
this.height - 1, 0, 1,
];
const colDeltas = [
this.width - 1, 0, 1,
];
for (rowDelta in rowDeltas) {
for (colDelta in colDeltas) {
if (rowDelta === 0 && colDelta === 0) {
continue;
}
const neighborRow = (row + rowDelta) % this.height();
const neighborCol = (col + colDelta) % this.width();
const index = this.index(neighborRow, neightborCol);
// cast as bool by adding
count += this.cells()[index];
}
}
return count;
}
tick() {
const nextCells = this.cells.map((cell) => cell.copy())
for (let row = 0; row < self.height; row ++) {
for (let col = 0; col < self.width; col++) {
const index = this.index(row, col);
const cell = this.cells[index];
const neighborCount = this.liveNeighborCount(row, col);
let nextLife = cell.alive;
if (cell.alive) {
if (neighborCount < 2) {
nextLife = false;
} else if (neighborCount > 3) {
nextLife = false;
}
} else {
if (neighborCount === 3) {
nextLife = true;
}
}
nextCells[index] = new Cell(nextLife);
}
}
this.cells = nextCells;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment