Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active June 25, 2024 08:04
Show Gist options
  • Save matt-dray/8cbf2f8cd0f52d63f56c23df7a3922aa to your computer and use it in GitHub Desktop.
Save matt-dray/8cbf2f8cd0f52d63f56c23df7a3922aa to your computer and use it in GitHub Desktop.
Messing about with kenney.nl sprites on a grid with {nara}
# {nara} by Mike Cheng: https://coolbutuseless.github.io/package/nara/index.html
# Kenney by Kenney: https://www.kenney.nl
# Read png tiles
tile_paths <- list.files(
"~/Desktop/kenney/kenney_tiny-dungeon/Tiles",
pattern = ".png$",
full.names = TRUE,
recursive = TRUE
)
tile_names <- stringr::str_remove(basename(tile_paths), ".png")
tile_paths <- tile_paths |> purrr::set_names(tile_names)
tile_to_nr <- function(path) {
png::readPNG(path, native = TRUE)
}
tiles_nr <- purrr::map(tile_paths, tile_to_nr) |>
purrr::set_names(tile_names)
# selected tiles
tiles <- list(
ground1 = tiles_nr$tile_0048,
ground2 = tiles_nr$tile_0049,
guy = tiles_nr$tile_0085
)
# get tile dimensions (assume same size)
tile_dim <- dim(tiles[[1]])
tile_pixels_x <- tile_dim[2]
# square canvas, dims based on tile size
n_tiles_x <- 3
x_pixels <- tile_pixels_x * n_tiles_x
x_seq <- seq(0, x_pixels - tile_pixels_x, tile_pixels_x)
# place tiles
nr <- nara::nr_new(x_pixels, x_pixels, "black")
for (x in x_seq) {
for (y in x_seq) {
sampled_tile <- sample(names(tiles)[1:2], 1)
nara::nr_blit(nr, x, y, tiles[[sampled_tile]])
}
}
nara::nr_blit(nr, sample(x_seq, 1), sample(x_seq, 1), tiles$guy)
# draw
grid::grid.newpage()
grid::grid.raster(nr, interpolate = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment