python uses turtle library to draw tree shapes, python turtle draws simple trees

Hello everyone, the editor is here to answer the following questions for you. Python uses the turtle library to draw tree shapes, and python turtle draws simple trees. Now let us take a look!

Author | 1_bit
Editor | Produced by Wang Xiaoman
| CSDN Blog

start


I used Turtle to draw a tree and looked at the code on the Internet. Basically, the core method is to use recursion; secondly, the thickness of the pen is changed by recursively passing parameters to change the line segment during drawing and the trunk size of the tree. When traversing to the last node , change the color and thickness of the pen, and draw the petals or green leaves on the top of the tree.

This blog post is modified from the code on the Internet. Basically, it is simple to write and uses recursion. I also took it and used it to summarize the secondary python test points and python frequently asked questions . I originally wanted to draw the environment by the way, but I have to go to work tomorrow and have other things to do today, so I have to give it up and write another case to fix the environment when I have time; the following is the result after the final code is run ( The code is not optimized and the efficiency may not be very good):

It feels a little fresh, hahaha, the color is deliberately matched, floral!

Okay, now let’s see how to write it. The final code is at the bottom, and the above is a step-by-step explanation of some of the problems encountered.
First, we use the simplest way to draw a trunk of the tree. The code is as follows:

from turtle import *

left(80)
fd(100)
right(30)
fd(30)
right(30)
fd(40)
input()

The result is as follows:

The above code first uses t.left(80) to move the turtle to a position almost perpendicular to the horizontal line, then uses t.fd(100) to draw a 100-unit line segment in the direction of the cutting head, and then uses t.right(30) to draw a line segment of 100 units in the direction of the cutting head. Turn right 30 degrees, and then draw a line segment 30 units forward with t.fd(30); at this time, there is a node between the line segments. This node is generated by turning the right angle to simulate the trunk of the tree; finally t. right(30) turns 30 degrees to the right, and t.fd(40) draws 40 unit length line segments forward to extend the final torso.

However, the above line segments are not suitable to describe the tree as a plant, but don’t worry, let’s change the thickness and color of the drawn line segments first to make the drawn picture look more like a tree.

color|pensize()

Change the thickness and color of the pen through t.pensize() and t.color(). The code is as follows:

from turtle import *

color('#5E5E5E')
pensize(10)
left(80)
fd(100)
right(30)
fd(30)
right(30)
fd(40)
input()

After changing the thickness of the pen, the drawing result is as follows:

Maybe the result is more like a blade of grass, but it doesn't matter, we slowly change the code; now we lengthen the branches of the tree and reduce the thickness of the pen:

from turtle import *

color('#5E5E5E')
pensize(6)
left(80)
fd(150)
right(30)
fd(50)
right(30)
fd(60)
input()

The result is as follows:

It looks a lot better. The entire trunk part can be divided into the main trunk and scattered branches. We can divide it into several parts to write; first draw the trunk of the tree, and then use the function to draw the branches of the tree:

from turtle import *

def drawTree(length):
    right(20)
    fd(length)

color('#5E5E5E')
pensize(5)

up()
goto(0,-300)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(60)
input()

The running results are as follows:

At this time, the code starts from the bottom of the drawing area and draws upwards. Use color('#5E5E5E') to set the drawing color; pensize(5) sets the thickness of the drawn line segment; goto(0,-300) jumps to the drawing area. The lower part is used as the starting point; then turn 80 degrees to the left and draw a line segment as the trunk of the tree; then call the function drawTree(120) and pass in the length to draw the branches. In the drawTree function, right(20) The right side is rotated 20 degrees, and fd(length) draws a line segment as a branch.

Now that we have written the function, we can use recursion to start drawing branches:

from turtle import *

def drawTree(length):
    if length>1:
        right(20)
        fd(length)
        drawTree(length - 10)

color('#5E5E5E')
pensize(5)

up()
goto(0,-300)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(60)
input()
运行结果如下:

From the code point of view, only the code content of the drawTree function part has been modified; recursion is used in the function, and the value passed in after the recursion is the current length minus 10 lengths, and it is judged in the function that it will only be executed when the length is greater than 1, so This prevents infinite loops caused by no escape conditions in recursion.

The current lengths have fixed differences. Random numbers are used to make the drawn branch lengths random, which is closer to the real branches (only the modified part of the code is posted here):

def drawTree(length):
    if length>1:
        right(20)
        fd(length)
        randlen=random.random()
        drawTree(length - 10*randlen)

operation result:

The code uses random numbers, subtracts the random value from the fixed difference of 10, and participates in the subtraction operation after obtaining the value.
So here, the rotation angle is also fixed, let’s randomize the rotation angle:

def drawTree(length):
    if length>1:
        randangle=random.random()
        randlen=random.random()
        right(20*randangle)
        fd(length)

        drawTree(length - 10*randlen)

operation result:

Officially begin

Our branches now have only one direction, which is to the right. We now add left-facing branches to draw:

from turtle import *
import random

def drawTree(length):
    if length>1:
        randangle=random.random()
        randlen=random.random()
        right(20*randangle)
        fd(length)

        drawTree(length - 10*randlen)
        left(40 * randangle)
        fd(length)


color('#5E5E5E')
pensize(5)

up()
goto(0,-300)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(60)
input()

However an error occurred:

Why is this happening?

That's because we need to jump to the previous drawing position, just use the backward function. Change the drawTree function as follows:

def drawTree(length):
    if length>1:
        randangle=random.random()
        randlen=random.random()
        right(20*randangle)
        fd(length)
        up()
        backward(length)
        down()
        left(40 * randangle)
        fd(length)
        drawTree(length - 10*randlen)

The result is as follows:

In fact, this effect is still good, but it is not what we want. This effect may be good for painting dogtail grass; change the code:

from turtle import *
import random

def drawTree(length):
    if length>1:
        #随机角度与长度
        randangle=random.random()
        randlen=random.random()

        #每次使用函数先绘制线段,再调整角度,这里是向右的角度转动
        fd(length)
        right(20*randangle)
        drawTree(length - 10*randlen)

        #这里是向左的角度转动
        left(40 * randangle)
        drawTree(length - 10*randlen)

        #为什么需要再向右转20度?那是因为我一共向左转了40度,使用backward后退,必须是相同的角度,不然退回去角度就不同了位置就不会对
        right(20 * randangle)

        up()
        backward(length)
        down()

tracer(False)
color('#5E5E5E')
pensize(5)

up()
goto(0,-300)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(60)
input()

The result is as follows:

The code explanation is in the comments. It is a simple recursion. However, since the length passed in is not long, there are not many line segments drawn on the branches, which will cause the whole tree to not grow lush enough. Let’s modify the passed length value. is 120, and the drawing result is as follows. Note that since the drawing takes too long, you can directly use tracer(False) to directly display the effect. There is no need to draw and render once (this depends on your parameters, just change it to False); here To change the coordinate system, customize it to a larger coordinate system than the current one. Otherwise, the screen display will not be complete. Just use the code setworldcoordinates(-1000,-750,1000,750). The overall code is as follows:

from turtle import *
import random

def drawTree(length):
    if length>1:
        #随机角度与长度
        randangle=random.random()
        randlen=random.random()

        #每次使用函数先绘制线段,再调整角度,这里是向右的角度转动
        fd(length)
        right(20*randangle)
        drawTree(length - 10*randlen)

        #这里是向左的角度转动
        left(40 * randangle)
        drawTree(length - 10*randlen)

        #为什么需要再向右转20度?那是因为我一共向左转了40度,使用backward后退,必须是相同的角度,不然退回去角度就不同了位置就不会对
        right(20 * randangle)

        up()
        backward(length)
        down()

setworldcoordinates(-1000,-750,1000,750)        
tracer(False)
color('#5E5E5E')
pensize(5)

up()
goto(0,-300)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(120)
input()

The result is as follows:

However, since there is no minimum length limit for the corners of random numbers and the length of branches, you can multiply a suitable number at random times and adjust the starting position downwards. The code is as follows:

randangle=2*random.random()
randlen=2*random.random()
.
.
.
.
.
.
goto(0,-700)

The result is as follows:

almost done

The general shape of a tree has been drawn. Now start filling in the green and red flowers on the branches of the tree. Generally speaking, the higher the top of the branches of the tree, the smaller they are. Judging the value of the length, it will be green within a certain range. , it is red within a certain range, then you can simulate the effect of tree blossoms and green leaves. The code is as follows, and the color code can be adjusted by yourself:

from turtle import *
import random

def drawTree(length):
    if length>1:
        if length<30 and length>14:#缩小一下树干
            pensize(4)
        elif length<15 and length>5:#长度这个范围内那么就是绿叶
            color('#04B486')#
            pensize(3)
        elif length<5 and length>1:#红花
            color('#FE2E9A')
            pensize(2)
        else:
            color('#5E5E5E')#其他范围就是正常的树干
            pensize(5)
        #随机角度与长度
        randangle=2*random.random()
        randlen=2*random.random()

        #每次使用函数先绘制线段,再调整角度,这里是向右的角度转动
        fd(length)
        right(20*randangle)
        drawTree(length - 10*randlen)

        #这里是向左的角度转动
        left(40 * randangle)
        drawTree(length - 10*randlen)

        #为什么需要再向右转20度?那是因为我一共向左转了40度,使用backward后退,必须是相同的角度,不然退回去角度就不同了位置就不会对
        right(20 * randangle)

        up()
        backward(length)
        down()

setworldcoordinates(-1000,-750,1000,750)        
tracer(False)
color('#5E5E5E')
pensize(5)

up()
goto(0,-700)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(120)
input()

The running results are as follows:

Drawing falling flowers

The tree is a bit too long and lush, hahaha; the tree shape is randomly different every time, so I don’t understand that it won’t fit on one screen, but it doesn’t matter much. Now we start to draw the effect of falling leaves and flowers.
The function of the falling flower effect is as follows:

def fallingFlowers(m):
    x,y=-1000,-750

    yval=50
    for i in range(m):
        a = 100*random.random()
        b = 2*random.random()
        print(a)
        if a>59:
            color('#FE2E9A')
        else:
            color('#04B486')
        circle(5)
        up()
        goto(x,y+(yval*b))
        fd(a)
        yval+=50
        down()      

Run as follows:

Because the coordinate system we defined is [-1000,-750] to [1000,750], we start drawing the falling flowers from the lower left corner. The values ​​of the x and y coordinates defined in the code are x, y =-1000,-750, and then use a y value in the loop to increase each time. The drawing position goes up from the lower left corner each time, so the y coordinate increases each time in the loop, and is given random multiplication, so that it will For better randomization, use goto(x,y+yval) every time to jump to the specified x,y coordinate position, but please note here that the value of x remains unchanged; and in the loop I set A variable a is mainly used for fd(a) to perform randomization on the x-axis. The same value will lead to the same arrangement, which is not very beautiful. This is also the reason why the random value b is multiplied by yval.

Then modify the code and set a loop in the outer layer to add the x coordinate values ​​and fill the drawing area horizontally:

from turtle import *
import random

def drawTree(length):
    if length>1:
        if length<30 and length>14:#缩小一下树干
            pensize(4)
        elif length<15 and length>5:#长度这个范围内那么就是绿叶
            color('#04B486')#
            pensize(3)
        elif length<5 and length>1:#红花
            color('#FE2E9A')
            pensize(2)
        else:
            color('#5E5E5E')#其他范围就是正常的树干
            pensize(5)
        #随机角度与长度
        randangle=2*random.random()
        randlen=2*random.random()

        #每次使用函数先绘制线段,再调整角度,这里是向右的角度转动
        fd(length)
        right(20*randangle)
        drawTree(length - 10*randlen)

        #这里是向左的角度转动
        left(40 * randangle)
        drawTree(length - 10*randlen)

        #为什么需要再向右转20度?那是因为我一共向左转了40度,使用backward后退,必须是相同的角度,不然退回去角度就不同了位置就不会对
        right(20 * randangle)

        up()
        backward(length)
        down()
