Created
March 15, 2022 21:02
-
-
Save mikemahoney218/df261f25dccfa7cd66da2846bcac91db to your computer and use it in GitHub Desktop.
Quick code to make turmites in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.cursor <- R6::R6Class( | |
"cursor", | |
list( | |
x = 0, | |
y = 0, | |
direction = 0, | |
left = function() { | |
self$direction <- self$direction + 270 | |
invisible(self) | |
}, | |
right = function() { | |
self$direction <- self$direction + 90 | |
invisible(self) | |
}, | |
none = function() { | |
self$direction <- self$direction | |
invisible(self) | |
}, | |
turn = function() { | |
self$direction <- self$direction + 180 | |
invisible(self) | |
}, | |
advance = function() { | |
switch( | |
sample(1:4, 1), | |
self$left(), | |
self$right(), | |
self$none(), | |
self$turn() | |
) | |
if (self$direction >= 360) self$direction <- self$direction %% 360 | |
if (self$direction == 0) { | |
self$y <- self$y + 1 | |
} else if (self$direction == 90) { | |
self$x <- self$x + 1 | |
} else if (self$direction == 180) { | |
self$y <- self$y - 1 | |
} else { | |
self$x <- self$x - 1 | |
} | |
invisible(self) | |
}, | |
execute = function(n_steps = 1000) { | |
output <- setNames( | |
data.frame(matrix(nrow = n_steps, ncol = 2)), | |
c("x", "y") | |
) | |
for (i in seq_len(n_steps)) { | |
self$advance() | |
output[i, ]$x <- self$x | |
output[i, ]$y <- self$y | |
} | |
output | |
} | |
) | |
) | |
make_turmite <- function(n_steps = 1000, | |
color = sample(grDevices::colors(), 1)) { | |
cursor <- .cursor$new() | |
turmite <- dplyr::mutate( | |
dplyr::count( | |
cursor$execute(n_steps), | |
x, | |
y, | |
name = "z"), | |
z = z %% 2) | |
ggplot2::ggplot(turmite, ggplot2::aes(x, y, fill = factor(z))) + | |
ggplot2::geom_raster() + | |
ggplot2::scale_fill_manual(values = c("white", color)) + | |
ggplot2::theme_void() + | |
ggplot2::theme(legend.position = "none", | |
panel.background = ggplot2::element_rect(fill = "white")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment