5.3 Writing Turtle Functions

Once you have designed some shapes that you think you might want to draw again, you should write them up as functions. Here for example, is the code for a function that makes squares:

turtle_square <- function(side) { 
  turtle_do({
    for (i in 1:4) {
      turtle_forward(side)
      turtle_right(90)
    }
  })
}

Note that the user can vary the length of a side. You would use it like this:

turtle_init(mode = "clip")
turtle_square(side = 30)

5.3.1 Practice Exercises

  1. Write a function called star8() that makes an eight-sided star with rays of length 20 each. The user should be able to specify the thickness of the rays (think turtle_lwd()). The body of the function should begin with turtle_init() so that the star is always drawn inside a new field. The function should take a single parameter called width, the desired thickness of the rays. Typical examples of use should be as follows:

    star8(width = 2)

    star8(width = 10)

  2. Modify your star8() function to make a new function called superstar8() that takes an additional parameter called color that allows the user to specify the color of the rays. The default value of color should be "burlywood". Typical examples of use should be as follows:

    superstar8(width = 5)

    superstar8(width = 15, color = "lavenderblush4")

5.3.2 Solutions to the Practice Exercises

  1. From the Practice Exercises of the previous section we are already familiar with making 8-ray stars; we just need to encapsulate the process into a function. Here’s the code:

    star8 <- function(width) {
      turtle_init(mode = "clip")
      turtle_lwd(lwd = width)
      turtle_do({
      for ( i in 1:8 ) {
        turtle_forward(20)
        turtle_backward(20)
        turtle_turn(45)
      }
      })
    }
  2. Try this:

    superstar8 <- function(width, color = "burlywood") {
      turtle_init(mode = "clip")
      turtle_lwd(lwd = width)
      turtle_col(col = color)
      turtle_do({
      for ( i in 1:8 ) {
        turtle_forward(20)
        turtle_backward(20)
        turtle_turn(45)
      }
      })
    }