Skip to content

Instantly share code, notes, and snippets.

@raed667
Last active April 12, 2020 10:56
Show Gist options
  • Save raed667/e4d5eed8f1d7e0b90f407bdef710c871 to your computer and use it in GitHub Desktop.
Save raed667/e4d5eed8f1d7e0b90f407bdef710c871 to your computer and use it in GitHub Desktop.
Very basic JS implementation of Conway's Game of Life
let Matrix = [];
const fillMatrix = (m, size) => {
for (let index = 0; index < size; index++) {
m[index] = Array(size).fill(false);
}
};
const getCellSafe = (i, j) => {
if (Matrix[i] && Matrix[i][j]) return Matrix[i][j];
};
const getAliveNeigboursCount = (i, j) => {
let count = 0;
[i - 1, i, i + 1].forEach((it) => {
count += getCellSafe(it, j - 1) === true ? 1 : 0;
if (it !== i) count += getCellSafe(it, j) === true ? 1 : 0;
count += getCellSafe(it, j + 1) === true ? 1 : 0;
});
return count;
};
const setPattern = (inputArray) =>
inputArray.forEach((input) => (Matrix[input[0]][input[1]] = true));
const tick = (Matrix) => {
const MatrixP = [];
fillMatrix(MatrixP, Matrix.length);
for (let i = 0; i < Matrix.length; i++) {
for (let j = 0; j < Matrix[i].length; j++) {
const count = getAliveNeigboursCount(i, j);
if (
(Matrix[i][j] === true && (count === 2 || count === 3)) ||
(Matrix[i][j] === false && count === 3)
) {
MatrixP[i][j] = true;
} else {
MatrixP[i][j] = false;
}
}
}
return MatrixP;
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const printRow = (row) => {
let output = "";
for (let index = 0; index < row.length; index++) {
switch (row[index]) {
case true:
output += " ▓ ";
break;
case false:
default:
output += " ░ ";
break;
}
}
return output;
};
const printMatrix = (m) => m.forEach((row) => console.log(printRow(row)));
// MAIN
const init = async () => {
const size = 10;
fillMatrix(Matrix, size);
setPattern([
// Blinker
[1, 1],
[1, 2],
[1, 3],
// Toad
[5, 3],
[5, 4],
[5, 5],
[6, 2],
[6, 3],
[6, 4],
]);
while (true) {
console.clear();
printMatrix(Matrix);
Matrix = tick(Matrix);
await sleep(1000);
}
};
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment