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 2: Computational Plants 🌱

Plants as binary trees

Lindenmayer introduced L-systems to describe how plants grow, and we’ll put this into practice with the art that we’re generating. In Part 1, every L-system had a fixed set of rules, so the same L-system always drew the same picture. However, real plants of the same kind don’t look identical -- there is some element of randomness to how the branches split and grow.

We’ll write code to generate plant images that apply L-system rules stochastically (at random), so that no two plants are alike. To keep track of every choice, we’ll store each plant as a binary tree: each branch of the plant is a node, and the branches that grow from its end are its children. Your Turtle from Part 1 will then be used to draw the tree.

Once the base Plant class is complete, we’ll apply inheritance concepts from the beginning of the semester to extend the provided classes in order to customize our plant designs:

1. PlantNode.java

PlantNode.java will be the building block of our plant images. A PlantNode object is one node of the plant’s binary tree, and it represents one branch of the plant, one step (one F in terms of Turtle graphics) long. Open up the provided starter file to take a look at the following instance variables and its constructor:

// The direction this branch grows: "F", "+F", or "-F"
private String direction;

// The branch's Strahler number, which determines its width.
private int strahler;

// The branches growing from this branch's end, or null if there are none.
private PlantNode left;
private PlantNode right;

// drawing instance variables omitted...

public PlantNode(String direction) {
    this.direction = direction;
    this.strahler = 0;
    this.left = null;
    this.right = null;
}

Note that left and right are themselves PlantNode objects, each with a left and right of their own. Thus the PlantNode class acts just like the BinaryTreeNode class we have been working with in lecture and lab. A node with no children represents a leaf of the tree, and we’ll write recursive algorithms traversing each node’s left and right.

Branch directions

Each node stores the direction its branch grows as one of three possible strings:

CommandWhat the turtle does
"F"Moves forward, drawing the trunk
"+F"Turns left, then moves forward
"-F"Turns right, then moves forward

These are the same F, +, and - commands from the turtle command table in Part 1.

Here is a small plant next to its binary tree. Each branch is labeled with a letter, so you can match each line segment of the plant to its node in the tree:

On the left, a plant drawn with a turn angle of 30 degrees. On the right, the same plant as a binary tree of PlantNode objects, with each branch’s commands written below its node. Branch G has only a left child, so in the plant, only one branch grows from G’s end.

Figure 2:On the left, a plant drawn with a turn angle of 30 degrees. On the right, the same plant as a binary tree of PlantNode objects, with each branch’s commands written below its node. Branch G has only a left child, so in the plant, only one branch grows from G’s end.

A PlantNode also contains Processing drawing functionality, like the Card class you wrote in PA 2. The width of its branch comes from its Strahler number, which we’ll discuss further in the next section. For now, all we need to know is that branches near the bottom of the plant have higher Strahler numbers and are drawn thicker, while branches near the top have lower Strahler numbers and are drawn thinner.

For example, to create branches A, B, and G in the figure above, we would need to write code that creates a trunk, then sets its left and right with new PlantNode objects:

// the trunk is drawn with "F"
PlantNode trunk = new PlantNode("F");
// the left child turns left with "+F"
trunk.setLeft(new PlantNode("+F"));
// the right child turns right with "-F"
trunk.setRight(new PlantNode("-F"));

There are other provided methods in PlantNode that determine how the plant looks, which we’ll look at later on in section 4.

2. Plant.java

Now, we’ll use PlantNode as a building block for the Plant class. A Plant holds the trunk of the plant as the root of its binary tree, just like how the BinaryTree class from lecture holds its root node. It has two instance variables:

  • root, a PlantNode: the trunk of the plant.

  • generation, an int: how many times the plant has grown.

[Task] Plant constructor

Complete the Plant() constructor, which creates a new plant that is just a trunk:

  1. Set root to a new PlantNode object with the direction "F" to represent a straight trunk.

  2. Set generation to 0.

Stochastic L-systems

In Part 1, each character had exactly one rule. A stochastic L-system instead gives a character several rules, and chooses one of them at random each time the character is replaced.[1] Our plants use the character X to mark a growing tip, just like the dragon curve used X and Y in Part 1. We have the following rules:

StringRuleChanceWhat the rule does
"GROW_LEFT"X -> [+FX]8%Grows a left branch only
"GROW_RIGHT"X -> [-FX]8%Grows a right branch only
"REST"X -> X8%Grows nothing this generation
"GROW_BOTH"X -> [+FX][-FX]76%Grows a left branch and a right branch

A new plant is a trunk with one growing tip, FX. Here is what that tip becomes under each rule:

The rule for each tip is chosen by the getLeafRule() method, which is provided for you in the starter file:

public String getLeafRule() {
    // Math.random() returns a random decimal number within the range [0, 1)
    float randomNum = (float) Math.random();
    // there is an 8% chance we grow left [0, 0.08)
    if (randomNum < 0.08) {
        return "GROW_LEFT";
    // there is an 8% chance we grow right [0.08, 0.16)
    } else if (randomNum < 0.16) {
        return "GROW_RIGHT";
    // there is an 8% chance we rest and grow nothing [0.16, 0.24)
    } else if (randomNum < 0.24) {
        return "REST";
    }
    // the remaining 76% of the time, we split both left and right
    return "GROW_BOTH";
}

Math.random() returns a decimal number that is at least 0 and less than 1, with every number in that range equally likely. We then write a chain of if-else statements to match the probabilities of each rule: we split the range from 0 to 1 into four pieces, and the length of each piece is the chance of its rule. The order of the conditionals matters here, because each else if only runs when every condition above it was false. For example, randomNum < 0.16 is only checked once we know randomNum is at least 0.08, so it covers the 8% of the range from 0.08 up to 0.16.

[Task] grow() method

We’ll begin by implementing the grow() method, which grows the plant by one generation. Just as generate() replaced every character of an L-system’s string exactly once in Part 1, grow() applies a rule to every leaf node of the plant exactly once.

The public grow() method is provided for you in the starter file. It calls a private recursive helper method on the root, and then increases the generation by 1:

public void grow() {
    growHelper(root);
    generation++;
}

This is the same structure as the height() method from lecture, which called a recursive helper method on the root of the tree. Your job is to complete the recursive helper, growHelper(PlantNode node), which grows the part of the plant whose root is node:

private void growHelper(PlantNode node) {
    // TODO your code here

}

To create each new branch, use the provided createPlantNode() method rather than calling the PlantNode constructor directly:

public PlantNode createPlantNode(String direction) {
    return new PlantNode(direction);
}

We use the createPlantNode() method in order to write subclasses of Plant that can change what kind of PlantNode object is returned, which is what allows us to customize the look of our plant in Section 4.

The growHelper(PlantNode node) helper has three cases:

  1. Base case: If node is null, there is nothing to grow, so return.

  2. If node is a leaf node, call getLeafRule() to randomly select a rule. Then:

    • If the rule is equal to "GROW_LEFT", set the node’s left child to a new node created using createPlantNode() with the direction "+F".

    • If the rule is equal to "GROW_RIGHT", set the node’s right child to a new node created using createPlantNode() with the direction "-F".

    • If the rule is equal to "GROW_BOTH", set the node’s left child to a new node created with the direction "+F" and the node’s right child to a new node created with the direction "-F".

    • Otherwise, do nothing in the "REST" case.

  3. Recursive case: Otherwise, the node is not a leaf, so recursively call growHelper on its left subtree and its right subtree.

[Task] Strahler number

Next, we’ll write another recursive method that determines the thickness of each branch. A branch near the bottom of a plant should be drawn thicker than a branch near a leaf. One measure of this is the Strahler number of each node in a tree.[2] Like the height of a tree from lecture, it is defined recursively:

  • Base case: an empty tree (a null node) has Strahler number 0.

  • Recursive case: recursively compute the Strahler numbers of the branch’s left and right subtrees.

    • If both subtrees have the same Strahler number kk, the current node has Strahler number k+1k + 1.

    • Otherwise, the current node has the max of the two Strahler numbers.

This is very similar to the structure of the recursive height() method from lecture: return 0 for an empty tree, and otherwise combine the answers for the two subtrees. The only difference is in the combine step. Note that a branch’s Strahler number depends on its children’s Strahler numbers, so the recursive calls happen before determining the Strahler number for the current node.

[Task] strahler() method

