Setting boundaries on the screen and having object show up within the boundaries

Viewed 30

I'm trying to make a dot pop up on a screen at a random point. I set the screen boundaries, but when I use those boundaries to choose a random number, the number is sometimes too large and does not show up on the screen. What can I do to fix this? My code is below. import turtle import random import time

# screen
screen = turtle.Screen()
screen.title("Moving Block")
screen.bgcolor("white")
screen.setup(width=1920, height=1080)
width = 1920
height = 1080

# dot
dot = turtle.Turtle()
dot.shape("circle")
dot.color("black")
dot.penup()
dot.turtlesize(0.5,0.5)

# 2 seconds rest before beginning
time.sleep(2)

# display dot 
counter = 0 
while counter < 5:
    dot.hideturtle()
    # position
    time.sleep(1)
    x = random.randrange(int(width/2*-1), int(width/2))
    y = random.randrange(int(height/2*-1), int(height/2))
    dot.setpos(x,y)
    print(x, y)
    dot.showturtle()
    time.sleep(3)
    counter += 1 
1 Answers

Part of the screen height is allocated under the title and the screen can also have scrollbars, which also takes away the height and width. It's better to set the width and height like this:

width = screen.window_width()
height = screen.window_height()

Since there are different sizes of monitors, it is better to use relative sizes.

screen.setup(width=0.9, height=0.9)

If you don't want your program to "sleep" all the time, use .ontimer()

Related