In this adventure, you’ll learn how to use images with Python and PyGame
. During previous adventures you’ve used PyGame
’s drawing functions to draw shapes. You’ve discovered how flexible this is and how much it allows you to do, but it can’t do everything! Sometimes you will want to use images from other programs instead of drawing them with code.
During this adventure, you’ll create programs to load and layer images. You’ll create a program that lets you add a moustache to any image and another program to move a sprite around the window, which forms the basis of a game.
The first thing you’ll do in this adventure is learn how to load and display an image. Before you can start, you’ll need to save your chosen images into the folder that the program will be saved in. In this adventure I’ve chosen the images for you. To download these images, follow the steps given in the Appendix.
Finished? Once you have the images, copy all of them into the Adventure 8
folder.
The first images you will be using are catSmall.png
, catLarge.png
, hat.png
and space.png
. Make sure they are in the Adventure 8
folder; if they aren’t then make sure you follow the steps in the Appendix. If they are in the correct place then you may begin.
This program will display a picture of a cat. The program loads an image into Python using PyGame
and displays it in a new window.
loadImage.py
in the Adventure 8
folder.PyGame
window:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
load()
function and placed onto the window using the blit()
function. Add this code to your program now:
image = pygame.image.load('catLarge.png')
screen.blit(image, (0, 0))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
pygame.quit()
You’re now going to give your cat a hat. To do this, you need a program that uses two images, one of a cat and the other of a hat, which are loaded from files. The cat’s face is placed on the background of the window, and the hat is placed on top of it. The position of the hat is set in the program. This program shows you how to layer images on top of each other.
Time to get started:
layeredImage.py
in the Adventure 8
folder.PyGame
window:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
cat = pygame.image.load('catLarge.png')
hat = pygame.image.load('hat.png')
x = 0
y = 0
screen.blit(cat, (x + 10, y + 50))
screen.blit(hat, (x + 7, y))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
pygame.quit()
There is no limit to the number of images you can blit to the PyGame
window surface. Images will stay on the surface, meaning that you can blit images on top of each other.
The images will stay on the surface until you fill the surface with a colour or place another image over the top of it—you’ll cover that later in this adventure.
Next, you’re going to layer images randomly all over the window surface. The end result should look something like Figure 8-3. The images layer on top of each other because you never refresh the background and, just to maximize the randomness, you’re going to rotate each image by a random angle.
randomImages.py
in the Adventure 8
folder.PyGame
window:
import random
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
image = pygame.image.load('catSmall.png')
bg = pygame.image.load('space.png')
screen.blit(bg, (0, 0))
done = False
while not done:
x = random.randint(0, windowSize[0])
y = random.randint(0, windowSize[1])
angle = random.randint(0, 360)
rotatedImage = pygame.transform.rotate(image, angle)
screen.blit(rotatedImage, (x, y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(10)
pygame.quit()
You can create some really cool programs by using images and the mouse. You’re now going to use the mouse to put a moustache on the cat’s face, as in Figure 8-4. This program combines code from the programs you’ve already created in this adventure and in Adventure 7 when you learned how to use a mouse with PyGame
. Why not try using a picture of your own instead of the cat image?
Time to get started:
moustache.py
in the Adventure 8
folder.PyGame
window:
import pygame
pygame.init()
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
background = pygame.image.load('catLarge.png')
moustache = pygame.image.load('moustache.png')
black = pygame.color.Color("#000000")
bgPos = (0, 0)
pos = (0, 0)
screen.blit(background, bgPos)
done = False
while not done:
event for
loop checks if the mouse has been clicked. If it has, it will refresh the window’s background and place the moustache image where the mouse was clicked. Add this code now:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
screen.fill(black)
screen.blit(background, bgPos)
screen.blit(moustache, pos)
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
pygame.quit()
In 2D computer games, the player and other characters in the game often have collections of images for all their movement and actions. These are called sprites. When combined in animations, the collection of images make the sprite look like it’s moving. In this part of the adventure, you’ll learn how to make basic sprite animations using images in PyGame
.
In these programs, you will use the image functions that you’ve already learned in this adventure to make animations for sprite movement.
The first program will allow the sprite to move in one direction. You’ll then build on top of that to allow it to move in all directions. Finally, you’ll add an awesome teleportation animation.
Let’s get going on the first part of the program, in which you create a sprite that can walk down the window when the s key is pressed (see Figure 8-5). Animations are a necessary part of games. They help the players understand what is going on in the game and make the game more interactive than just using single images. For example, walking animations help make player movement look more relatable to players.
The sprite you will be using in this program is an adventurer with a hat and a beard. The sprite is similar in size to some classic modern adventure games. With the knowledge you gain in this chapter and later chapters, you could develop this program or even further to turn it into a full game.
walkingSprite.py
in the Adventure 8
folder.PyGame
:
import pygame
pygame.init()
count
variable and, depending on its value, it returns one of the two images in the animation:
def move(image1, image2):
global count
if count < 5:
image = image1
elif count >= 5:
image = image2
if count >= 10:
count = 0
else:
count += 1
return image
PyGame
window. Add it to the file editor:
windowSize = [400, 300]
screen = pygame.display.set_mode(windowSize)
clock = pygame.time.Clock()
standing = pygame.image.load('standing.png')
down1 = pygame.image.load('down1.png')
down2 = pygame.image.load('down2.png')
white = pygame.color.Color("#FFFFFF")
count
, x
and y
variables. The count
variable is used in the animations for timing the changes between images. As usual, the x
and y
variables are used to record the position of the sprite:
count = 0
x = 0
y = 0
done = False
while not done:
screen.fill(white)
keys = pygame.key.get_pressed()
move()
function:
#player movement
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
else:
image = standing
screen.blit(image, (x, y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(32)
pygame.quit()
Next it’s time to expand your program. In the previous part, you made it so that the sprite could walk downwards. In this part you’ll add code so that the sprite can walk in all directions (see Figure 8-6).
walkingSprite.py
.down1 = pygame.image.load('down1.png')
down2 = pygame.image.load('down2.png')
up1 = pygame.image.load('up1.png')
up2 = pygame.image.load('up2.png')
left1 = pygame.image.load('side1.png')
left2 = pygame.image.load('side2.png')
right1 = pygame.transform.flip(left1, True, False)
right2 = pygame.transform.flip(left2, True, False)
if
statement that looks like this:
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
else:
image = standing
elif
statements shown in bold here:
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
elif keys[pygame.K_w]:
image = move(up1, up2)
y -= 1
elif keys[pygame.K_a]:
image = move(left1, left2)
x -= 1
elif keys[pygame.K_d]:
image = move(right1, right2)
x += 1
else:
image = standing
To finish off this program, you’re now going to add a final animation that teleports your sprite to a new location when you press the space bar, as in Figure 8-7. You might use this in a game when your player needs to quickly move from one location to another or steps on a portal.
To get this to work, the program will add an animation for the teleportation and set the coordinates of the sprite to a new random location. While this happens, movement with the keyboard will be locked so that no unexpected bugs can occur.
walkingSprite.py
file open in IDLE.import random
right1 = pygame.transform.flip(right1, True, False)
right2 = pygame.transform.flip(right2, True, False)
teleport1 = pygame.image.load('teleport1.png')
teleport2 = pygame.image.load('teleport2.png')
teleport3 = pygame.image.load('teleport3.png')
count = 0
x = 0
y = 0
locked = False
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
elif keys[pygame.K_w]:
image = move(up1, up2)
y -= 1
elif keys[pygame.K_a]:
image = move(left1, left2)
x -= 1
elif keys[pygame.K_d]:
image = move(right1, right2)
x += 1
else:
image = standing
count = 0
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
elif keys[pygame.K_w]:
image = move(up1, up2)
y -= 1
elif keys[pygame.K_a]:
image = move(left1, left2)
x -= 1
elif keys[pygame.K_d]:
image = move(right1, right2)
x += 1
elif keys[pygame.K_SPACE]:
locked = True
else:
image = standing
count = 0
if
statement to the code and indent it so that it won’t run if the locked if
statement is True
. This will stop the players from moving with the direction keys while they are teleporting:
if not locked:
#player movement
if keys[pygame.K_s]:
image = move(down1, down2)
y += 1
elif keys[pygame.K_w]:
image = move(up1, up2)
y -= 1
elif keys[pygame.K_a]:
image = move(left1, left2)
x -= 1
elif keys[pygame.K_d]:
image = move(right1, right2)
x += 1
elif keys[pygame.K_SPACE]:
locked = True
else:
image = standing
count = 0
else
statement that runs the teleport animation and teleports the player to a random location:
else:
if count < 5:
image = teleport1
elif count < 10:
image = teleport2
elif count < 15:
image = teleport3
else:
x = random.randrange(0, windowSize[0])
y = random.randrange(0, windowSize[1])
count = 0
locked = False
count += 1
Python Command Quick Reference Table |
|
Command |
Description |
|
This function is used by |
|
Blit is used to place images onto a |
|
The |
|
Like the |
Achievement Unlocked: Rising star of images in PyGame
.