1

I have to make a change to this specific code, which produces a square grid of circles, I have to change the code to make a triangle grid of circles.

import turtle
window = turtle.Screen()
my_boi = turtle.Turtle()
my_boi.speed(0)
for y in range(-200,200,50):
    for x in range(-200,200,50):
       my_boi.penup()
       my_boi.setposition(x,y)
       my_boi.pendown()
       my_boi.circle(20)
window.exitonclick()
MAO3J1m0Op
  • 423
  • 3
  • 14

3 Answers3

2

I'm sure there is a smarter approach, but this is one way to do it:

import turtle
window = turtle.Screen()
my_boi = turtle.Turtle()
my_boi.speed(0)

for (i,y) in enumerate(range(-200,200,50)):
    for x in range(-200+(25*i),200-(25*i),50):
       my_boi.penup()
       my_boi.setposition(x,y)
       my_boi.pendown()
       my_boi.circle(20)

window.exitonclick()

turtle.done()

In the second for-loop the range is iteratively decreased by 1/2 of the circle diameter in each side.

0

I'd simplify things somewhat:

from turtle import Screen, Turtle

window = Screen()

my_boi = Turtle()
my_boi.speed('fastest')
my_boi.penup()

for y in range(1, 9):
    my_boi.setposition(-25 * y + 25, 50 * y - 250)

    for x in range(y):
        my_boi.pendown()
        my_boi.circle(20)
        my_boi.penup()
        my_boi.forward(50)

my_boi.hideturtle()
window.exitonclick()

Only the starting position of each row has to be calculated and placed via setposition(). The column positions can be a simple forward() statement.

cdlane
  • 40,441
  • 5
  • 32
  • 81
0

I know this is an old post, but I was looking for the answer and managed to figure it out, so to help everyone else out, All you need to do is change the stop range in the nested loop to be y. I switched the x and y variables because I wanted the triangle to be flat, but if you need it the other way that also works.

    import turtle
    window = turtle.Screen()
    my_boi = turtle.Turtle()
    my_boi.speed(0)
    for x in range(-200,200,50):
        for y in range(-200,x,50):
            my_boi.penup()
            my_boi.setposition(x,y)
            my_boi.pendown()
            my_boi.circle(20)
    window.exitonclick()
Answer
  • 1