Turtle Power

Turtle Power

Thanks to this great website, I’ve been having some more fun with Python.  I’m now in the chapter on Recursion, which introduces Python’s Turtle module. Turtle is an implementation of Logo, a language I remember playing with happily in my younger years. What you can do with it in Python is quite amazing sometimes.  There are some demo scripts that come pre-installed, and can be accessed this way:

python -m turtledemo

I’ve still not wrapped my head around the more complex ones, but the Sierpinski example in the tutorial is a nice start. I learned from their example and wrote my own (fairly similar) version. The result looks pretty nice:

sierpinski

A couple of weeks back I wouldn’t have been able to come up with something like this at all, so I’m pretty happy with what I’ve learned so far.
Below is the script. Just pasting it in a python3 prompt should suffice.

import turtle
def drawTriangle(points, color, t):
    t.fillcolor(color)
    t.penup()
    t.goto(points[0][0],points[0][1])
    t.pendown()
    t.begin_fill()
    t.goto(points[1][0],points[1][1])
    t.goto(points[2][0],points[2][1])
    t.goto(points[0][0],points[0][1])
    t.end_fill()
def findMid(p1,p2):
    return( (p1[0]+p2[0])/2, (p1[1]+p2[1])/2 )
def sierpinski(points,depth,t):
    colormap=['purple2','tomato2','khaki3','gold','orchid','spring green','turquoise']
    drawTriangle(points,colormap[depth-1],t)
    if depth>1:
        sierpinski([points[0],findMid(points[0],points[1]),
                    findMid(points[0],points[2])],depth-1,t)
        sierpinski([points[1],findMid(points[1],points[2]),
                    findMid(points[0],points[1])],depth-1,t)
        sierpinski([points[2],findMid(points[2],points[0]),
                    findMid(points[2],points[1])],depth-1,t)
def main():
    t = turtle.Turtle()
    myWin = turtle.Screen()
    t.speed(0)
    points=[[-300,-150],[0,150],[300,-150]]
    sierpinski(points,6,t)
    t.hideturtle()
    myWin.exitonclick()
main()
Comments are closed.
%d bloggers like this: