Skip to content

Commit f87e6c0

Browse files
committed
Add game of life in JavaScript.
Closes #1377.
1 parent 8ebd795 commit f87e6c0

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
main();
2+
3+
async function main() {
4+
let parameters = {
5+
dimension: 20,
6+
fps: 4,
7+
frameCount: 60,
8+
spawnRate: 0.3,
9+
};
10+
11+
for (let i = 0; i < process.argv.length - 1; i++) {
12+
if (process.argv[i] == "--dimension") parameters.dimension = process.argv[++i];
13+
else if (process.argv[i] == "--fps") parameters.fps = process.argv[++i];
14+
else if (process.argv[i] == "--frameCount") parameters.frameCount = process.argv[++i];
15+
else if (process.argv[i] == "--spawnRate") parameters.spawnRate = process.argv[++i];
16+
}
17+
18+
// Initialize a board as a lifeless square array.
19+
let board = new Array(parameters.dimension).fill(new Array(parameters.dimension).fill(false));
20+
21+
// Load up the array with trues (live) and falses (dead).
22+
board = board.map((row) => row.map(() => Math.random() < parameters.spawnRate));
23+
24+
for (let i = 0; i < parameters.frameCount; i++) {
25+
printBoard(board);
26+
27+
// Mutate the board
28+
board = board.map((row, rowIndex) =>
29+
row.map((cell, colIndex) => {
30+
prevRowIndex = rowIndex - 1 < 0 ? parameters.dimension - 1 : rowIndex - 1;
31+
nextRowIndex = rowIndex + 1 > parameters.dimension - 1 ? 0 : rowIndex + 1;
32+
prevColIndex = colIndex - 1 < 0 ? parameters.dimension - 1 : colIndex - 1;
33+
nextColIndex = colIndex + 1 > parameters.dimension - 1 ? 0 : colIndex + 1;
34+
35+
// Get the count of neighbors that are alive
36+
neighbors = [
37+
[prevRowIndex, prevColIndex],
38+
[prevRowIndex, colIndex],
39+
[prevRowIndex, nextColIndex],
40+
[rowIndex, prevColIndex],
41+
[rowIndex, nextColIndex],
42+
[nextRowIndex, prevColIndex],
43+
[nextRowIndex, colIndex],
44+
[nextRowIndex, nextColIndex],
45+
].reduce((sum, indices) => sum + (board[indices[0]][indices[1]] ? 1 : 0), 0);
46+
47+
// Mutate the current cell
48+
if (cell && (neighbors < 2 || neighbors > 3)) return false;
49+
if (!cell && neighbors == 3) return true;
50+
return cell;
51+
})
52+
);
53+
54+
await sleep((1 / parameters.fps) * 1000);
55+
}
56+
}
57+
58+
function printBoard(board) {
59+
console.clear();
60+
board.forEach((row) => {
61+
console.log(row.reduce((prev, curr) => prev.concat(curr ? "█" : " "), ""));
62+
});
63+
}
64+
65+
function sleep(time) {
66+
return new Promise((resolve) => {
67+
setTimeout(resolve, time);
68+
});
69+
}

0 commit comments

Comments
 (0)