Creating Pygame Games (for the complete Noob
 
 
Hosted By
Web Hosting by iPage
 
 
 

Animation in Pygame

Animation is, very simply, pictures in a sequence to form the illusion of movement, as in a flipbook. To show you the basic idea, we are going to get the world spinning. We are going to accomplish this by using transform functions from the Pygame library. try adding this underneath the line graphic = pygame.image.load("world.png").convert():

graphic2 = pygame.transform.rotate(graphic, 90)
graphic3 = pygame.transform.rotate(graphic, 180)
graphic4 = pygame.transform.rotate(graphic, 270)
graphics = graphic, graphic2, graphic3, graphic4 #put graphics in list container
index = 0 #set a variable to loop through list

If you run your program at this point you won't see a difference, but I want you to understand the above commands before we continue. pygame.transform.rotate() takes two arguments; the surface(in this case our graphic) and the degree you want it rotated. It will return your surface counter-clockwise for positive numbers and clockwise for negative. Then we make a list of our graphics so that it is easy to run through them with the index variable in the next line.

Next lets change the screen.blit() function in the main running loop to read:

screen.blit(graphics[index], (0,0)) #Display image at index at top left

and then all we need is some conditional statements to make index count 0, 1, 2, 3 and then return to 0(because if you remember, that is how the index of the list is numbered). Put this at the end of the running loop:

if index == len(graphics) - 1: #if index reaches end of list, set back to 0
    index = 0
else: #otherwise increment index by 1
     index += 1

If you run this, you will immediately notice a problem. It is spinning almost too fast to tell! The solution to this is making use of pygame.time(). Place this at the top of your running loop:

pygame.time.delay(100)

If you have all your whitespace correct, this program should run and you should see a spinning graphic on the screen. If you are using the world graphic, you will see that it would have looked alot better if we had spent the time and drawn a couple different pictures of different views of the world. But hopefully we managed to kill two birds with one stone here, though, by learning the transform.rotate() function which you should be able to apply to all the transform functions, given their descriptions here.

 

 
Recommended Books

 

 
 

Pygame Tutorial on drawing different shapes

Pygame Tutorial on Loading and Manipulating Images / Graphics

Contact Me