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:
<- function(side) {
turtle_square 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
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 (thinkturtle_lwd()
). The body of the function should begin withturtle_init()
so that the star is always drawn inside a new field. The function should take a single parameter calledwidth
, the desired thickness of the rays. Typical examples of use should be as follows:star8(width = 2)
star8(width = 10)
Modify your
star8()
function to make a new function calledsuperstar8()
that takes an additional parameter calledcolor
that allows the user to specify the color of the rays. The default value ofcolor
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
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:
<- function(width) { star8 turtle_init(mode = "clip") turtle_lwd(lwd = width) turtle_do({ for ( i in 1:8 ) { turtle_forward(20) turtle_backward(20) turtle_turn(45) } }) }
Try this:
<- function(width, color = "burlywood") { superstar8 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) } }) }