Search code examples
pythonrecursionturtle-graphicspython-turtle

Using recursion to draw nested Triangles


I'd like to draw a series of nested triangles using recursion.

My faulty code below:

def recursiveTri(x, y, shrink):

    tt.penup()
    tt.setx(x)
    tt.sety(y)

    if x > -10:
        return

    for element in range(3):
        tt.pendown()
        tt.forward(x)
        tt.right(120)

    recursiveTri(x + shrink, y - shrink, shrink)

def main():
    recursiveTri(-300,300,30)

main()

The current code produces the following:

Actual output

Here is what I mean by nested shapes, except that I would like to draw triangles instead of squares:

Nested squares


Solution

  • The problem is with

    tt.forward(x)
    

    Remember that your x is always negative, and the length of a side is not x, but rather -2 * x, if you want to be symmetrical about zero. Since your triangles are nested, you can also compute the initial y from x, given that it is 1/3 of the way up the main bisector. -sqrt(3) / 3 * x therefore puts the center of the circles circumscribed around and inscribed in your triangle at 0, 0.

    In fact, it is probably easier to just fix the length of a side, and compute x and y from that:

    import turtle as tt
    from math import sqrt
    
    def recursiveTri(side, shrink):
        if side < 10: return
    
        tt.penup()
        tt.goto(-side / 2, sqrt(3) / 6 * side)
    
        tt.pendown()
    
        for _ in range(3):
            tt.forward(side)
            tt.right(120)
    
        recursiveTri(side - shrink, shrink)
    
    tt.penup()
    tt.home()
    tt.dot()
    recursiveTri(300, 30)
    

    In this case, shrink is the total amount removed from each side. If you want it to be the amount you step forward, change the recursive call to recursiveTri(side - 2 * shrink, shrink).

    The result (without multiplying shrink by 2) is

    Nested triangles