Search code examples
javaapplet

Java applet turtle


So we just got into the Turtle applet and saw this code on the web.

private void tree(int s)
{
   if (s < 8)
      return;

   forward(s);
   left(45);
   tree(s / 2);
   right(90);
   tree(s / 2);
   left(45);
   back(s);
}

This is what the result should look like, but in my mind the turtle stops where my red circle is...

enter image description here

Can anyone explain why the turtle is going further AND why the turtle starts two subtrees ?

Because if I understood the code right the turtle will move forward s steps and then turn left by 45 degrees but not right...


Solution

  • The turtle should end up back where he started. Let's dissect the code line-by-line:

    forward(s);
    

    This draws the vertical trunk of the tree.

    left(45);
    

    We turn to the left so that we're pointing to the upper-left corner.

    tree(s / 2);
    

    We recursively call tree with half the base length, causing a new tree to branch off from our trunk in the direction we specified (45 degrees to the left). Notice that tree will continue to recursively branch out until the base length becomes less than 8 units (pixels?) long. Afterwards, it returns to the place it split from, the base of the branch.

    right(90);
    

    After we finish drawing the left branch, we turn to the right 90 degrees so that we're now pointing to the upper-right corner.

    tree(s / 2);
    

    Like before, we split off and begin drawing a tree in that direction with half the base length.

    left(45);
    

    We turn to the left 45 degrees to reorient ourselves so that we point straight up.

    back(s);
    

    The turtle returns to the base of the tree.


    Altogether, the code branches out left at 45 degree angles with half the base length until the branches become too short; afterward, it then effectively spirals back outward while drawing the remaining branches (left first, then right).