Draw Checkerboard in R

Viewed 406

I am attempting to draw a checkerboard in R by creating a function that will take two parameters (the colors of the checkerboard); using only base R:

checkerboard <- function(color1, color2) {
for (x in 1:8){
  for (y in 1:8){
    plot(0,0, xlim=c(0,8), ylim=c(0,8), axes=F, ylab = "", xlab = "")
      polygon(c(0, 0, 1, 1), c(0, 1, 1, 0), col = 'red')
  }
}

So far, the for loop in the function gives me one square, and I am trying to figure out how to draw the others.

2 Answers

Here's a way to do it with a single loop:

checkers <- function(col1, col2)
{
  plot(0, 0, xlim = c(0, 8), ylim = c(0, 8), col = "white", axes = FALSE)
  x <- sapply(0:63, function(i) {
        polygon(c(0:1, 1:0, 0) + i %% 8 , c(0, 0:1, 1:0) + i %/% 8,
        col = c(col1, col2)[(i + (i %/% 8)) %% 2 + 1])
        })
}

Resulting in:

checkers("gold", "deepskyblue4")

enter image description here

Use x and y to get the corners of the squares.

plot needs to be outside the loop.

To get the colour, check if the evenness of x matches the evenness of y.

checkerboard <- function(color1, color2) {
  plot(0, 0, xlim=c(0,8), ylim=c(0,8), axes=F, ylab = "", xlab = "")

  for (x in 1:8){
    for (y in 1:8){
      polygon(c(x - 1, x - 1, x, x), c(y - 1, y, y, y - 1), col = ifelse(x %% 2 == y %% 2, color1, color2))
    }
  }
}


checkerboard("black", "white")

plot

Related