Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@good-idea
Last active January 7, 2020 22:19
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 good-idea/2648bcba48d3dd26c686f7c54f8391a6 to your computer and use it in GitHub Desktop.
Save good-idea/2648bcba48d3dd26c686f7c54f8391a6 to your computer and use it in GitHub Desktop.
Game of Life in javascript
const SIZE = 24;
const generateBoard = () => {
return Array.from({ length: SIZE }, () => {
// return a row
return Array.from({ length: SIZE }, () => Math.round(Math.random()));
});
};
const printBoard = board => {
console.clear();
const lines = board
.map(row =>
row
.join("")
.replace(/0/g, "🌑 ")
.replace(/1/g, "🦠 ")
)
.join("\n");
console.log(lines);
};
const getCell = (rowIndex, cellIndex, board) => {
if (!board[rowIndex]) return 0;
if (!board[rowIndex][cellIndex]) return 0;
return board[rowIndex][cellIndex];
};
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let rounds = 0;
const play = async board => {
rounds += 1;
printBoard(board);
const nextBoard = board.map((row, rowIndex) => {
return row.map((cell, cellIndex) => {
const neighbors = [
// up
getCell(rowIndex - 1, cellIndex, board),
//top left
getCell(rowIndex - 1, cellIndex - 1, board),
// left
getCell(rowIndex, cellIndex - 1, board),
//bottom left
getCell(rowIndex + 1, cellIndex - 1, board),
// bottom
getCell(rowIndex + 1, cellIndex, board),
//bottom right
getCell(rowIndex + 1, cellIndex + 1, board),
// right
getCell(rowIndex, cellIndex + 1, board),
//top right
getCell(rowIndex - 1, cellIndex + 1, board)
];
const count = neighbors.reduce((acc, n) => acc + n, 0);
if (count === 0) {
return 0;
} else if (count === 1) {
return 0;
} else if (count === 2) {
return cell;
} else if (count === 3) {
return 1;
} else {
return 0;
}
});
});
// END on:
// all the same as the last time
// all 0s
if (JSON.stringify(board) === JSON.stringify(nextBoard)) {
console.log("");
console.log("done!");
console.log(rounds + " rounds");
} else {
await sleep(300);
play(nextBoard);
}
};
const initialBoard = generateBoard();
play(initialBoard);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment