Skip to content

Instantly share code, notes, and snippets.

@stepharr
Created June 11, 2026 02:36
Show Gist options
  • Select an option

  • Save stepharr/680266c23985386624c329f05a92c293 to your computer and use it in GitHub Desktop.

Select an option

Save stepharr/680266c23985386624c329f05a92c293 to your computer and use it in GitHub Desktop.
Conway's Game of Life
// Conway's Game of Life — runs in your terminal with: node game-of-life.js
const WIDTH = 40;
const HEIGHT = 20;
const FPS = 8;
// Create a random starting grid (each cell ~30% chance of being alive)
function randomGrid() {
return Array.from({ length: HEIGHT }, () =>
Array.from({ length: WIDTH }, () => (Math.random() < 0.3 ? 1 : 0))
);
}
// Count the live neighbors around a cell (wraps around the edges)
function neighbors(grid, x, y) {
let count = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) continue;
const nx = (x + dx + WIDTH) % WIDTH;
const ny = (y + dy + HEIGHT) % HEIGHT;
count += grid[ny][nx];
}
}
return count;
}
// Apply the rules: live cells survive with 2-3 neighbors, dead cells revive with 3
function step(grid) {
return grid.map((row, y) =>
row.map((cell, x) => {
const n = neighbors(grid, x, y);
return cell ? (n === 2 || n === 3 ? 1 : 0) : n === 3 ? 1 : 0;
})
);
}
// Draw the grid to the terminal
function render(grid, generation) {
console.clear();
console.log(`Conway's Game of Life — generation ${generation}`);
console.log(grid.map((row) => row.map((c) => (c ? "█" : " ")).join("")).join("\n"));
console.log("(Ctrl+C to quit)");
}
let grid = randomGrid();
let generation = 0;
setInterval(() => {
render(grid, generation++);
grid = step(grid);
}, 1000 / FPS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment