I am trying to write a program that draws a sierpinski tree with python using turtle. Here is my idea:
import turtle
def draw_sierpinski(length,depth):
window = turtle.Screen()
t = turtle.Turtle()
if depth==0:
for i in range(0,3):
t.fd(length)
t.left(120)
else:
draw_sierpinski(length/2,depth-1)
t.fd(length/2)
draw_sierpinski(length/2,depth-1)
t.bk(length/2)
t.left(60)
t.fd(length/2)
t.right(60)
draw_sierpinski(length/2,depth-1)
window.exitonclick()
draw_sierpinski(500,1)
The program does not reach the 2nd line after the else statement and I don't know why. Can anyone help me?
I don't think you should be creating the turtle or window object inside the function. Since draw_sierpinski
gets called four times if you originally call it with depth 1, then you'll create four separate windows with four separate turtles, each one drawing only a single triangle. Instead, I think you should have only one window and one turtle.
import turtle
def draw_sierpinski(length,depth):
if depth==0:
for i in range(0,3):
t.fd(length)
t.left(120)
else:
draw_sierpinski(length/2,depth-1)
t.fd(length/2)
draw_sierpinski(length/2,depth-1)
t.bk(length/2)
t.left(60)
t.fd(length/2)
t.right(60)
draw_sierpinski(length/2,depth-1)
window = turtle.Screen()
t = turtle.Turtle()
draw_sierpinski(500,1)
window.exitonclick()
Result:
These results look pretty good for a depth 1 triangle, but what about when we call draw_sierpinski(100,2)
?
Ooh, not so good. This occurs because the function should draw the shape, and then return the turtle to its original starting position and angle. But as is evident from the depth 1 image, the turtle doesn't return to its starting position; it ends up halfway up the left slope. You need some additional logic to send it back home.
import turtle
def draw_sierpinski(length,depth):
if depth==0:
for i in range(0,3):
t.fd(length)
t.left(120)
else:
draw_sierpinski(length/2,depth-1)
t.fd(length/2)
draw_sierpinski(length/2,depth-1)
t.bk(length/2)
t.left(60)
t.fd(length/2)
t.right(60)
draw_sierpinski(length/2,depth-1)
t.left(60)
t.bk(length/2)
t.right(60)
window = turtle.Screen()
t = turtle.Turtle()
draw_sierpinski(100,2)
window.exitonclick()
Result: