We will now draw trees. For that, we will write a method using double recursion following this prototype
[!java|c]void [/!]tree([!java|c]int [/!]steps[!scala]:Int[/!], [!java|c]double [/!]length[!scala]:Double[/!], [!java|c]double [/!]angle[!scala]:Double[/!], [!java|c]double [/!]shrink[!scala]:Double[/!])
To draw a tree of four levels, you have to draw a trunk of the given length, turn right of the given angle, draw a tree of level 3, turn left twice of the given angle, draw another tree of level 3, and come back to your initial location. Don't forget to come back to the initial location!
If a tree's trunk is of length 'len', the trunk of the next level tree will be of length 'len*shrink'.
At the end, here is the pseudo-code of the general case (you should add the base case yourself):
Move forward of the desired length Draw (recursively) the right subtree Draw (recursively) the left subtree Move back to your initial position
Don't forget to add the base case to your code, or your buggle will enter an infinite loop. Then, drawing the right subtree comes down to turn right and then draw the subtree.
As you can see, each recursion level is represented by a distinctive color. For that, you have to call the
current(step)
, passing the current recursion level as a parameter. This will pick the right color for you.
Don't erase your great colors when you move back to your initial location.
If you get your function wrong, this can easily become hairly to debug as your
errors will appear at each level of the recursion, completely changing the drawing.
For debugging purpose, you can use the subtree()
that will draw a correct
subtree. This function is then very similar to the one you are trying to write. The only difference
is that subtree()
only draws in black. So, you can use it instead of a recursive call
to debug your code, but you have to change for a proper recursive call to your own code (once it works)
to get the colors right, and pass the exercise.