python - Sierpinski triangle recursion using turtle graphics -
i trying write program draws sierpinski tree python using turtle. here idea:
import turtle def draw_sierpinski(length,depth): window = turtle.screen() t = turtle.turtle() if depth==0: 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 not reach 2nd line after else statement , don't know why. can me?
i don't think should creating turtle or window object inside function. since draw_sierpinski
gets called 4 times if orininally call depth 1, you'll create 4 separate windows 4 separate turtles, each 1 drawing single triangle. instead, think should have 1 window , 1 turtle.
import turtle def draw_sierpinski(length,depth): if depth==0: 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 pretty depth 1 triangle, when call draw_sierpinski(100,2)
?
ooh, not good. occurs because function should draw shape, , return turtle original starting position , angle. evident depth 1 image, turtle doesn't return starting position; ends halfway left slope. need additional logic send home.
import turtle def draw_sierpinski(length,depth): if depth==0: 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:
Comments
Post a Comment