Pygame sprite class
Categories: pygame
We introduced sprites in a previous tutorial. No we will look at them in more detail.
Sprites are objects
You will most likely to be familiar with objects in Python. Common examples of objects in Python are lists and strings.
Typically an object has:
- A type. For example a string has type
String
, a list has typeList
. Different types of object behave in different ways. - A creation method. For example you can use
k = [1, 2, 3]
to create a list. - Some data. For example, list can contain a collection of numbers.
- Some functions that belong to that type of object. These functions are called methods. For example, a list has a
clear
method that deletes all the data from the list, soa.clear()
will empty the lista
.
Python allows you to create you own object types. You create a new object type by defining a class. For example we can define a class Ball
that represents a ball sprite. We can then create Ball
objects (that have type Ball
) to use in our game.
When you write a game, you will usually have several different types of sprite, and you would normally create a different class for each type.
A sprite class
Here is a simple sprite class:
class Ball(pg.sprite.Sprite):
def __init__(self, pos):
super(Ball, self).__init__()
self.image = pg.image.load(os.path.join('resources', 'ball.png'))
self.rect = self.image.get_rect()
self.rect.center = pos
def update(self):
pass
This declares a class called Ball
. Within the class definition we include the name pg.sprite.Sprite
, which is a Sprite
class defined by pygame. This just tells Python that the Ball
class is a type of Sprite
(we say it is a subclass of Sprite
). In other words, a Ball
is similar to a default sprite, but it has a few special characteristics that we add in our Ball
code.
The definition includes two methods, __init__
and update
.
You will notice that both methods have self
as the first parameter. This parameter represents the actual object itself.
__init__ method
The __init__
method is a special method that most classes include, which tells Python how to create a new object for the class.
The method takes two parameters:
self
, the object being created.pos
, the initial position of the sprite on the screen.pos
should be a list or tuple with two values,x
andy
that represent the coordinates of the centre of the sprite.
Within the method, we do several things:
- Call
super(Ball, self).__init()__
. OurBall
class is based on theSprite
class, and this call allows theSprite
class to initialise itself. - Set
self.image
. We load the resources/ball.png image file as an image to be used to display the sprite. You will find this file on github with the source code. - Calls
image.get_rect()
to get the rectangular region of the image. The rectangle width and height will be set to match the image size. This is stored inself.rect
. - Set
rect.centre
equal topos
, the position that was passed into the call to__init__
. This positions the rectangle with its centre atpos
. This controls where the sprite will be drawn.
self
here refers to the actual sprite. If you have several ball sprites in your game, each sprite will have its own image
and rectangle
, and self
identifies which one is being changed.
Your code will not call __init__
directly. To create a new Ball
, you use code like this:
ball = Ball((100, 200))
When you call Ball(pos)
, it will automatically call __init__
for the Ball
class. The parameter pos
, which is (100, 200) in our case, will be passed into __init__
. Notice that Ball
only takes one parameter. The self
parameter in the __init__
call is added by Python.
update method
The update
method of Ball
is called in in the main loop. It updates the sprite, for example:
- Moving the sprite (by moving
self.rect
). - Change the sprite image to create animation.
- Checking for collisions with other sprites.
- Deleting the sprite if it is no longer required.
In the implementation above, the update method does nothing, so the sprite will just sit there without moving.
You can call update
like this:
ball.update()
Notice again that in the class definition, update
takes a self
parameter, but when you call update
you don't need to pass a parameter in. Python will automatically add ball
as the first parameter.
In fact, on most cases, you won't call update on the sprite directly. If the sprite is part of a group, you can just update the group:
group.update()
Thsi will call update on every sprite in the group.
Sprite class summary
For a sprite class you should do the following:
- Derive the class from
pg.sprite.Sprite
as shown above. - Create an
image
member that holds the image that controls the appearance of the sprite. - Create a
rect
member that has the same size as the image, and is positioned wherever you want the sprite to appear. - Implement an
update
method.
This is the minimum you must do. Of course, you can also add extra members and methods as you need to.
See also
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added:
Popular tags
2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest