How to Draw with Pygame on Your Raspberry Pi
Drawing on the Raspberry Pi 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
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.
Let’s 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:
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:
The frame around our game arena is made of three thin rectangles, two down each side, and one across the top. Here is the code to draw first the top one, and then the left side, and then the right side.
pygame.draw.rect(gameSurface,PURPLE,(16,16,406,2)) pygame.draw.rect(gameSurface,PURPLE,(16,16,2,440)) pygame.draw.rect(gameSurface,PURPLE,(422,16,2,440))
We also use rectangles for the bricks in our game, as you will see later (see “Drawing the Bricks”). The other shape is, obviously, a circle for the ball. You need to tell Pygame to use your canvas gameSurface; which color you want; the X and Y coordinates of the center of the circle; and its radius.
The command to draw a circle looks like this:
Here’s how to draw a blue circle at X=100 and Y=170 with a radius of 40 pixels:
You don’t need the blue circle or the green rectangle for this game, so you can take them out again if you tried them out.