Game Development Reference
In-Depth Information
17 - Graphics and Animation
40))
The
pygame.draw.rect()
function will draw a rectangle. The third parameter is a
tuple of four ints for the left, top, width, and height of the rectangle. Instead of a tuple of four
ints for the third parameter, you can also pass a
Rect
object. In line 45, we want the
rectangle we draw to be 20 pixels around all the sides of the text. This is why we want the
drawn rectangle's left and top to be the left and top of
textRect
minus
20
. (Remember,
we subtract because coordinates decrease as you go left and up.) And the width and height
will be equal to the width and height of the
textRect
plus
40
(because the left and top
were moved back 20 pixels, so we need to make up for that space).
The pygame.PixelArray Data Type
47. # get a pixel array of the surface
48. pixArray = pygame.PixelArray(windowSurface)
49. pixArray[480][380] = BLACK
On line 48 we create a
pygame.PixelArray
object (which we will just call a
PixelArray
object for short). The
PixelArray
object is a list of lists of color tuples
that represents the
Surface
object you passed it. We passed
windowSurface
object
when we called the
PixelArray()
constructor function on line 48, so assigning
BLACK
to
pixArray[480][380]
will change the pixel at the coordinates (480, 380) to be a
black pixel. Pygame will automatically modify the
windowSurface
object with this
change.
The first index in the
PixelArray
object is for the X-coordinate. The second index is
for the Y-coordinate.
PixelArray
objects make it easy to set individual pixels on a
PixelArray
object to a specific color.
50. del pixArray
Creating a
PixelArray
object from a
Surface
object will lock that
Surface
object.
Locked means that no
blit()
function calls (described next) can be made on that
Surface
object. To unlock the
Surface
object, you must delete the
PixelArray
object with the del operator. If you forget to delete the
Surface
object, you will get an
error message that says
pygame.error: Surfaces must not be locked
during blit
.