How should i draw a Peano Curve?

Question:

This is my code for drawing a peano curve using python turtle in Visual Studio Code. I can get level 1 just fine but other than that it does not really repeat the shape correctly for the subsequent levels. Any suggestions?

from turtle import *
def peano(level, length):
    if level == 1:
       print(rt(45), fd(length/3), rt(90), fd(length/3), lt(90), fd(length/3))
       print(lt(90), fd(length/3), lt(90), fd(length/3), rt(90), fd(length/3))
       print(rt(90), fd(length/3), rt(90), fd(length/3), lt(90), fd(length/3))
    else:
       peano(level-1, length/2)
       rt(45)
       peano(level-1, length/2)
       rt(-45)
       peano(level-1, length/2)

peano(2, 40)
Asked By: raxer007

||

Answers:

At its most basic, 0th level, the fractal routine needs to simply draw a straight line using forward() (aka fd()). At level 1, it should draw the basic pattern that makes up the fractal, but using the fractal routine itself to draw lines, not forward(). Every level above that does the same. We’re replacing line drawing with fractal drawing:

from turtle import *

def peano(level, length):
    if level == 0:
        forward(length)
    else:
        angle = 90

        peano(level-1, length/3)

        right(angle)
        peano(level-1, length/3)

        for _ in range(2):
            for _ in range(3):
                left(angle)
                peano(level-1, length/3)

            angle = -angle

        left(angle)
        peano(level-1, length/3)

# Starting position and angle to fill our window
penup()
goto(-220, 220)
pendown()
right(45)

peano(2, 600)

exitonclick()

You don’t need the nested loops that I added, you can write out the steps explicitly:

    else:
        peano(level-1, length/3)

        right(90)
        peano(level-1, length/3)

        left(90)
        peano(level-1, length/3)
        left(90)
        peano(level-1, length/3)
        left(90)
        peano(level-1, length/3)

        right(90)
        peano(level-1, length/3)
        right(90)
        peano(level-1, length/3)
        right(90)
        peano(level-1, length/3)

        left(90)
        peano(level-1, length/3)

enter image description here

Answered By: cdlane