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