Did you finish Homework 5? This article shows how someone may draw Trees and Branches using Turtle Graphics and recursive functions in R.
Trees and branches
Trees are a common recursive structure found in
nature. Each branch is like a small tree. More precisely, a tree with
n
levels has branches with n-1
levels. Your
task is to make a function to draw trees with three
branches.
The function should be named tree()
with three inputs:
the number of levels n
, the length of the trunk
length
, and the angle between the branches
angle
.
So the idea is something like this:
<- function(n, length, angle) {
tree
trunk
branch
branch
branch }
Each branch is a tree with n-1
levels and with
length equal to 0.8 times the length of the previous level. The first
branch of every tree is angle
degrees to the left of the
trunk; the second is aligned with the trunk, and the last one is
angle
degrees to the right of the trunk.
Now we know how to draw each branch:
<- function(n, length, angle) {
tree turtle_forward(length)
turtle_left(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
}
The most important issue is that the
tree()
functions must leave the turtle in
the same position and the same angle
as before. Your function can move the turtle as you wish, but it must
leave the turtle as it was at the beginning of the function. The
functions turtle_getpos()
, turtle_getangle()
,
turtle_setpos()
, and turtle_setangle()
can be
useful for this.
What is the exit condition?
Please complete the function.
We add turtle_getpos()
, turtle_getangle()
,
turtle_setpos()
, and turtle_setangle()
as
indicated:
<- function(n, length, angle) {
tree <- turtle_getpos()
old_pos <- turtle_getangle()
old_angle turtle_forward(length)
turtle_left(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_setangle(old_angle)
turtle_setpos(old_pos[1], old_pos[2])
}
But there is something missing: an exit condition.
The question says that it is recursive. So we will have a function calling itself, and an exit condition.