def fallingFlowers(m):
    x,y=-1000,-750
    for i in range(30):
        up()
        goto(x,y)
        x+=100
        down()
        yval=50
        for i in range(m):
            a = 100*random.random()
            b = 2*random.random()
            print(a)
            if a>59:
                color('#FE2E9A')
            else:
                color('#04B486')
            circle(5)
            up()
            goto(x,y+(yval*b))
            fd(a)
            yval+=50
            down()      

setworldcoordinates(-1000,-750,1000,750)        
tracer(False)
color('#5E5E5E')
pensize(5)

# up()
# goto(0,-700)#跳到绘制起始点
# down()

# left(80)
# fd(140)
# drawTree(120)
fallingFlowers(10)
input()

operation result:

The new outer loop increments the value of x, and finally tiles the lower half of the drawing area.

Final Results

Finally, combined with the tree drawing code, open the comments and set the background color bgcolor("#F5F6CE"):

from turtle import *
import random

def drawTree(length):
    if length>1:
        if length<30 and length>14:#缩小一下树干
            pensize(4)
        elif length<15 and length>5:#长度这个范围内那么就是绿叶
            color('#04B486')#
            pensize(3)
        elif length<5 and length>1:#红花
            color('#FE2E9A')
            pensize(2)
        else:
            color('#5E5E5E')#其他范围就是正常的树干
            pensize(5)
        #随机角度与长度
        randangle=2*random.random()
        randlen=2*random.random()

        #每次使用函数先绘制线段,再调整角度,这里是向右的角度转动
        fd(length)
        right(20*randangle)
        drawTree(length - 10*randlen)

        #这里是向左的角度转动
        left(40 * randangle)
        drawTree(length - 10*randlen)

        #为什么需要再向右转20度?那是因为我一共向左转了40度,使用backward后退,必须是相同的角度,不然退回去角度就不同了位置就不会对
        right(20 * randangle)

        up()
        backward(length)
        down()
def fallingFlowers(m):
    x,y=-1000,-750
    for i in range(30):
        up()
        goto(x,y)
        x+=100
        down()
        yval=50
        for i in range(m):
            a = 100*random.random()
            b = 2*random.random()
            print(a)
            if a>59:
                color('#FE2E9A')
            else:
                color('#04B486')
            circle(5)
            up()
            goto(x,y+(yval*b))
            fd(a)
            yval+=50
            down()      

setworldcoordinates(-1000,-750,1000,750)        
tracer(False)

fallingFlowers(10)#绘制落叶
bgcolor("#F5F6CE")
color('#5E5E5E')
pensize(5)

up()
goto(0,-700)#跳到绘制起始点
down()

left(80)
fd(140)
drawTree(120)

input()

The result is as follows:

If you feel that there are not enough fallen leaves and flowers, you can change the parameters. Because the code is not optimized, the running effect is too slow. I will post it after optimization.

Copyright statement: This article is an original article by CSDN blogger "1_bit" and follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.

Original link: https://blog.csdn.net/a757291228/article/details/106029202

【END】

更多精彩推荐
  ☞Flash 已死,Deno 当立?
☞OceanBase 十年:一群追梦人的成长史
☞2 年 6 个月 11 天,外包到阿里的修仙之路!| 原力计划
☞服务器软件大扫盲!
☞绝悟之后再超神,腾讯30篇论文入选AI顶会ACL
☞中本聪并没有出现,那真相是?
你点的每个“在看”,我都认真当成了喜欢

Guess you like

Origin blog.csdn.net/chatgpt001/article/details/132969230