Game of Life
// import {log, toString} from './helpers.mjs';
import {Matrix} from './Matrix.mjs';
/* โญ๏ธ Conway's Game of Life
------------------------
โข n = 3 -> alive
โข n = 2 & alive -> alive
*/
export class GameOfLife {
// init
constructor(cells){
this._matrix = new Matrix(cells);
}
// game.cells
get cells() {
return this._matrix.cells;
}
// game.toString() or `${game}`
toString(){
// const d = ['โช', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ'];
const b = ['โก', 'โ '];
return this._matrix.toString(' ', n => b[n]);
}
// game.nextGen
get nextGen(){
let m = this._matrix.expand();
// 2D array of neighbors count of each cell
let count = m.map((_,i,j) => m.sumOfCellsAround(i,j));
let neighbors = new Matrix(count);
// โข n = 3 -> alive
// โข n = 2 & alive -> alive
let arrAlive = neighbors
.map((n,i,j) => +(n === 3 || (n === 2 && m.cell(i,j))));
let alive = new Matrix(arrAlive).trim();
return new GameOfLife(alive.cells);
}
// return array of self + n generations
generations(n){
let arr = [this];
let parent = this;
for(let i = 0; i < n; i++) {
let child = parent.nextGen;
arr.push(child);
parent = child;
}
return arr;
}
}
Last updated
Was this helpful?