Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

PA 4 part 1: Turtle Graphics and L-Systems 🐢

1. Turtle Graphics¶

In turtle graphics, we draw by giving directions to a turtle that walks around the window. The turtle maintains two pieces of information: where it is located in terms of (x, y) coordinates, and which direction it’s facing in terms of an angle in degrees. As it walks forward, it leaves a line behind it.[1]

We give the turtle its directions as a string, where each character is one command. Our turtle understands five commands:

CommandWhat the turtle does
FMoves forward by one step, drawing a line segment
+Turns left (counterclockwise) by a fixed angle
-Turns right (clockwise) by a fixed angle
[Saves its current position and direction
]Returns to the most recently saved position and direction

Any other character is ignored by the turtle. This comes into play when we get to writing more sophisticated L-system strings later on in the assignment.

For example, suppose the turtle turns left by 90 degrees on each +. Then the command string F+F+F+F tells the turtle to move forward, turn left, move forward, turn left, and so on. After the fourth F, the turtle is back where it started, and it has drawn a square:

We’ll build the turtle out of three classes. Two of them are provided for you, so let’s examine them in more detail first.

LineSegment.java¶

A LineSegment object represents one line the turtle has drawn, from a start point (x1, y1) to an end point (x2, y2). Here is its constructor, which is provided for you in the starter file:

public LineSegment(float x1, float y1, float x2, float y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

The class also provides a getter for each of the four values: getX1(), getY1(), getX2(), and getY2().

TurtleState.java¶

A TurtleState object is a snapshot of the turtle at one moment. It holds three values:

  • x and y, both float values: the turtle’s position.

  • heading, a float: the direction the turtle is facing, in degrees.

A heading of 0 means the turtle is facing right, and the heading increases as the turtle turns left (counterclockwise). So a heading of 90 faces up, 180 faces left, and 270 faces down.

Here is the turtle turning left 15 degrees at a time, with the corresponding heading in degrees:

Like LineSegment, the TurtleState constructor is provided for you in the starter file, along with the getters getX(), getY(), and getHeading():

public TurtleState(float x, float y, float heading) {
    this.x = x;
    this.y = y;
    this.heading = heading;
}

Remember that in Processing, coordinates are measured from the top-left corner of the window. The x coordinate increases to the right, and the y coordinate increases downward. So a turtle at y = 100 is near the top of a 300 pixel tall window, not near the bottom.

2. Turtle.java¶

Now, we’ll use LineSegment and TurtleState as building blocks for the Turtle class. Each time the turtle moves forward, it adds a LineSegment to its segments list, which will then be read by a Processing application to be drawn. This will allow us to test the turtle using our usual testCode() approach without having to open a Processing window.

[Task] Turtle constructor¶

We begin with the data a turtle holds. Open Turtle.java, where the instance variables are already declared:

  • x and y, both float values: the turtle’s current position.

  • heading, a float: the direction the turtle is currently facing, in degrees.

  • stepLength, a float: how far the turtle moves on each F, in pixels.

  • turnAngle, a float: how many degrees the turtle turns on each + or -.

  • segments, a List<LineSegment>: every line segment the turtle has drawn so far.

  • savedStates, an MHCStack<TurtleState>: the states saved by [ and restored by ].

  • commands, an MHCQueue<Character>: the commands that have been loaded but have not run yet.

The last two instance variables use two different data structures:

  • We use a stack for savedStates because ] always returns the turtle to the most recently saved state. The last state we add is the first one we need back, which is exactly the LIFO (Last In First Out) behavior of a stack.

  • We use a queue for commands because commands run in the same order they were loaded. The first command we add is the first one that runs, which corresponds to the FIFO (First In First Out) behavior of a queue.

Complete the Turtle() constructor, which takes a starting position, a starting heading, a step length, and a turn angle. It sets up the instance variables as follows:

  1. Store x, y, heading, stepLength, and turnAngle directly from the parameters.

  2. Set segments to a new, empty ArrayList.

  3. Set savedStates to a new, empty MHCStackLL.

  4. Set commands to a new, empty MHCQueueLL.

MHCStackLL and MHCQueueLL are the linked list implementations of the MHCStack and MHCQueue interfaces that we worked with in Lab 7, and both are provided for you in the starter folder.

[Task] Moving and turning¶

Next, let’s implement the two methods that change the turtle’s position and heading: forward() and turn().

The forward() method moves the turtle stepLength pixels in the direction of its heading. To do that, we need to work out how far that step moves the turtle horizontally and how far it moves the turtle vertically. One way to picture this: the step is the long side of a right triangle, and the two shorter sides are the change in x and the change in y.

A turtle at (x, y) taking one step of length stepLength to (newX, newY). The horizontal side of the triangle is how far x changes, and the vertical side is how far y changes.

A turtle at (x, y) taking one step of length stepLength to (newX, newY). The horizontal side of the triangle is how far x changes, and the vertical side is how far y changes.

You may remember from a math class that the cosine and sine of an angle give us the lengths of those two sides. If your trigonometry feels rusty, no worries! The two formulas below are all that we’ll need:

newX=x+stepLengthƗcos⁔(radians(heading))\text{newX} = x + \text{stepLength} \times \cos(\text{radians}(\text{heading}))
newY=yāˆ’stepLengthƗsin⁔(radians(heading))\text{newY} = y - \text{stepLength} \times \sin(\text{radians}(\text{heading}))

Note that the formula for newX adds and the formula for newY subtracts. In the figure, the turtle is moving up the window, and because y coordinates increase downward, moving up means that y gets smaller.

Processing provides the cosine and sine functions as PApplet.cos() and PApplet.sin(). However, there’s a catch: both expect their angle in a unit called radians, and our headings are in degrees. Processing also provides PApplet.radians() to convert an angle from degrees to radians. The three methods we’ll need are:

  • PApplet.radians(float degrees) returns the given angle converted from degrees to radians.

  • PApplet.cos(float angle) returns the cosine of an angle given in radians.

  • PApplet.sin(float angle) returns the sine of an angle given in radians.

To take the cosine of an angle in degrees, we convert it first to radians using PApplet.radians(), and then call PApplet.cos() on the result:

// the cosine of 60 degrees, which is about 0.5
float result = PApplet.cos(PApplet.radians(60));

Putting this together, forward() has three parts:

  1. Compute newX and newY using the formulas above.

  2. Add a new LineSegment object to the segments list that goes from the turtle’s current position (x, y) to (newX, newY).

  3. Update the turtle’s x and y coordinates to newX and newY.

The turn(float degrees) method is brief: all it does is add degrees to the turtle’s heading. Since headings increase as the turtle turns left, a positive value turns the turtle left and a negative value turns it right.

[Task] Saving and restoring turtle states¶

Now that our turtle can move and turn, let’s implement the saveState() and restoreState() methods, which correspond to the [ and ] commands.

With only F, +, and -, the turtle draws one continuous path: every segment starts where the previous one ended. To draw more complex shapes, it is useful to be able to save and restore the turtle’s position and heading. The [ and ] commands make this possible:

  • [ saves the turtle’s current position and heading as a TurtleState, pushing it to the top of the savedStates stack.

  • ] pops the most recently saved TurtleState from the top of the stack, and sets the turtle’s position and heading back to the saved values.

So in the command string F[+F]F, the [ saves the turtle’s state, the +F draws a line segment off to the left, and the ] restores the turtle’s state to where it was before. The final F then continues from the saved position and heading. Below is a video visualizing this process where the turtle starts at (100, 100) and heading 90 (up), with a step length of 20 and a turn angle of 45:

Before writing the methods, let’s trace an example by hand.

Now that you have a visualization of what the [ and ] commands do, implement the methods that correspond to them:

  • saveState() creates a new TurtleState object from the turtle’s current x, y, and heading, and pushes it onto savedStates.

  • restoreState() has two parts:

    1. Pop the top TurtleState off of the savedStates stack.

    2. Set the turtle’s x, y, and heading to the values in that state, using the TurtleState getters getX(), getY(), and getHeading().

