Reputation: 361
I'm learning recursion, and want to achieve this in Python (turtle):
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:
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
Reputation: 37706
When drawing fractal with turtle
, you should be careful regarding the following points:
There are two problems in your code:
backward(length // 2)
to start correctly the drawing of the left square (as you did in the comment)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