Skip to content

Instantly share code, notes, and snippets.

@viktorbezdek
Created July 14, 2023 10:00
Show Gist options
  • Save viktorbezdek/b14294e84e69398cb8432ea0c176b55c to your computer and use it in GitHub Desktop.
Save viktorbezdek/b14294e84e69398cb8432ea0c176b55c to your computer and use it in GitHub Desktop.
Functional TypeScript Conway's Game of Life
// Conway's Game of Life in functional TypeScript
// Game board size
const ROWS = 10;
const COLS = 10;
// Game board represented as 2D array
type Board = boolean[][];
// Create empty board
const createEmptyBoard = (): Board => {
return Array.from({length: ROWS}, () =>
Array(COLS).fill(false)
);
}
// Print board to console
const printBoard = (board: Board) => {
console.clear();
console.log(board.map(row => row.join(' ')).join('\n'));
}
// Get number of living neighbors for cell at [r, c]
const getLivingNeighbors = (board: Board, r: number, c: number): number => {
let count = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) {
continue;
}
const x = r + i;
const y = c + j;
if (x >= 0 && x < ROWS && y >= 0 && y < COLS) {
if (board[x][y]) {
count++;
}
}
}
}
return count;
}
// Update game board to next generation
const nextGeneration = (board: Board): Board => {
const newBoard = board.map(row => [...row]);
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const neighbors = getLivingNeighbors(board, r, c);
if (board[r][c]) {
// Cell is alive
if (neighbors < 2 || neighbors > 3) {
newBoard[r][c] = false;
}
} else {
// Cell is dead
if (neighbors === 3) {
newBoard[r][c] = true;
}
}
}
}
return newBoard;
}
// Game loop
const gameLoop = (board: Board) => {
printBoard(board);
// Exit game loop after 50 generations
for (let i = 0; i < 50; i++) {
board = nextGeneration(board);
printBoard(board);
// Delay between generations
setTimeout(() => {}, 200);
}
}
// Create and run game
const board = createEmptyBoard();
gameLoop(board);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment