2

I have written some code to place dots all around the screen randomly; however, it does not cover the entire screen:

import turtle
import random

t = turtle.Turtle()

color = ["red", "green", "blue", "pink", "yellow", "purple"]
t.speed(-1)
for i in range(0, 500):
    print(turtle.Screen().screensize())
    z = turtle.Screen().screensize()
    x = z[0]
    y = z[1]
    t.color(color[random.randint(0,5)])
    t.dot(4)
    t.setposition(random.randint(-x,x), random.randint(-y,y))


turtle.done()

output

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Atate75
  • 33
  • 4
  • 2
    `.screensize()` isn't quite what you want here - it works with the size that the display widget *wants* to be, but normally it's constrained to fill the window, so the window's actual size overrides it. Use `.window_width()`, `.window_height` instead. – jasonharper Feb 22 '20 at 23:28

1 Answers1

2

"Screen" refers to the turtle's logical boundaries (scrollable area) which may not be the same as the window size.

Call turtle.setup(width, height) to set your window size, then use the turtle.window_width() and turtle.window_height() functions to access its size.

You could also make sure the screensize matches the window size, then use it as you are doing. Set the screen size with turtle.screensize(width, height).

Additionally, your random number selection is out of bounds. Use

random.randint(0, width) - width // 2

to shift the range to be centered on 0.

Putting it together:

import turtle
import random

turtle.setup(480, 320)
color = ["red", "green", "blue", "pink", "yellow", "purple"]
t = turtle.Turtle()
t.speed("fastest")

for _ in range(0, 100):
    t.color(random.choice(color))
    t.dot(4)
    w = turtle.window_width()
    h = turtle.window_height()
    t.setposition(random.randint(0, w) - w // 2, random.randint(0, h) - h // 2)

turtle.exitonclick()
ggorlen
  • 44,755
  • 7
  • 76
  • 106