Now that you’ve worked through an example by hand, let’s implement it in the code. Like most of the recursive methods in the course, we need a public strahler() method, which calls the private recursive helper method on the root:

public int strahler() {
    // TODO your code here
    return 0;
}

Next, complete the recursive helper strahlerHelper(PlantNode node), which labels every branch of the plant rooted at node with its Strahler number, and returns the Strahler number of node:

  1. If node is null, return 0.

  2. Compute the Strahler number of the left subtree and the right subtree using recursive calls.

  3. If the two Strahler numbers are equal, the node’s Strahler number is one more than that number. Otherwise, the node’s Strahler number is the larger of the two.

  4. Store the Strahler number in the current node using node.setStrahler(number).

  5. Finally, return the current Strahler number.

[Task] testCode()

Creating binary trees by hand for test cases is a bit tedious, so we provide the test cases for grow() for you.

We also provide starter code for generating a plant that matches the one in the drawing exercise in order to test your strahler() method. Write tests against this starter code, and refer to your labeled drawing to see what you should expect if any of them fail. Specifically, you should test whether strahler() returns the correct value and if each node’s Strahler numbers are correctly set.

toString() method

Finally, to draw the plant, PlantViewer needs an L-system string that your Turtle drawer can follow. We provide a toString() method that builds this string with a pre-order traversal. Like grow() and strahler(), it calls a private recursive helper method on the root. We encourage you to read through the implementation to understand how it works, but you don’t need to modify it.

The Plant class is now complete!

3. Running PlantViewer

To visualize the plants being drawn with your Turtle graphics system, open the provided PlantViewer.java class and run it. You should see your turtle draw a single vertical line.

Each time PlantViewer draws the plant, it calls strahler() to label the branches, and gives the string from toString() to a new Turtle. Then it draws each line segment your turtle records with the PlantNode it belongs to, and draws a leaf at the end of every tip.

  • Press the space bar to grow the plant by one generation.

  • Press N to grow a new plant to the same generation. Since every plant chooses its rules at random, each new plant looks different.

Here is PlantViewer growing a Plant from generation 0 to generation 8:

Drawing a BlossomBush

The plant that PlantViewer draws is chosen in its newPlant() method:

private Plant newPlant() {
    // Choose the plant to draw by commenting out the other lines
    return new Plant();
    // return new BlossomBush();
    // return new MyPlant();
}

Comment out return new Plant() and uncomment return new BlossomBush() -- your PlantViewer should now be generating images like the one below:

The BlossomBush class is short, as it only overrides three of the methods it inherits from Plant. We’ll take a closer look at it in the next section.

4. Design your own plant

Now that we have the framework for generating plant art computationally, we can customize the look of our drawings by utilizing the inheritance concepts from the beginning of the semester: we can write subclasses that extend Plant and PlantNode and override some of the methods that determine the look of the plant. In particular, you’ll write two classes:

  • MyPlantNode, which extends PlantNode and changes how the branches and leaves look.

  • MyPlant, which extends Plant, changes how it grows, and is made of MyPlantNode objects.

[Task] MyPlantNode class

The provided BlossomPlantNode class is an example of extending PlantNode. It overrides two methods:

  • getLeafColor() randomly returns one of three shades of pink instead of PlantNode’s green.

  • getLeafSize() returns 16, so its blossoms are drawn wider than PlantNode’s 10-pixel leaves.

Here is the class:

public class BlossomPlantNode extends PlantNode {

    private static final int PINK = rgb(250, 190, 210);
    private static final int DEEP_PINK = rgb(242, 69, 130);
    private static final int PALE_PINK = rgb(255, 225, 235);

    // Width of each blossom, in pixels
    private static final float BLOSSOM_SIZE = 16;

    // The pink this branch's blossom is drawn in.
    private int leafColor;

    public BlossomPlantNode(String direction) {
        super(direction);
        leafColor = chooseLeafColor();
    }

    private int chooseLeafColor() {
        // Math.random() returns a random decimal number within the range [0, 1)
        float randomNum = (float) Math.random();
        // there is a 40% chance the blossom is pink [0, 0.4)
        if (randomNum < 0.4) {
            return PINK;
        // there is a 40% chance the blossom is deep pink [0.4, 0.8)
        } else if (randomNum < 0.8) {
            return DEEP_PINK;
        }
        // the remaining 20% of the time, the blossom is pale pink
        return PALE_PINK;
    }

