|
- # Josua Kugler, Christian Merten
-
- library(R6)
-
- compass <- c("N", "E", "S", "W")
- movement <- list(N = c(0, 1), S = c(0, -1), W = c(-1, 0), E = c(1, 0))
-
- # helper because R indexing beginning at 1 is stupid
- get_dir <- function(k) {
- compass[(k-1) %% 4 + 1]
- }
-
- arrow_coords <- function(n, coord) {
- (coord + 0.5) / n
- }
-
- GridPath <- R6Class("GridPath", list(
- path = matrix(c(0,0), nrow=1),
- dir = character(0),
- initialize = function(dir) {
- self$dir <- dir
- },
- move = function(steps) {
- if (steps == 0) return(invisible(self))
- n <- nrow(self$path)
- self$path <- rbind(self$path,
- self$path[n,] + movement[[self$dir]])
- self$move(steps-1)
- },
- rotate_right = function() {
- self$dir <- get_dir(which(self$dir == compass) + 1)
- invisible(self)},
- rotate_left = function() {
- self$dir <- get_dir(which(self$dir == compass) - 1)
- invisible(self)
- },
- print = function() {
- n <- max(self$path)+1
- grid <- matrix(rep(F, n^2), nrow=n)
- apply(self$path, 1, function(r) grid[r[1]+1, r[2]+1] <<- T)
- image(grid, useRaster=T, asp=T, col=c("white", "black"),
- axes=F)
- final <- self$path[nrow(self$path),]
- print(final)
- mv <- movement[[self$dir]]
- coords <- c((final)/(n-1),
- (final + mv) / (n-1))
- arrows(coords[1], coords[2], coords[3], coords[4], col="red")
- }))
-
- gpath3 <- GridPath$new("N")
- gpath3$move(7)$
- rotate_right()$move(8)$
- rotate_right()$move(7)$
- rotate_right()$move(6)$
- rotate_right()$move(5)
-
- gpath3
|