PyGame Sprite Animation Tutorial – Simple Walk Loop

Hi everyone, I hope you liked the last post about Installation of PyGame. Today we will learn a little more, in this PyGame Sprite Animation Tutorial. So it is clear from the name itself that we are going to draw a character inside the window, and we will make the character walk. I hope you already know about 2d Animation. The basic concept is we draw images in a loop creating an illusion of movement.

With PyGame making sprite animation is super easy. The hard part is creating the sprite 😉 but don’t worry I have the sprites for you.

What is Sprite?

In computer graphics any bitmap that is drawn in our game window is called a Sprite. So if you do not like the name “Sprite”, you can consider it the image that you are going to draw in your game.

Designing a Sprite

As I told you this is the hard part, so for designing a sprite you can use any tool available there for example photoshop, illustrator etc. Just google it and you will find a lot of online tools as well.

But don’t worry, for following this tutorial you do not need to design a character, I have a sprite for you, and it is for walking cycle.

Download Sprites

I found the above sprite from here: Game Art 2D. You can find some good free game assets from here.

PyGame Sprite Animation

Now let’s learn how we can implement the sprite animation using pygame.

Creating a new Project

  • Just create a new folder anywhere in your computer. I have created a folder named MyFirstSprite.
  • Inside the folder MyFirstSprite, create one more folder named images. And paste all the sprite images that you downloaded.
pygame sprite animation
PyGame Sprite Animation
  • Now inside the same folder (not inside images, inside MyFirstSprite folder) create a new file named game.py.
  • Open the file in any code editor, I am using Visual Studio Code.

Importing PyGame and Defining Constants

  • On the top of the file game.py write the following code.

  •  So we have imported pygame and also defined some constants. You can change the values if you want.

Creating our Sprite

  • For our sprite we will create a class. So below I have my class named MyFirstSprite, you have to write the same code.

  • The above code is pretty much self explanatory, and I have also added the comments. But still if you think you are not getting something, please leave your comment.

Drawing the Sprite

  • Now let’s draw the sprite that we created.

  • Now finally we need to call main.

The final Code

  • After doing everything your file game.py will be like this.

  • Now just run your code and you will see the chracter moving.
pygame sprite animation
PyGame Sprite Animation

So that’s all for this PyGame Sprite animation tutorial friends, let me know in comments if you are having any query. Thank You 🙂

Leave a Comment