Random Fun and Games: Go Ahead, Take a Chance! 113
How Big Is Our Canvas?
Now that we know how to position spirals at random locations on
the window, or canvas, we have one problem remaining: how do we
know how big our canvas is? We can generate a random number
for the x- and y-coordinates of a location and draw a spiral at that
location, but how can we make sure that the location we choose is
on the visible window—not off the window to the right, left, top, or
bottom? Then, how can we make sure we cover the entire drawing
window, from left to right, top to bottom?
To answer the question about canvas size, we need to use two
more functions, turtle.window_width() and turtle.window_height().
First, window_width() tells us how wide our turtle window is, in pixels.
The same goes for window_height(); we get the number of pixels from
the bottom of our turtle window to the top. For example, our turtle
window in Figure 6-2 is 960 pixels wide and 810 pixels tall.
turtle.window_width() and turtle.window_height() will help us
with random x- and y-coordinates, but we have one more obstacle.
Remember that in turtle graphics, the center of the window is the
origin, or (0, 0). If we just generate random numbers between 0
and turtle.window_width(), the first problem is that we will never
draw anything in the lower left of the window: the coordinates
there are negative in both the x- and y-directions (left and down),
but a random number between 0 and our window_width() value is
always positive. The second problem is that if we start from the
center and go window_width() to the right, we’ll end up off the right-
hand edge of the window.
We have to figure out not just
how wide and tall the window is but
also what the range of the coordi-
nates is. For example, if our window
is 960 pixels wide and the origin
(0, 0) is at the center of our window,
we need to know how many pixels we
can move to the right and left without
leaving the visible window. Because
(0, 0) is in the middle of our window,
halfway across, we just divide the
width in half. If the origin is in the
middle of a window that is 960 pix-
els across, there are 480 pixels to the
right of the origin and 480 pixels to