[Task] Loading and running commands¶

Finally, we’ll connect the turtle’s methods to the command strings we started with.

The runCommand(char command) method runs a single command, and it is provided for you in the starter file:

public void runCommand(char command) {
    if (command == 'F') {
        forward();
    } else if (command == '+') {
        turn(turnAngle);
    } else if (command == '-') {
        turn(-turnAngle);
    } else if (command == '[') {
        saveState();
    } else if (command == ']') {
        restoreState();
    }
}

Each conditional matches one row of the command table, and each one calls a method you’ve already written. Note that + and - call the same turn() method, with a positive turnAngle to turn left and a negative one to turn right. Also note that there is no final else: if the character isn’t one of the five commands, none of the conditionals are true and the method does nothing.

What’s left is getting the characters of a command string to runCommand() one at a time. We do this in two steps, using the commands queue:

  • loadCommands(String commandString) enqueues every character of commandString to the commands queue, reading the string in order from left to right. For example, loadCommands("F+-") will enqueue the characters F, +, and - in that order.

  • step() dequeues the next command from the commands queue and runs it by calling runCommand() on it.

By adding the commands to the queue, we can watch the turtle draw by calling step() once each time the Processing window is redrawn.

[Task] testCode() and TurtleViewer¶

Before moving on, make sure to test the methods you wrote in the Turtle class by adding tests to testCode(). In particular, make sure to test the following:

  • forward() and turn()

  • saveState() and restoreState() should save and restore the turtle’s position and heading properly on the savedStates stack.

  • loadCommands() and step() should load the commands and run them properly on the commands queue.

Running TurtleViewer¶

Up to this point, we’ve tested the turtle without opening a Processing window. We provide the TurtleViewer.java class that draws the turtle’s line segments. Open the file and click the play button in VSCodium. If your implementation is working correctly, you should see your turtle draw a square, one command at a time.

TurtleViewer creates one Turtle near the bottom middle of the window, facing up. It calls step() four times per second and then draws each LineSegment along with a picture of a turtle at the turtle’s current position and heading.

The main() method at the bottom of the file holds four examples, each one a command string and a turn angle:

ExampleCommandsAngle
A squareF+F+F+F90
A triangleF+F+F120
The design from the ā€œDraw the codeā€ exerciseF[+F]F[-F]F--45
A small tree that branches into twoF[+F[+F][-F]][-F[+F][-F]]30

To draw a different example, comment out the current commands and angle lines and uncomment another pair. Try each of the four. For the last two, keep an eye on the number of saved states on the stack as the turtle reaches each [ and ]. Also feel free to write a command string of your own!

By the last example, you should have your turtle sitting on a trunk of a ā€œtreeā€:

The Turtle class is now complete!

3. L-Systems¶

Writing a command string by hand works for a square or a small tree, but a detailed drawing can take thousands of commands. In this section, we’ll build the LSystem class, which can generate intricate patterns by continually applying sets of rules to a starting string.

L-System concepts¶

L-systems were introduced by biologist Aristid Lindenmayer (the L in L-system) in 1968 as a way to formalize how plants and algae grow. An L-system describes a ā€œgrammarā€ that has two parts:

  • An axiom: a beginning string.

  • A set of rules. Each rule gives one character and the string that replaces it. We write a rule with an arrow, so the rule A -> AB means ā€œreplace A with ABā€.

To grow the string, we read it one character at a time from left to right, and build a new string as we go:

  • If the character has a rule, we add that rule’s replacement to the new string.

  • If the character doesn’t have a rule, we add the character itself to the new string.

Each new string we build this way is called a generation. The axiom is generation 0, the string we build from the axiom is generation 1, the string we build from generation 1 is generation 2, and so on.

For example, here is the L-system that Lindenmayer used to describe how algae grows:

  • Axiom: A

  • Rules:

    • A -> AB

    • B -> A

Let’s work out the first two generations:

  • Generation 0 is the starting axiom A.

  • Generation 1: we read generation 0, which is A. Its only character is A, and the rule A -> AB replaces it with AB. So generation 1 is AB.

  • Generation 2: we read generation 1, which is AB. The A is replaced with AB, and then the B is replaced with A. Putting the two replacements together in order gives AB followed by A, so generation 2 is ABA.

Note that every character we read comes from the previous generation. In generation 1, the B was added by the rule for A, but we don’t apply the rule B -> A to it until we build generation 2. Each generation replaces each character exactly once by reading left to right.

GenerationResulting String
0A
1AB
2ABA

[Task] LSystem constructor¶

Let’s begin by looking at the instance variables of the LSystem.java class:

  • name, a String: a name to display for the L-system, such as ā€œalgaeā€.

  • axiom, a String: the generation 0 string.

  • angle and heading, both float values: the turn angle and the starting heading a Turtle should use to draw this L-system, in degrees.

  • symbols, a char array: the characters that have a rule.

  • replacements, a String array: the string that replaces each of those characters.

  • currentGen, a String: the string for the current generation.

  • generation, an int: the current generation number.

The rules are stored across the symbols and replacements arrays, which line up by index: the character at index i of symbols is replaced with the string at index i of replacements. For example, here are the two arrays for the algae L-system:

// index 0 holds the rule A -> AB, and index 1 holds the rule B -> A
char[] symbols =        {'A',  'B'};
String[] replacements = {"AB", "A"};

Complete the LSystem() constructor, which takes a name, an axiom, an angle, a heading, and the two arrays of rules. It sets up the instance variables as follows:

  1. Store name, axiom, angle, heading, symbols, and replacements directly from the parameters.

  2. Set currentGen to the axiom.

  3. Set generation to 0.

[Task] LSystem methods¶

Next, let’s implement the three methods that grow the string. Each one builds on the one before it: getRule() replaces one character, applyRules() replaces every character of a string, and generate() moves the L-system forward by one generation.

getRule() method¶

The getRule(char c) method returns the string that the character c is replaced with. Using the algae L-system as an example:

  • getRule('A') returns "AB".

  • getRule('B') returns "A".

  • getRule('F') returns "F". There is no rule for F, so it is replaced with itself.

Our approach is to:

  1. Loop over the indices of the symbols array.

  2. If the character at the current index of symbols is equal to c, return the string at the same index of replacements.

  3. If we complete the loop over the symbols array without finding a rule, return the character itself as a string. This return case is already provided for you in the starter file:

public String getRule(char c) {
    // TODO your code here



    // if no rule is found, return the character itself as a string
    return String.valueOf(c);
}

applyRules() method¶

The applyRules(String current) method takes one generation’s string and returns the next generation’s string. The overall approach is to start with an empty String, and then loop over the characters of current from left to right, adding what getRule() returns for each character to the end of the new string.

For example, with the algae L-system, applyRules("ABA") returns "ABAAB", which matches going from generation 2 to generation 3 in the ā€œCheck your understandingā€ question.

generate() method¶

Finally, the generate() method advances the L-system by one generation. Just as step() advances the turtle by one command, generate() advances the L-system by one generation each time it is called. It does two things:

  1. Calls applyRules() on currentGen, and sets currentGen to the string it returns.

  2. Increases generation by 1.

The LSystem class is now complete!

4. Drawing Different L-Systems¶

Now that we have a Turtle that follows a command string and an LSystem that generates strings, let’s put the two together. The algae L-system only uses the characters A and B, which our turtle ignores. To get a drawing, we need an L-system whose strings are made of the turtle’s commands.

Running LSystemViewer¶

We provide the LSystemViewer.java class, which draws an L-system with your turtle. Open the file and click the play button in VSCodium. If your implementations of Turtle and LSystem are working correctly, you should see your turtle draw a single horizontal line.

LSystemViewer gives the L-system’s current string to a Turtle and animates the turtle running its commands. Each time you press the space bar, it calls generate() on the L-system and gives the new string to a new turtle. The Processing window also shows the name of the L-system, the generation number, and the number of commands in the current string.

The main() method at the bottom of the file creates the L-system to draw. It starts with one called the Koch curve[2]:

// Koch curve
String kochAxiom = "F";
float kochAngle = 90;
float kochHeading = 0;
char[] kochRulesStart = {'F'};
String[] kochRulesReplacements = {"F+F-F-F+F"};

system = new LSystem("Koch curve", kochAxiom, kochAngle, kochHeading, kochRulesStart, kochRulesReplacements);

The Koch curve has an axiom of F and a single rule, F -> F+F-F-F+F. Its turtle turns 90 degrees on each + or -, and starts with a heading of 0 (facing right).

Press the space bar a few times, and compare the string at the top of the window with what the turtle draws:

The Koch curve from generation 0 to generation 4.

[Task] The Sierpinski triangle and the dragon curve¶

Next, let’s draw two more L-systems. Below the Koch curve in main() are commented-out lines for each of them. The angle and the heading are filled in, but the axiom and the rules are left as TODOs. For example, here are the lines for the Sierpinski triangle[3]:

// Sierpinski triangle
// float sierpinskiAngle = 60;
// float sierpinskiHeading = 0;
// String sierpinskiAxiom = TODO;
// char[] sierpinskiRulesStart = TODO;
// String[] sierpinskiRulesReplacements = TODO;
// system = new LSystem("Sierpinski triangle", sierpinskiAxiom, sierpinskiAngle, sierpinskiHeading, sierpinskiRulesStart, sierpinskiRulesReplacements);

To draw one of these L-systems, replace the TODOs with the axiom and the rules from the table below, following the structure of the Koch curve’s lines. Then uncomment the lines to create the L-system.

Here are the axiom and the rules for the two L-systems:

L-systemAxiomAngleRules
Sierpinski triangleXF60X -> YF+XF+Y
Y -> XF-YF-X
Dragon curveFX90X -> X+YF+
Y -> -FX-Y

Both of these L-systems have rules for X and Y, which are not turtle commands. Recall from section 1 that any other character is ignored by the turtle. The X and Y characters are thus only there for the rules to replace, which is how the string grows from one generation to the next.

Try out both L-systems, pressing the space bar to step through their generations. Part 1 is now complete! We’ll build on this turtle drawing framework to generate more art in Part 2.

Part 1 task checklist¶

Going further¶

Here are some directions to explore. None of these are required!

  • You can draw a plant by adding one more L-system to main() in LSystemViewer, following the structure of the other three. This one is called the fractal plant:

    L-systemAxiomAngleHeadingRules
    Fractal plantX2590X -> F+[[X]-X]-F[-X]+X
    F -> FF

    Its rules use the [ and ] commands, so keep an eye on the number of saved states on the stack as the turtle draws. Generation 0 is X, which the turtle ignores, so the window stays empty until you press the space bar.

  • You can design an L-system of your own. One way to start is to change the angle or one of the rules of an L-system you’ve already drawn, and see how the drawing changes.

  • Many of the L-systems that draw plants come from the book The Algorithmic Beauty of Plants by Przemyslaw Prusinkiewicz and Aristid Lindenmayer, which is free to read online.

Footnotes¶
  1. Turtle graphics comes from Logo, a programming language created in 1967 to teach introductory programming concepts to kids. The first turtles were small robots that rolled around on a sheet of paper, drawing with a pen as they moved.

  2. The Koch curve is named after the mathematician Helge von Koch, who described it in 1904. His original curve uses triangular bumps, and ours is a variation that uses right angles.

  3. This L-system draws a single winding line called the Sierpinski arrowhead curve. With each generation, the line comes closer to filling in the Sierpinski triangle, a triangle made of smaller copies of itself.