A Python version of turtle graphics that allows you to manipulate a turtle with a pen to draw a picture. Scratch is famous for children, but it seems to be a good teaching material depending on how you use it. I thought that this drawing was amazing and tried using it ...
――You can draw such a line art (like a forest or a forest)
Here is the sample code. Let's create a function called forest.
turtlePicture.py
#
#Import turtle and draw a line
# 2020.06.15 ProOJI
#
import turtle
#kameSan object creation
kameSan = turtle.Turtle()
#Create a method (recursive usage)
def forest(n, length:int=1000)->None:
    if n <= 0:
        kameSan.forward(length)
        return
    '''Recursion 1 length= 1000 * 0.5 '''
    forest(n-1, length * 0.5)
    #Rotate 85 degrees to the right
    #From gentle to sharp
    kameSan.right(85)
    '''Recursive 2 length= 1000 ÷ 3 '''
    forest(n-1, length / 3)
    #Rotate 170 degrees to the left
    #Draw a sharp needle on a sharp turn
    kameSan.left(170)
    '''Recursion 3 length= 1000 ÷ 3 '''
    forest(n-1, length / 3)
    #Rotate 85 degrees to the right
    #Land in a gentle direction again
    kameSan.right(85)
    '''Recursion 4 length= 1000 ÷ 0.38 '''
    forest(n-1, length * 0.38)
if __name__ == '__main__':
    kameSan.penup()
    kameSan.setpos(270, -20)
    kameSan.pendown()
    kameSan.left(180)
    kameSan.speed(0)
    forest(5)
    kameSan.done()
By doing this, you can draw a line. Also, if you make some modifications and set a color change in the recursive part ...
--Sample code (colored)
turtlePictureWithColor.py
#
#Import turtle and draw a line
#kameSan draws lines when moving
# 2020.06.15 ProOJI
#
import turtle
#kameSan object creation
kameSan = turtle.Turtle()
#Create a method (recursive usage)
def forest(n, length:int=1000)->None:
    if n <= 0:
        kameSan.forward(length)
        return
    '''Recursion 1 length= 1000 * 0.5 '''
    kameSan.pencolor("red")
    forest(n-1, length * 0.5)
    #Rotate 85 degrees to the right
    #From gentle to sharp
    kameSan.right(85)
    '''Recursive 2 length= 1000 ÷ 3 '''
    kameSan.pencolor("blue")
    forest(n-1, length / 3)
    #Rotate 170 degrees to the left
    #Draw a sharp needle on a sharp turn
    kameSan.left(170)
    '''Recursion 3 length= 1000 ÷ 3 '''
    kameSan.pencolor("green")
    forest(n-1, length / 3)
    #Rotate 85 degrees to the right
    #Land in a gentle direction again
    kameSan.right(85)
    '''Recursion 4 length= 1000 ÷ 0.38 '''
    forest(n-1, length * 0.38)
if __name__ == '__main__':
    #penup No drawing because the pen is raised
    kameSan.penup()
    #Move to Position
    kameSan.setpos(270, -20)
    #pendown The pen is lowered so it is drawn from here
    kameSan.pendown()
    #Turn 180 degrees to the left
    kameSan.left(180)
    kameSan.speed(0)
    forest(5)
    kameSan.done()
You can see which code draws the line and how.
Recommended Posts