pythonpython-turtlefractals

Recursive fractal with python turtler


I am trying to figure out a way to draw this:

enter image description here

but somehow I cant do this. I realize that the image is the same it's just 4 times in the right place. Here is the code that I have so far, can somebody help me achieve this ???

import turtle

def draw_fractal(t, length, depth):

    if depth: 
        for _ in range(4):
            t.forward(length)
            t.right(90)

        t.penup()
        t.forward(length / 2)
        t.right(90)
        t.forward(length / 2)
        t.left(90)
        t.pendown()

        # Draws smaller squares
        for _ in range(4):
            draw_fractal(t, length / 2, depth - 1)
            if _ < 3: 
                t.penup()
                t.forward(length)
                t.right(90)
                t.pendown()
        
        t.penup()
        t.left(90)
        t.forward(length / 2)
        t.right(90)
        t.forward(length / 2)
        t.pendown()

def main():
    
    window = turtle.Screen()
    window.bgcolor("white")
    t = turtle.Turtle()
    t.speed(0)

    
    draw_fractal(t, 200, 3)

    
    window.mainloop()

main()



Solution

  • I find that folks new to programming either write too little code, or too much code to solve the problem. You're mostly in the "too much code" camp (due to lack of understanding of recursion) but are also missing some code elements you need. The fractal recursion should occur inside this loop, not after it:

    for _ in range(4):
        t.forward(length)
        t.right(90)
    

    As you round each corner, you should be starting your next recursion.

    An element you don't account for at all is the the gap. This fractal is unusual in that the gap is a constant all the way down -- unlike the size of the squares it doesn't decrease. So, we either need to supply the gap size to the initial call, or compute it on the top level call and pass that result down to the recursive calls.

    It would also be nice to use all that extra code to center the figure. My rework of your code with one possible solution to the problems:

    from turtle import Screen, Turtle
    
    GAP_RATIO = 0.05
    
    def draw_fractal(t, length, depth, gap=None):
    
        if depth:
            if gap is None:
                gap = length * GAP_RATIO
    
            for _ in range(4):
                draw_fractal(t, (length / 2) - gap, depth - 1, gap)
                t.forward(length)
                t.right(90)
    
    def main():
    
        SIDE = 400
    
        screen = Screen()
    
        turtle = Turtle()
        turtle.speed('fastest')
    
        turtle.penup()
        turtle.goto(-SIDE/2, SIDE/2)  # center image
        turtle.pendown()
    
        draw_fractal(turtle, SIDE, 4)
    
        turtle.hideturtle()
        screen.exitonclick()
    
    main()
    

    enter image description here