O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Drawing with Pygame

Drawing on the screen has two stages. The first is that you draw onto the canvas (or surface object), and the second is that you update the screen with those changes. To make the window background white, use

gameSurface.fill(WHITE)

pygame.display.update()

tip.eps You don’t need to update the display for every drawing instruction. Your program runs more quickly (and often looks more professional) if you wait until you’ve finished all your drawing instructions and then update the screen just the once.

In our game, we’re going to use two shapes. The first is a rectangle. To draw a rectangle, you need to specify the surface object you are drawing on, which will be our canvas gameSurface; the color; the X coordinate of the rectangle’s top-left corner; the Y coordinate of the rectangle’s top-left corner; and its width and height. The coordinates are measured from the top-left corner of the window, so X values get higher as you cross the screen from left to right, and Y values get higher as you go down the screen.

The command to draw a rectangle looks like this:

pygame.draw.rect(object,color,(x,y,width,height))

Imagine you wanted to draw a green rectangle that was 150 pixels wide by 75 pixels high, and you wanted to put it at the coordinate X=30, Y=90. Here’s how you’d do that:

pygame.draw.rect(gameSurface,GREEN,(30,90,150,75))

The frame around our game arena (see Figure 13-1 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required