Skip to content
Advertisement

How can I set boundaries on the screen?

I’m trying to make it so that If the arrow reaches the screen boundary it will go up and turn around continuing the code so that I can create a piece of art. I’ve been looking for a post to answer my problem but I can’t find anything that’s specific to this problem.

import random
from turtle import Screen, Turtle

dots = Turtle()
screen = Screen()
screen.colormode(255)
dots.speed("fastest")
dots.penup()
dots.goto(-350, -350)

# setting x and y-axis:
dots.xcor()
dots.ycor()
WIDTH, HEIGHT = 800, 800
screen.setup(WIDTH, HEIGHT)

color_list = [(250, 246, 243), (211, 154, 98), (53, 107, 131), (235, 240, 244), (177, 78, 33),
              (198, 142, 35), (116, 155, 171), (124, 79, 98), (123, 175, 157), (226, 197, 130), (190, 88, 109),
              (12, 50, 64),
              (56, 39, 19), (41, 168, 128), (50, 126, 121), (199, 123, 143), (166, 21, 30), (224, 93, 79)]

random_color = random.choice(color_list)

for _ in range(100):
    new_random_color = random.choice(color_list)
    dots.dot(20, new_random_color)
    dots.fd(40)

x, y = dots.position

if x < WIDTH:
    if y < HEIGHT:
        dots.undo()  # undo error
        dots.left(180)  # turn around
        dots.forward(10)  # redo movement but in new direction

screen.exitonclick()

Thanks!

Advertisement

Answer

I think what’s missing is just to relocate pointer to starting X axis with Y axis + your interval. Easier way would be to follow similar logic. Allocate your pointer in the beginning with setheading() method then indicate what path to follow.

or

you need to indicate one more goto() method like

new_y = dots.ycor + (interval what you want eg: 50) dots.goto(-350, new_y) and create for loop depending how many rows you need. Personally I’ve done this as follows:

dots = Turtle()
screen = Screen()
screen.colormode(255)
dots.speed("fastest")
dots.penup()
dots.setheading(225)
dots.forward(300)
dots.setheading(0)

random_color = random.choice(color_list)
num_of_dots = 100

for dot_count in range(1, num_of_dots + 1):
    dots.penup()
    dots.dot(20, random.choice(color_list))
    dots.forward(50)

    if dot_count % 10 == 0:
        dots.setheading(90)
        dots.forward(50)
        dots.setheading(180)
        dots.forward(500)
        dots.setheading(0)
Advertisement