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