Game Development Reference
In-Depth Information
first two parameters for
pygame.Rect() are the XY
coordinates of the top left corner. We
want the random coordinate to be
between 0 and the size of the window
minus the size of the food square. If
we had the random coordinate
between 0 and the size of the window,
then the food square might be pushed
outside of the window altogether.
Look at the diagram in Figure 18-4.
The square on the left has an X-
coordinate of its top left corner at
380 . Because the food square is 20
pixels wide, the right edge of the food
square is at 400. (This is because 380
+ 20 = 400.) The square on the right
has an X-coordinate of its top left
corner at 400. Because the food square is 20 pixels wide, the right edge of the food square
is at 420, which puts the entire square outside of the window (and not viewable to the
user).
Figure 18-4: For a 20 by 20 rectangle, having the top left
corner at (400, 200) in a 400 by 400 window would place
the rectangle outside of the window. To be inside, the
top left corner should be at (380, 200) instead.
The third parameter for pygame.Rect() is a tuple that contains the width and height
of the food square. Both the width and height will be equal to the value in the FOODSIZE
constant.
Drawing the Bouncer on the Screen
Lines 71 to 109 cause the bouncer to move around the window and bounce off of the
edges of the window. This code is very similar to lines 44 to 83 of our animation program
in the last chapter, so we will not go over them again here.
111. # draw the bouncer onto the surface
112. pygame.draw.rect(windowSurface, WHITE, bouncer
['rect'])
After moving the bouncer, we now want to draw it on the window in its new position.
We call the pygame.draw.rect() function to draw a rectangle. The
windowSurface passed for the first parameter tells the computer which
pygame.Surface object to draw the rectangle on. The WHITE variable, which has
(255, 255, 255) stored in it, will tell the computer to draw a white rectangle. The
pygame.Rect object stored in the bouncer dictionary at the 'rect' key tells the
position and size of the rectangle to draw. This is all the information needed to draw a
white rectangle on windowSurface .
Search WWH ::




Custom Search