    public int getLeafColor() {
        return leafColor;
    }

    public float getLeafSize() {
        return BLOSSOM_SIZE;
    }
}

Note that the constructor calls super(direction) first, which runs the PlantNode constructor to set up the direction, the Strahler number, and the children. Also note that the color is chosen in the constructor, and stored in the leafColor instance variable.

Using the BlossomPlantNode as a template (feel free to copy the file), create your own class called MyPlantNode that extends the PlantNode class. Have your implementation override at least one of these PlantNode methods:

  • getLeafColor(): the color of each leaf. Feel free to use BlossomPlantNode as a template for choosing colors at random.

  • getLeafSize(): the width of each leaf, in pixels.

  • drawLeaf(PApplet app, float x, float y): how a leaf is drawn. For example, it could draw a different shape.

  • drawPlantNode(PApplet app, LineSegment segment): how a branch is drawn. For example, it could use a different bark color.

To choose your colors, you’ll need the amounts of red, green, and blue for each color to pass to the rgb() method. Conveniently, VSCodium has a built-in color picker that you can use just by hovering over the lines of code that have rgb:

[Task] MyPlant class

The provided BlossomBush class is an example of extending Plant. It overrides three methods:

public class BlossomBush extends Plant {

    public float getAngle() {
        return 25;
    }

    public String getLeafRule() {
        double r = Math.random();
        if (r < 0.15) {
            return "GROW_LEFT";
        } else if (r < 0.30) {
            return "GROW_RIGHT";
        } else if (r < 0.40) {
            return "REST";
        }
        return "GROW_BOTH";
    }

    public PlantNode createPlantNode(String direction) {
        return new BlossomPlantNode(direction);
    }
}
  • getAngle() returns the angle, in degrees, that each + or - turns. Plant uses 22 degrees, and a BlossomBush spreads wider with 25.

  • getLeafRule() gives the four rules different chances than Plant does, so a bush grows on one side only more often.

  • createPlantNode() returns a BlossomPlantNode instead of a PlantNode. Since your grow() method creates every new branch by calling createPlantNode(), every branch that is created is a BlossomPlantNode object.

Using the BlossomBush as a template (feel free to copy the file), create your own class called MyPlant that extends the Plant class. Complete MyPlant by overriding:

  • createPlantNode(), so that it returns a new MyPlantNode, and

  • at least one of getAngle() and getLeafRule().

[Task] Take a screenshot of your plant

In PlantViewer’s newPlant() method, comment out the other lines and uncomment return new MyPlant();. Run PlantViewer, grow your plant with the space bar, and press N until you find a plant you like. Then take a screenshot of the Processing window and save it as myPlant.png.

When your plant is growing in PlantViewer, you’ve finished PA 4 (and all of the programming assignments for this semester!)

5. Reflection

Finally, answer the following reflection questions in a file named README.md and submit it to Gradescope:

  1. Approximately how much time did you spend on PA 4?

  2. What were the most challenging portion(s) of the assignment?

  3. What is one thing you have a better understanding of after completing this assignment and going through the class content?

  4. Would you be willing to have your custom plant be part of a class collage?

  5. Indicate the number of late days (if any) you are using for this assignment.

Part 2 task checklist

Going further

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

  • Override drawPlantNode() in MyPlantNode to color the bark by Strahler number, for example darker near the trunk and lighter near the leaves.

  • Override drawLeaf() to draw a leaf of a different shape. Processing’s app.triangle(), app.rect(), and app.ellipse() are a good place to start.

  • Many more plant-like L-systems, including stochastic ones, are in The Algorithmic Beauty of Plants by Przemyslaw Prusinkiewicz and Aristid Lindenmayer, which is free to read online.

Footnotes
  1. Prusinkiewicz and Lindenmayer describe stochastic L-systems in The Algorithmic Beauty of Plants, as a way to make each plant of a species look different while keeping its overall structure.

  2. The Strahler number comes from the study of rivers. The geographers Robert Horton and Arthur Strahler used it to classify the streams in a river network.