Search code examples
pythonturtle-graphicstiling

How to draw a tiled triangle with python turtle


I am trying to draw a tiled equilateral triangle that looks like this

enter image description here

using python's turtle. I would like to be able to have either 16,25,36,49 or 64 triangles.

My initial attempts are clumsy because I havent figured out how to neatly move the turtle from one triangle to the next.

Here it is my (partially correct) code

def draw_triangle(this_turtle, size,flip):    
    """Draw a triangle by drawing a line and turning through 120 degrees 3 times"""
    this_turtle.pendown()
    this_turtle.fill(True)
    for _ in range(3):
        if flip:
           this_turtle.left(120)
        this_turtle.forward(size)
        if not flip:
           this_turtle.right(120)
    this_turtle.penup()

myturtle.goto(250,0)
for i in range(4):
   for j in range(4):
      draw_triangle(myturtle, square_size,(j%2 ==0))
      # move to start of next triangle
      myturtle.left(120)
      #myturtle.forward(square_size)

   myturtle.goto(-250,(i+1)*square_size)

There must be an elegant way of doing this?


Solution

  • I found this an interesting problem, if modified so that the turtle must draw the figure just by moving and without jumps.

    The solution I found is ugly, but it can be a starting point...

    def n_tri(t, size, n):
        for k in range(n):
            for i in range(k-1):
                t.left(60)
                t.forward(size)
                t.left(120)
                t.forward(size)
                t.right(180)
            t.left(60)
            t.forward(size)
            t.right(120)
            t.forward(k * size)
            t.left(60)
        t.right(180)
        t.forward(n * size)
        t.right(180)
    

    You can see how the pattern looks here