03 November 2015

I just found there is a module called turtle in python.

Try them out:

Fractal Tree

 1 import turtle
 2 
 3 def tree(branchLen,t):
 4     if branchLen > 5:
 5         t.forward(branchLen)
 6         t.right(20)
 7         tree(branchLen-15,t)
 8         t.left(40)
 9         tree(branchLen-15,t)
10         t.right(20)
11         t.backward(branchLen)
12 
13 def main():
14     t = turtle.Turtle()
15     myWin = turtle.Screen()
16     t.left(90)
17     t.up()
18     t.backward(100)
19     t.down()
20     t.color("green")
21     tree(75,t)
22     myWin.exitonclick()
23 
24 main()

Sierpinski Triangle

 1 import turtle
 2 
 3 def drawTriangle(points,color,myTurtle):
 4     myTurtle.fillcolor(color)
 5     myTurtle.up()
 6     myTurtle.goto(points[0][0],points[0][1])
 7     myTurtle.down()
 8     myTurtle.begin_fill()
 9     myTurtle.goto(points[1][0],points[1][1])
10     myTurtle.goto(points[2][0],points[2][1])
11     myTurtle.goto(points[0][0],points[0][1])
12     myTurtle.end_fill()
13 
14 def getMid(p1,p2):
15     return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2)
16 
17 def sierpinski(points,degree,myTurtle):
18     colormap = ['blue','red','green','white','yellow',
19                 'violet','orange']
20     drawTriangle(points,colormap[degree],myTurtle)
21     if degree > 0:
22         sierpinski([points[0],
23                         getMid(points[0], points[1]),
24                         getMid(points[0], points[2])],
25                    degree-1, myTurtle)
26         sierpinski([points[1],
27                         getMid(points[0], points[1]),
28                         getMid(points[1], points[2])],
29                    degree-1, myTurtle)
30         sierpinski([points[2],
31                         getMid(points[2], points[1]),
32                         getMid(points[0], points[2])],
33                    degree-1, myTurtle)
34 
35 def main():
36    myTurtle = turtle.Turtle()
37    myWin = turtle.Screen()
38    myPoints = [[-100,-50],[0,100],[100,-50]]
39    sierpinski(myPoints,3,myTurtle)
40    myWin.exitonclick()
41 
42 main()

I hope this is interesting.

Reference: Problem Solving with Algorithms and Data Structures