5.6 Artistic Turtles

In the Practice Exercises (see Section 5.4.6) you met the colors() function. Let’s have the Turtle put it to good use.

First of all, we might ask the Turtle to show us a sample of a given color:

turtle_show_color <- function(color) {
  cat("I'm drawing a ", color, " square!", sep = "")
  turtle_init()
  turtle_col(color)
  turtle_lwd(50)
  turtle_do({
    turtle_setpos(x = 30, y = 30)
    turtle_square(40)
  })
}

Note the very thick lines specified above: turtle_lwd(50). Our turtle will draw a square with very thick sides that have the desired color. Let’s ask for burlywood. The resulting color-swatch is shown in Figure 5.14.

turtle_show_color("burlywood")
I'm drawing a burlywood square!

Figure 5.14: I’m drawing a burlywood square!

Feel free to ask for a random color. The result of the call below is shown in Figure 5.15.

turtle_show_color(sample(colors(), size = 1))
I'm drawing a palegreen2 square!

Figure 5.15: I’m drawing a palegreen2 square!

The function below is the Turtle’s attempt to dash off a quick imitation of the work of Jackson Pollack, the great American abstract expressionist:

turtle_quick_pollack <- function(strokes) {
  turtle_init(mode = "clip")
  turtle_lwd(50)
  colorsUsed <- character(strokes)
  turtle_do({
    for ( i in 1:strokes ) {
      randomColor <- sample(colors(), size = 1)
      turtle_col(randomColor)
      colorsUsed[i] <- randomColor
      randomAngle <- runif(1, min = 0, max = 360)
      turtle_left(randomAngle)
      turtle_forward(10)
    }
  })
  cat("Behold my masterpiece!  It was painted with:\n")
  print(colorsUsed)
}

Note that the colors used are output to the console. Let’s have it make a picture with 50 strokes made by random-colored brushes. The resulting painting appears as Figure 5.16

turtle_quick_pollack(50)
Behold my masterpiece!

Figure 5.16: Behold my masterpiece!

## Behold my masterpiece!  It was painted with:
##  [1] "lightskyblue3"   "gray12"          "grey62"          "cyan"           
##  [5] "gray77"          "lightpink3"      "sandybrown"      "gray57"         
##  [9] "darkolivegreen2" "snow3"           "grey43"          "sandybrown"     
## [13] "grey79"          "orangered1"      "blanchedalmond"  "gray95"         
## [17] "mediumpurple2"   "darkgoldenrod4"  "purple"          "dodgerblue2"    
## [21] "grey93"          "violetred"       "steelblue2"      "grey71"         
## [25] "gold4"           "grey64"          "goldenrod2"      "brown3"         
## [29] "orangered2"      "gray"            "gray52"          "darkgoldenrod3" 
## [33] "grey70"          "lightslategrey"  "aquamarine4"     "grey71"         
## [37] "grey5"           "darkslategray"   "gray19"          "ivory1"         
## [41] "deeppink"        "mediumorchid"    "palevioletred1"  "wheat2"         
## [45] "tan"             "springgreen"     "thistle"         "chartreuse3"    
## [49] "grey9"           "royalblue4"