|
| 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