Recursive Triangles with Turtle

After much fight, here is the code for recursive triangles in Turtle:


import turtle

# We will draw equilateral triangles, one inside the other

def set_turtle_position(myTurtle, x, y):
    myTurtle.penup()
    myTurtle.setx(x)
    myTurtle.sety(y)
    myTurtle.pendown()

def get_turtle_position(myTurtle):
    return (myTurtle.xcor(), myTurtle.ycor())

def draw_triangle(myTurtle, length, isReverse):
    myTurtle.setheading(0)

    if (isReverse):
        pacman.color("blue", "white")
    else:
        pacman.color("blue", "green")

    pacman.begin_fill()
    for i in range(1, 4):
        myTurtle.forward(length)
        if (isReverse):
            myTurtle.right(120)
        else:
            myTurtle.left(120)
    pacman.end_fill()

def draw_recursive_triangles_internal(myTurtle, length, curDepth, maxDepth, position):
    if (curDepth > maxDepth):
        return
            
    (x1, y1) = position
    (x2, y2) = (x1+(length/2), y1)
    
    set_turtle_position(myTurtle, x1, y1)
    myTurtle.left(60)
    myTurtle.fd(length/2)
    draw_triangle(myTurtle, length/2, 1)

    (x3, y3) = get_turtle_position(myTurtle)
        
    draw_recursive_triangles_internal(myTurtle, length/2, curDepth+1, maxDepth, (x2, y2))
    draw_recursive_triangles_internal(myTurtle, length/2, curDepth+1, maxDepth, (x3, y3))
    draw_recursive_triangles_internal(myTurtle, length/2, curDepth+1, maxDepth, (x1, y1))
    

def draw_recursive_triangles(myTurtle, length, maxDepth):
    currentDepth = 1
    position = get_turtle_position(myTurtle)

    draw_recursive_triangles_internal(myTurtle, length, currentDepth, maxDepth, position)

# Basic screen and turtle configuration
canvas = turtle.Screen()
pacman = turtle.Turtle()
pacman.shape("turtle")
pacman.shapesize(1, 1, 1)
pacman.pensize(2)
canvas.bgcolor("white")
pacman.speed(10)

# Initial turtle position
set_turtle_position(pacman, -180, -150)
pacman.setx(-180)
pacman.sety(-150)
pacman.clear()

draw_triangle(pacman, 400, 0)
draw_recursive_triangles(pacman, 400, 5)

canvas.exitonclick()


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s