In this lesson, you’ll replace all those boring white rectangles with some cooler images that will make the game feel like an actual game.
Earlier, you learned that images on disk can be loaded into a
Surface with some help from the
image module. For this tutorial, we made a little jet for the player and some missiles for the enemies. You’re welcome to use this art. You can click the link below to download the art used in this tutorial:
Sample Code: Click here to download the source code for the PyGame sample project used in this tutorial.
Before you use images to represent the player and enemy sprites, you need to make some changes to their constructors. The code below replaces the code used previously:
7 # Import pygame.locals for easier access to key coordinates 8 # Updated to conform to flake8 and black standards 9 from pygame.locals import ( 10 RLEACCEL, 11 K_UP, 12 K_DOWN, 13 K_LEFT, 14 K_RIGHT, 15 K_ESCAPE, 16 KEYDOWN, 17 QUIT, 18 ) 19 20 # Define constants for the screen width and height 21 SCREEN_WIDTH = 800 22 SCREEN_HEIGHT = 600 23 24 # Define the Player object by extending pygame.sprite.Sprite 25 # Instead of a surface, use an image for a better-looking sprite 26 class Player(pygame.sprite.Sprite): 27 def __init__(self): 28 super(Player, self).__init__() 29 self.surf = pygame.image.load("images/jet.png").convert() 30 self.surf.set_colorkey((255, 255, 255), RLEACCEL) 31 self.rect = self.surf.get_rect()
Here’s what similar changes to the
Enemy look like:
54 # Define the enemy object by extending pygame.sprite.Sprite 55 # Instead of a surface, use an image for a better-looking sprite 56 class Enemy(pygame.sprite.Sprite): 57 def __init__(self): 58 super(Enemy, self).__init__() 59 self.surf = pygame.image.load("images/missile.png").convert() 60 self.surf.set_colorkey((255, 255, 255), RLEACCEL) 61 self.rect = self.surf.get_rect( 62 center=( 63 random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100), 64 random.randint(0, SCREEN_HEIGHT), 65 ) 66 ) 67 self.speed = random.randint(5, 20)
For more information about loading images and
RLEACCEL, check out the following resources from the
Comments & Discussion
Become a Member to join the conversation.