Home > Enterprise >  4 triangles to be aligned vertically
4 triangles to be aligned vertically

Time:11-10

so I'm working on a program where i want the output to have 4 triangles with the lengths 20,40,60,80 placed vertically where the top of each triangle should be exactly halfway along the baseline of the triangle above.

I have managed to get the first two triangles correct but cannot get the top two to align the way I want. I know I am going wrong somewhere but i cannot seem to see it

from turtle import *
NUMBER_OF_SHAPES = 4

for shape in range(1, NUMBER_OF_SHAPES   1):
    #Draw a Triangle
    for sides in range(3):
        forward(20 * shape)
        left(120)
        
   #Move forward to start position of next triangle
    penup()
    left(120)
    forward(20 * shape)
    right(120)
    pendown()

CodePudding user response:

from turtle import *
import time
NUMBER_OF_SHAPES = 4

for shape in range(1, NUMBER_OF_SHAPES   1):
    #Draw a Triangle
    for sides in range(5): #redraw some edges to place the cursor on the top 
        forward(20 * shape)
        left(120)
        
   #Move forward to start position of next triangle
    penup()
    right(60)
    forward(10 * (shape 1)) # half of the size of the next triangle
    right(180)
    time.sleep(0.5)
    pendown()

CodePudding user response:

Think outside the triangle:

from turtle import *

for length in range(20, 100, 20):
    penup()
    sety(length   ycor())
    pendown()

    circle(-2*length/3, steps=3)

hideturtle()
exitonclick()

Here were using turtle's circle() method to achieve two goals, first to draw a triangle, steps=3, and second to draw centered triangles starting from their top point by using a negative radius. Beyond that we simply need to adjust the vertical position.

enter image description here

As far as your code, I believe the problem is simpler than you're trying to make it. Things get easier if we start by moving forward half the length of the triangle, and then build from there:

from turtle import *

NUMBER_OF_SHAPES = 4

for shape in range(1, NUMBER_OF_SHAPES   1):
    forward(10 * shape)

    for _ in range(4):
        left(120)
        forward(20 * shape)

    right(120)

exitonclick()

This, in combination with reversing the order of the steps in the loop, and increasing iterations to 4, leaves us centered for the next triangle.

  • Related