Pygame References
Here is a quick reference guide for things commonly done in Pygame. You can also find the Graphics Template at the bottom. This is a quick reference. It is expected that you have completed the relevant topics for specific details.
Events in Pygame
There are a number of events in Pygame that you may want to listen for. Here is an example of an event loop with many of the events covered in this course. There are other events that are not shown here (see the link below for more).
for event in pygame.event.get():
if event.type == pygame.QUIT: # User clicks on the x in the game window
# Code here to end program
elif event.type == pygame.KEYDOWN: # User presses down on a key
if event.key == pygame.K_LEFT:
# Code here for left arrow pressed
elif event.key == pygame.K_RIGHT:
# Code here for right arrow pressed
elif event.type == pygame.KEYUP: # User releases a key
if event.key == pygame.K_LEFT:
# Code here for left arrow released
elif event.key == pygame.K_RIGHT:
# Code here for right arrow released
elif event.type == pygame.MOUSEMOTION: # User moves the mouse
# Code for when mouse moves
elif event.type == pygame.MOUSEBUTTONDOWN: # User clicks a mouse button
# Code for when a mouse button is clicked
You can see all of the events Pygame listens for here:
https://www.pygame.org/docs/ref/event.html
You can use this like to see all of the key codes for Pygame:
Mouse Control
See Events for how to detect an event from the mouse.
Here is the official documentation for pygame.mouse:
https://www.pygame.org/docs/ref/mouse.html
Make the cursor invisible/visible:
pygame.mouse.set_visible(False) # Hides the cursor
pygame.mouse.set_visible(True) # Shows the cursor
Get the coordinates of the cursor:
mouse_pos = pygame.mouse.get_pos() # mouse_pos is a tuple containing the mouse location
# mouse_pos[0] contains the x coordinate
# mouse_pos[1] contains the y coordinate
Set the coordinate of the cursor:
pygame.mouse.set_pos([x, y])
Working with Images Loaded from Files
This assumes that all image files are in the same directory as the .py file. If not, you must specify the folder that they are in as well. When you load an image file into your program, it is stored as a Surface. Here is the documentation for Surface:
https://www.pygame.org/docs/ref/surface.html
Load an Image from a File
Note that the image size will be the same as it is in the file. If you want it to be a particular size, you will need to re-size it.
player_image = pygame.image.load(“image filename including extension”).convert()
#This following line will load an image with a transparencies
player_image = pygame.image.load(“image filename including extension”).convert_alpha()
size = player_image.get_size() # Gets the size of the Surface
# size[0] is the width, size[1] is the height
player_rect = player_image.get_rect() # Gets a rectangle encompassing this Surface, located
# at (0, 0)
Draw an Image
In this example screen is the Surface that you created for your game window and player_image is the image you wish to draw, and [x, y] is the coordinate location at which you will draw the image.
screen.blit(player_image, [x, y])
Re-Size an Image
player_image = pygame.transform.scale(player_image, (width, height))
If you scale the same Surface multiple times you may see distortion of the image. To fix this, you may need to reload the image file before scaling. Only do this if necessary as it negatively effects performance.
player_image = pygame.image.load("filename").convert()
playerImage = pygame.transform.scale(player_image, (width, height))
Image Transparencies
There are two ways to make parts of an image transparent.
Method 1 - Setting a Colorkey (better performance)
This method allows you to specify a specific color that will be made transparent (via RGB values). You need to know the RGB value of the parts of the image you want transparent. We will use MAGENTA so that all colors that are MAGENTA (255, 0, 255) will be made transparent. You may use whatever color you like.
MAGENTA = (255, 0, 255) # Set this value with all of your colors at the top of your program
player_image = pygame.image.load(“filename”).convert()
player_image.set_colorkey(MAGENTA)
Method 2 - Using an Image File with Transparency
This method allows you to just use an image file with transparent parts. The only drawback is a slight hit on performance. In a small game it should not be an issue. Simply change .convert() to .convert_alpha() when you load the image.
player_image = pygame.image.load(“filename”).convert_alpha()
Adding Sounds
There are two ways to play sounds. Choose which one best suits your needs.
Mixer.Sound
Use this for small sound effects that will be played multiple times. You can have multiple sound effects play at the same time.
Step 1: Load the Sound File (once before the game loop)
sound_effect_1 = pygame.mixer.Sound("sound filename with extension")
Step 2: Play the Sound (each time you want to play the sound)
sound_effect_1.play()
Mixer.Music
Here is the official documentation:
https://www.pygame.org/docs/ref/music.html
Use this for background music. You can only play one sound through Mixer.Music at a time.
Step 1: Load the Sound File (once before the game loop)
pygame.mixer.music.load('RockOn.mid')
Step 2: Play the Sound
# The first argument is the number of times to play the sound, 0 is repeat
# The second argument is the position where the music starts playing
pygame.mixer.music.play(0, 0.0)
pygame.mixer.music.stop()
Drawing Text
There are three things you need to do in order to draw text.
Step 1 - Create a SysFont Object
https://www.pygame.org/docs/ref/font.html#pygame.font.SysFont
text_font = pygame.font.SysFont('Calibri', 25, True, False)
Step 2 - Make the Text to Display
https://www.pygame.org/docs/ref/font.html#pygame.font.Font.render
text = text_font.render("This text will be displayed", True, BLACK)
Step 3 - Draw the Text to the Screen (to be done in the drawing part of the game loop)
screen.blit(text, [250, 250]) # The text from Step 2 will be drawn at (250, 250)
Collision
A Coordinate Colliding with a Rectangle
https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint
The method collidepoint() returns true if a coordinate is inside a rectangle named target and false otherwise.
target = pygame.Rect(10, 10, 50, 50) # a Rect object must be used
if target.collidepoint(15, 15): # An x and y value of the coordinate
# Collision code here
else:
# No collision code here (if any)
A list or tuple can also be used to represent the coordinate instead of two integers.
point = [15, 15]
if target.collidepoint(point): # An x and y value of the coordinate
# Collision code here
else:
# No collision code here (if any)
Two Rectangles Colliding
https://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect
You must have two Rect objects to use colliderect(). The method colliderect() returns true if target and player rectangles intersect, and false otherwise.
First, you need to have two Rect objects:
target = pygame.Rect(10, 10, 50, 50) # We need to have two Rect objects
player = pygame.Rect(25, 25, 10, 10)
if target.colliderect(player):
# Collision code here
else:
# No collision code here (if any)
A Rectangle Contains another Rectangle
https://www.pygame.org/docs/ref/rect.html#pygame.Rect.contains
You must have two Rect objects to use contains(). The method contains() returns true if player is entirely inside target, and false otherwise.
First, you need to have two Rect objects:
target = pygame.Rect(10, 10, 50, 50) # We need to have two Rect objects
player = pygame.Rect(25, 25, 10, 10)
if target.contains(player):
# Code for when player is contained within target here
else:
# Target does not fully contain player
Drawing Shapes
You can also visit the official documentation for more details:
Graphics Template
Source: http://programarcadegames.com/