Skip to content

Instantly share code, notes, and snippets.

@viktorbezdek
Last active October 2, 2022 16:54
Show Gist options
  • Save viktorbezdek/fdcec5b5398cf7921cd44aa3373916dc to your computer and use it in GitHub Desktop.
Save viktorbezdek/fdcec5b5398cf7921cd44aa3373916dc to your computer and use it in GitHub Desktop.
Imperative Game of Life
function conwaysGameOfLife(board) {
var newBoard = []
for (var i = 0; i < board.length; i++) {
newBoard.push([])
for (var j = 0; j < board[i].length; j++) {
newBoard[i].push(0)
}
}
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < board[i].length; j++) {
var neighbors = 0
if (i > 0 && j > 0 && board[i - 1][j - 1] === 1) {
neighbors++
}
if (i > 0 && board[i - 1][j] === 1) {
neighbors++
}
if (i > 0 && j < board[i].length - 1 && board[i - 1][j + 1] === 1) {
neighbors++
}
if (j > 0 && board[i][j - 1] === 1) {
neighbors++
}
if (j < board[i].length - 1 && board[i][j + 1] === 1) {
neighbors++
}
if (i < board.length - 1 && j > 0 && board[i + 1][j - 1] === 1) {
neighbors++
}
if (i < board.length - 1 && board[i + 1][j] === 1) {
neighbors++
}
if (
i < board.length - 1 &&
j < board[i].length - 1 &&
board[i + 1][j + 1] === 1
) {
neighbors++
}
// if the cell is alive
if (board[i][j] === 1) {
// if the cell has 2 or 3 neighbors, it lives
if (neighbors === 2 || neighbors === 3) {
newBoard[i][j] = 1
}
} else {
// if the cell is dead
// if the cell has 3 neighbors, it comes alive
if (neighbors === 3) {
newBoard[i][j] = 1
}
}
}
}
return newBoard
}
var board = Array.from({ length: 50 }, () =>
Array.from({ length: 50 }, () => Math.round(Math.random()))
)
;(async () => {
let x = 1000
for (let i = 0; i < x; i++) {
console.clear()
board = conwaysGameOfLife(board)
console.log(board.map((i) => i.join(" ")).join("\n"))
await new Promise((resolve) => setTimeout(resolve, 250))
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment