Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# mpjdem/game_of_life.R

Last active Jan 7, 2020
Conway's game of life in R, visualised in the terminal
 library(data.table) library(keypress) ## Create the universe. Well, sort of. dims <- c(49, 49) universe <- CJ(x = seq(dims), y = seq(dims), k = 1, cell = FALSE) universe[, cell := sample(c(FALSE, TRUE), prod(dims), TRUE)] ## Neighbourhood to consider for each cell neighbours <- CJ(xd = -1:1, yd = -1:1, k = 1)[xd != 0 | yd != 0] ## Function to advance the Game of Life one tick gol_tick <- function(xy, sz, nb) { nb[xy, on = .(k), allow.cartesian = TRUE ][, nbx := x + xd][, nby := y + yd ][nbx >= 1 & nbx <= sz & nby >= 1 & nby <= sz ][xy, on = .(nbx = x, nby = y) ][, .(nnb = sum(i.cell)), by = .(x, y, cell, k) ][!cell & nnb == 3, cell := TRUE ][cell & (nnb < 2 | nnb > 3), cell := FALSE ][, nnb := NULL] } ## Run & visualise the game cat("\033[?25l") repeat ({ kp <- keypress(FALSE) universe[order(y, x) ][, cat(fifelse(.SD\$cell, "\033[32;40m◼", "\033[90;40m◌"), "\033[K\n"), by = y] cat("\033[2K\033[33;40m", sum(universe\$cell), "\n") if (kp == "q") break if (kp == "x") { new_cells <- sample(c(FALSE, TRUE), prod(dims), TRUE, c(9, 1)) universe[, cell := cell | new_cells] } Sys.sleep(0.2) cat(paste0("\033[", dims + 1, "A")) universe <- gol_tick(universe, dims, neighbours) }) cat("\033[?25h")
to join this conversation on GitHub. Already have an account? Sign in to comment