# Extending the turtle's commands

Armed with this little bit of information about the inner workings of the turtle, how might we exploit it? We can extend the turtle language. You may recall that the way we made the Sierpinski gasket in §7 did not correspond exactly to our initial description, but relied on finding a fractal curve that traced out most of the gasket. We'll now describe another method, which will be closer to our original description.

Recall that the gasket consists of three copies of itself, two along the base, and one at the top. Consequently, we can construct an approximate gasket out of three copies of the approximate gasket . The first approximation is just an equilateral triangle.

First, lets write a procedure EqTriangle, which causes the turtle to trace out an equilateral triangle with a horizontal base.

>
EqTriangle := proc()
PushState();
PenDown();
SetTurtleAngle(120);

Forward();
Left();
Forward();
Left();
Forward();

PopState();
end:


The middle of this procedure is obvious: we send the turtle along the path FLFLF. But before that, we save its current state with PushState, then make sure that the heading and angle are correct for the triangle (since perhaps they were different), and ensure that the pen is down. After we are finished with the triangle, we put the turtle back the way it was with PopState. Note that we have taken care to ensure that the triangle always has the same orientation, no matter what direction the turtle is heading. The procedure also leaves the position and heading of the turtle unchanged.

Now, we will plug in an additional procedure to handle the new turtle command T, which draws a triangle. This is done by replacing DoUserCommand with our own version. This procedure is expected to return true if it recognized and handled the character, and false if not.

>
DoUserCommand:=proc(c)
if (c=T) then
EqTriangle();
else
RETURN(false);
fi;
true;
end:


With this new command in hand, we can produce a new set of commands to produce a Sierpinski gasket, closer to our original description. Assuming that the angle is 60and the scaling factor is .5, then

Sn = .

In words, this means to make Sn, we include a half-size Sn - 1, advance forward along its base and put in another copy. The we back up to the starting point, go up the left side, put in the third copy, and return. It is important to take care that the turtle is pointing in the proper direction when we finish.

Here is the corresponding maple procedure:

>
Sierp2 := proc(n::nonnegint)
if (n=0) then
T;
else
cat(S, Sierp2(n-1), F, Sierp(n-1),
BLFR, Sierp2(n-1), LBRG);
fi;
end: