Creating Sprites using Pygame

This tutorial is the second tutorial in a series of five Pygame tutorials:

Learning Objectives


In this second tutorial on how to create a retro arcade game using PyGame we are looking at creating our first sprite.
definition-sprite

Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould is called a Class.

So by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class and derive our first object from this class.

Context: Car Racing Game


For this tutorial we are looking at creating a car racing game. The user will be able to control the car and move on the road between lanes by using the left and right arrow keys, accelerate or slow down using the up and down arrow keys.

The main car will be an object called playerCar. It will derive from a Class called Car.

Our first Class


So let’s look at the code for our Car Class:
To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first object: the car of the player (playerCar)

So let’s save our class as a python file called car.py.

Our first Object


Now that we have a Class we can create objects from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

Let’s go back to our main.py file (from previous tutorial) to edit its content.

First let’s add at the top of the code an import statement to import our Car class.

#Let's import the Car Class
from car import Car

Then we need to create our sprite in our main program using the following line of code:

playerCar = Car(RED, 20, 30)

Per dafult your car will be on position (0,0) (top left og the screen). You can change the x and y properties of your car as follows:

playerCar.rect.x = 200
playerCar.rect.y = 300

You can see how easy it would be to create another car:

player1Car = Car(RED, 20, 30)
player1Car.rect.x = 200
player1Car.rect.y = 300
player2Car = Car(PURPLE, 20, 30)
player2Car.rect.x = 400
player2Car.rect.y = 400

However, because we are creating a fully working game we are going to do a few more things with this object.

Let’s reuse the code from the first tutorial. We have made a few amendments since to draw the backdrop of our game: A green screen with a grey straight road!

On line 3 notice how we are using the import command to link to our Car Class python file (car.py).

On line 20 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just one sprite, the player car.)

On line 22 we are creating our first sprite/object using the Car Class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, x, y, width and height of the car we want to create.

Now that we have created our first sprite we need to add it to our list of spites: all_sprites_list. This is what happens on line 27.

Finally, within the main program loop, on line 49 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

Here is the full code:

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
                
        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREEN)
        #Draw The Road
        pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per secong e.g. 60
        clock.tick(60)

pygame.quit()

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
PyGame Tutorial 3/5Control your sprite using the arrow keys

Did you like this challenge?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 16

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: , ,