Draws a rectangular shape on the Surface.
Example 1
pygame.draw.rect(screen, WHITE, [100, 100, 400, 300], 2)
This example will draw a rectangle as a line
Keep in mind
The Surface.fill() method works just as well for drawing filled rectangles.
Example 2
pygame.draw.rect(screen, WHITE, [100, 100, 400, 300])
This example will draw a rectangle that is filled in.
Some other pygame modules for drawing shapes
pygame.draw.polygon - draw a shape with any number of sides
pygame.draw.circle - draw a circle around a point
pygame.draw.ellipse - draw a round shape inside a rectangle
pygame.draw.arc - draw a partial section of an ellipse
pygame.draw.line - draw a straight line segment
pygame.draw.lines - draw multiple contiguous line segments
Practice 1
1. Create a window (800 x 600 pixels);
2. Set background image;
3. Create blue rectangle (100 x 100 pixels) at the center of the window.
Moving the object with keyboard
In order to move your object within pygame you will need to find out whether the user has pressed a certain key or not from the value of the event’s key property.
pygame.key - pygame module to work with the keyboard. This module contains functions for dealing with the keyboard.
The event queue gets pygame. KEYDOWN and pygame.KEYUP events when the keyboard buttons are pressed and released. Both events have a key attribute that is a integer ID representing every key on the keyboard.
Below is the script to move a square in the right or the left direction on the display screen.
# First initialize MOVE_LEFT or MOVE_RIGHT directions
MOVE_RIGHT = 1
MOVE_LEFT = 2
DIRECTION = 0
# put inside loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction=left
elif event.key == pygame.K_RIGHT:
direction=right
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
direction=0
elif event.key==pygame.K_RIGHT:
direction=0
if direction==left:
x-=1
elif direction==right:
x+=1
Practice 2
Continue the script above and move object UP and DOWN;
Hint: use event.key = pygame.K_UP, event.key = pygame.K_DOWN
Keep in mind
It is not possible to change a .jpg to another format just by renaming the file extension to .png. It is still a .jpg even if you call it something different. It requires conversion in a graphics program to change it to a different format.
Literacy
1. What is the difference between adding background image and character image?