Tom Smith
Tom Smith

Reputation: 361

Generate fractal squares using recursion

I'm learning recursion, and want to achieve this in Python (turtle):

Fractal cubes

I made a recursive function, in which I draw a square starting from the bottom-left corner, facing 'east'. I can get the squares on one of the sides correct, but not on the other.

Moving backwards before drawing the smaller square gives odd results:

Odd results

from turtle import *
delay(0)
speed(10)

def square(length, level):
if level == 0:
    return
else:
    # Start from the bottom-left corner
    forward(length)
    # Right square
    square(length // 2, level - 1)
    lt(90)

    forward(length)
    lt(90)

    forward(length)
    lt(90)

    forward(length)
    lt(90)

    ### Try moving backward before drawing
    ##backward(length / 2)

    # Left square
    square(length // 2, level - 1)

square(110, 4)

Any tips or good examples for learning these kinds of fractals?

Upvotes: 2

Views: 2878

Answers (1)

Holt
Holt

Reputation: 37706

When drawing fractal with turtle, you should be careful regarding the following points:

  1. Where the function must starts (in your case, you specify "bottom-left corner").
  2. Where it stops (?) - Position and orientation! This points is not clear in your code and it is why it is not working.

There are two problems in your code:

  • You should move backward(length // 2) to start correctly the drawing of the left square (as you did in the comment)
  • You should come back where you started the square (bottom-left corner of the big square)

Here is the code with some comment:

def square(length, level):
    # Start from the bottom-left corner    
    if level == 0:
        return
    else:
        # Draw the bottom side
        forward(length)
        # Draw the right square
        square(length // 2, level - 1)
        # Assume we ended at the same position
        # Draw the right side
        lt(90); forward(length)
        # Draw the upper side
        lt(90); forward(length)
        # Draw the left side
        lt(90); forward(length)
        # Go backward
        lt(90); backward(length // 2) ;
        # Draw the left square
        square(length // 2, level - 1)
        # Go back to the original position
        forward(length // 2)

Basically, you were missing the last forward(length // 2) which moves the turtle to its original position.

Upvotes: 1

Related Questions