Home > Software design >  A start to tiling the screen with triangles
A start to tiling the screen with triangles

Time:02-14

At the moment, I'm trying to get started trying to tile the python turtle graphics screen with equilateral triangles of random colors. I've made a function which is successfully able to make a triangle starting at say coordinates v_1 = (x, y). Once it's made the triangle, I want the turtle to head to one of the other triangle vertices that are not equal to v_1 and start a new triangle there. I'd like to do all of this in a while loop. However, when I run my code, it seems that the turtle always goes back to the initial position of the first equilateral triangle and makes a new one on top of it. I'm not sure what I'm doing wrong. Here's my code:

from turtle import Turtle, colormode, done
from random import randint
colormode(255)


def make_left_triangle(bob: Turtle, x: float, y: float) -> None:
    """Makes an equilaterial triangle at coordinates (x, y) with the turtle bob moving left."""
    r: int = randint(0, 255)
    g: int = randint(0, 255)
    b: int = randint(0, 255)
    rand_n: int = randint(1, 2)
    i: int = 0
    bob.penup()
    bob.goto(x, y)
    bob.pendown()
    bob.fillcolor(r, g, b)
    bob.begin_fill()
    while i < 3:
        bob.forward(200)
        bob.left(120)
        i  = 1
    bob.end_fill()
    while rand_n < 3:
        bob.forward(200)
        bob.left(120)
        rand_n  = 1


def main() -> None:
    bob: Turtle = Turtle()
    i: int = 0
    rand_n: int = randint(25, 50)
    x_coord: float = 0
    y_coord: float = 0
    while i < rand_n:
        make_left_triangle(bob, x_coord, y_coord)
        x_coord = bob.pos()[0]
        y_coord = bob.pos()[1]
        i  = 1
    done()


if __name__ == "__main__":
    main()

Any help on what's going wrong would be greatly appreciated! Thanks

CodePudding user response:

The problem is that the orientation of the bob is preserved between different calls to make_left_triangle. For example, if you draw a triangle ABC:

   C
  / \
 /   \
A-----B

and then move to vertex C you also turn in the direction of CA. So the next time you'll draw a new triangle CAB, which will be drawn over the initial ABC. You need to reset the orientation of the bob at the start of each make_left_triangle call.

  • Related