1024 Special Clip: Drawing a randomly generated tree using the Python Turtle library

Personal homepage::?Beginner level cow?
Highly recommended high-quality column: The world of C++ (continuously updated)
Recommended column 1: C language beginners
Recommended Column 2: C Language Advanced
Personal creed: Unity of knowing and doing
Introduction to this article:>: Use the Python Turtle library to draw a randomly generated tree
Share golden quotes:
?1024 Happy Programmer’s Day! ?

1. Preface

This code uses the Python Turtle library to draw a randomly generated tree and draw a 1024 Happy Programmer’s Day text on the top layer. The specific analysis is as follows:

Directory

  • I. Introduction
  • 2. Draw a random tree
    • 1. Import the `turtle` and `random` libraries.
    • 2. Create a `turtle` object
    • 3. Define a `draw_tree()` function
    • 4. Draw text
    • 5. Set drawing speed
    • Code example:
  • 3. Conclusion:

2. Draw random tree

1. Import the turtle and random libraries.

import turtle
import random

2. Create a turtle object

Create a turtle object and set the brush, such as brush color, width, etc.

Use the turtle module of Python to create a turtle object named “pen” and set its speed to 0 (fastest). Then, set its color to brown, its width to 2, and move its position below the center of the screen. Next, lift its pen and place it into the starting position. Finally, set the screen background color to white.

pen = turtle.Turtle()
pen.speed(0)
pen.color("brown")
pen.width(2)
pen.penup()
pen.setpos(0, -200)
pen.pendown()
turtle.bgcolor("white") # Set the screen background color to white

3. Define a draw_tree() function

This function uses recursion to draw branches randomly, and draws flowers and tree top on the top layer.

This is a custom function, the function name is draw_tree().
It requires three parameters:
(1) branch_len represents the branch length
(2) t represents the turtle object for drawing,
(3) level indicates the number of levels of the branch.

This function uses recursion to draw the tree. When the branch length is less than 5, the branch color changes to pink and a small dot is drawn to represent the flower; otherwise, it draws several branches and calls draw_tree() again for each branch function. Before drawing the branches, a random angle is chosen to make the branches look random. Additionally, the width of the branches adaptively adjusts based on the branch length to give them a more reasonable appearance.

Finally, after painting the tree, if this is the topmost branch, then it will change the brush color to green and draw a small dot at the top of the tree to represent the leaves. By default, the height of the tree is 150 units, but this can be modified in code.

def draw_tree(branch_len, t, level):
    if branch_len < 5:
        t.color("pink") //The color can be customized and modified
        t.stamp()
        t.color("brown")
    else:
        angle = random.randint(20, 45)
        sf = random.uniform(0.6, 0.8)
        t.pensize(branch_len / 10)
        t.forward(branch_len)
        t.left(angle)
        draw_tree(branch_len * sf, t, level + 1)
        t.right(angle * 2)
        draw_tree(branch_len * sf, t, level + 1)
        t.left(angle)
        t.backward(branch_len)

        if level == 0:
            t.color("green")
            t.stamp()

tree_height = 150
pen.left(90)
pen.backward(tree_height)
pen.pendown()
draw_tree(tree_height, pen, 0)

4. Draw text

Draw some text you want

pen.penup()
pen.setpos(0, 200)
pen.pendown()
pen.write("Niu Niu wishes everyone!", align="center", font=("Arial", 30, "normal"))
pen.penup()
pen.setpos(0, 150)
pen.pendown()
pen.write("1024 Happy Programmer's Day", align="center", font=("Arial", 30, "normal"))

5. Set drawing speed

pen.speed(0)

Code example:

import turtle
import random

#Create turtle object
pen = turtle.Turtle()
pen.speed(0)
pen.color("brown")
pen.width(2)
pen.penup()
pen.setpos(0, -200)
pen.pendown()
turtle.bgcolor("white")

# Define the function for drawing trees
def draw_tree(branch_len, t, level):
    if branch_len < 5:
        t.color("pink") # When less than 5, the leaves turn pink
        t.stamp() # Draw flowers
        t.color("brown") # Switch back to trunk color
    else:
        angle = random.randint(20, 45) # Randomly select the branch angle
        sf = random.uniform(0.6, 0.8) # Randomly select branch length scaling factor
        t.pensize(branch_len / 10) #Set the brush thickness according to the length of the branch
        t.forward(branch_len) # Draw branches
        t.left(angle) # Left turn branch angle
        draw_tree(branch_len * sf, t, level + 1) # Draw the right branch recursively, adding the level parameter
        t.right(angle * 2) # The branch angle of double the right turn, that is, twice the branch angle of the left turn
        draw_tree(branch_len * sf, t, level + 1) # Draw the left branch recursively, adding the level parameter
        t.left(angle) #Restore direction
        t.backward(branch_len) # Return to original position

        # Change the color of leaves and trunk at the top level of the tree (level=0)
        if level == 0:
            t.color("green") # The trunk turns green
            t.stamp() # Draw the top of the tree

#Initialize trunk length
tree_height = 150
pen.left(90)
pen.backward(tree_height)
pen.pendown()

# Start drawing the tree
draw_tree(tree_height, pen, 0) #The initial level is 0

# draw text
pen.penup()
pen.setpos(0, 200) #Set text position
pen.pendown()
pen.write("Niu Niu wishes everyone!", align="center", font=("Arial", 30, "normal"))
pen.penup()
pen.setpos(0, 150) #Set text position
pen.pendown()
pen.write("1024 Happy Programmer's Day", align="center", font=("Arial", 30, "normal"))


#Set drawing speed
pen.speed(0) #Set the drawing speed to 0, the fastest speed

while True:
    pen.hideturtle() # Hide the brush
    turtle.delay(500) # Wait for a while
    pen.showturtle() #Show brush
    turtle.delay(500) # Wait for a while

The final rendering:

3. Conclusion:

Date: 2023 year 10 month 24 day

Today is our holiday, let us celebrate our career and love together, and pay tribute to the pursuit of technology!

We pursue the ultimate in code quality and are obsessed with algorithm optimization and performance improvement. The software we write can help people improve their work efficiency, improve their quality of life, and promote technological development.

But at the same time, we also face huge challenges. Code bugs, technology may be outdated, communication and collaboration issues may affect our daily work. Therefore, we need to continue learning and making progress to be able to meet the challenges of new technologies and ensure that our software and systems can continue to meet people’s needs.

bless:
I wish all programmers a happy holiday, may our code be free of bugs, and our technology will advance with each passing day, so that we can continue to grow in this field and create a colorful life!