简体   繁体   中英

How should i draw a Peano Curve?

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)

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM