If you read books about Logo while you were a kid you remember all that fun with turtle graphics, using loops to draw circles and recursion to generate really complicated shapes.

As you can see on wikipedia drawing a Sierpinski carpet pixel by pixel is trivial when the squares are aligned to x & y axes. The general case is a bit harder. Here is how to do it with a turtle and a little bit of of recursion.

 

def carpet(r):
    if r < 1:
        return

    penup()
    forward(r / 2); left(90); forward(r / 2); right(90)
    
    pendown();
    for k in range(4):
        right(90)
        forward(r)

    penup(); forward(r / 2); left(90); forward(r / 2); right(90)

    for k in range(4):
        carpet(r / 3)
        right(90)
        forward(r)
        carpet(r / 3)
        forward(r)

    penup()
    back(r)
    right(90)
    forward(r)
    left(90)

 

Sierpinski carpet free rotation

Sierpinski carpet free rotation

About these ads