Skip to content

Instantly share code, notes, and snippets.

@mattcodez
Created March 16, 2018 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattcodez/bc3e4ee4a4bdcec750cb58df5980e3df to your computer and use it in GitHub Desktop.
Save mattcodez/bc3e4ee4a4bdcec750cb58df5980e3df to your computer and use it in GitHub Desktop.
/* GAME OF LIFE
1. Any live cell with fewer than two live neighbours dies.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies.
4. Any dead cell with exactly three live neighbours becomes a live cell.
*/
const blinkerSeed = {
height: 5,
coords: [[2,1], [2,2], [2,3]]
};
function buildGameBoard(height){
const gameBoard = [];
//build board
for (let i = 0; i < height; i++){
gameBoard.push((new Array(height)).fill(0));
}
return gameBoard;
}
let currentBoard = buildGameBoard(blinkerSeed.height);
// fill board
for (let i = 0; i < blinkerSeed.coords.length; i++){
const cell = blinkerSeed.coords[i];
currentBoard[cell[1]][cell[0]] = 1;
}
//console.log(currentBoard);
const update = () => {
const newBoard = buildGameBoard(blinkerSeed.height);
const gameBoard = currentBoard;
//console.log(newBoard)
const setBoard = (row, col, val) => {
//console.log(`${row},${col}`,newBoard);
// console.log(`${row},${col}`, newBoard[row,col])
newBoard[row][col] = val;
};
for (let i = 0; i < gameBoard.length; i++){
for (let j = 0; j < gameBoard[i].length; j++){
let neighbors = 0;
// get neighborcount
// top row
if ((gameBoard[i - 1]||[])[j - 1]) neighbors++;
if ((gameBoard[i - 1]||[])[j ]) neighbors++;
if ((gameBoard[i - 1]||[])[j + 1]) neighbors++;
// middle row
if ((gameBoard[i ]||[])[j - 1]) neighbors++;
if ((gameBoard[i ]||[])[j + 1]) neighbors++;
// bottom row
if ((gameBoard[i + 1]||[])[j - 1]) neighbors++;
if ((gameBoard[i + 1]||[])[j ]) neighbors++;
if ((gameBoard[i + 1]||[])[j + 1]) neighbors++;
const cell = gameBoard[i][j]; //console.log(neighbors)
if (cell && neighbors < 2) setBoard(i,j,0);
else if (cell && (neighbors == 2 || neighbors == 3)) setBoard(i,j,1);
else if (cell && neighbors > 3) setBoard(i,j,0);
else if (!cell && neighbors == 3) setBoard(i,j,1);
else setBoard(i,j,0);
}
}
console.log(newBoard);
currentBoard = newBoard;
};
setInterval(()=>{
update()
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment