Skip to content

Instantly share code, notes, and snippets.

@mrjazz
Created August 9, 2022 19:56
Show Gist options
  • Save mrjazz/3edc212660ade04504ab54e2c8cb1c80 to your computer and use it in GitHub Desktop.
Save mrjazz/3edc212660ade04504ab54e2c8cb1c80 to your computer and use it in GitHub Desktop.
const process = require("process")
function draw(arr) {
process.stdout.write('\u001b[0;0H')
for (let row of arr) {
for (let i of row) {
process.stdout.write(i == 1 ? "\u2588" : ' ')
}
process.stdout.write("\n")
}
}
function cell(state, coordX, coordY) {
const x = parseInt(coordX, 10);
const y = parseInt(coordY, 10);
const n = neighbours(state, x, y);
const isAlive = state[y][x] == 1;
if (isAlive && n < 2) {
// Any live cell with fewer than two live neighbours dies, as if by underpopulation.
return 0;
} else if (isAlive && n > 3) {
// Any live cell with more than three live neighbours dies, as if by overpopulation.
return 0;
} else if (!isAlive && n == 3) {
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
return 1;
}
return state[y][x];
}
function evaluate(state) {
const result = [];
for (let y in state) {
const row = [];
for (let x in state[y]) {
row.push(cell(state, x, y))
}
result.push(row);
}
return result;
}
const get = (state, x, y) => {
let yy = y % state.length;
yy = yy < 0 ? state.length + yy : yy;
let xx = x % state[yy].length;
xx = xx < 0 ? state[yy].length + xx : xx;
return state[yy][xx];
}
function neighbours(state, x, y) {
return (
get(state, x + 1, y) +
get(state, x - 1, y) +
get(state, x, y + 1) +
get(state, x, y - 1) +
get(state, x + 1, y + 1) +
get(state, x - 1, y - 1) +
get(state, x - 1, y + 1) +
get(state, x + 1, y - 1)
);
}
function life(state, iterations) {
let timer = setInterval(() => {
if (iterations-- <= 0) {
clearInterval(timer);
}
state = evaluate(state);
draw(state)
}, 100)
}
const state = [
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
// draw(state);
life(state, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment