repl.it
@akash_joshi/

game-life

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const giveStart = (rows, cols) => new Array(rows).fill(0).map(() => new Array(cols).fill(0).map(() => Math.floor(Math.random() * 2)));

const countNeighbors = (myArray, x, y) => {
  let count = 0;
  if (myArray[x - 1] && myArray[x - 1][y]) count++;
  if (myArray[x - 1] && myArray[x - 1][y+1]) count++;
  if (myArray[x - 1] && myArray[x - 1][y-1]) count++;
  if (myArray[x + 1] && myArray[x + 1][y]) count++;
  if (myArray[x + 1] && myArray[x + 1][y+1]) count++;
  if (myArray[x + 1] && myArray[x + 1][y-1]) count++;
  if (myArray[x][y + 1]) count++;
  if (myArray[x][y - 1]) count++;
  return count;
};

const initArray = giveStart(15, 15);

const nextState = prevState => prevState.map((row, x) => row.map((el, y) => {
  const count = countNeighbors(prevState, x, y);
  if (count > 3 || count < 2) return 0;
  if(count == 3 && !el) return 1;
  if((count == 2 || count == 3) && el) return 1;
  return el;}));

let mutableState = initArray;

setInterval(() => {
  console.clear();
  console.table(mutableState);
  mutableState = nextState(mutableState);
}, 500);