Simple Animation In Pygame

Here I’m going to show you how to make a simple animation in Pygame. Let’s get started.

Normally, every game in Pygame starts like this

import pygame, sys, time
from pygame.locals import *

# set up pygame
pygame.init()

# set up window
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
# create a window object (not screen object)
window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
pygame.display.set_caption('Animation') # set window title

# ....

# game loop
while True:
     for event in pygame.event.get():
          if event.type == QUIT:
               pygame.quit()
               sys.exit()
     pygame.display.update()

First we initialize Pygame, then we create a window_surface with size 400×400, and the title is ‘Animation’

Start the game loop, pygame.event.get return a list of events, end we check if user clicks on ‘x’ button. If they do, event.type == QUIT will return True. You may not know where QUIT comes from, it comes from pygame.locals. Finally, with each loop, we update the screen (not the window). pygame.display.update will get everything from window_surface and display it. But keep in mind that we don’t draw on the screen, because it’s too slow, what we will do is we draw on the window_surface, and when we finish drawing, we display it. Because changing objects in memory is way more faster than changing things that already displayed on the screen.
If you run the code above, you’ll get this:

capture

By default, window_surface background color is black, you can change this by using fill() method.

Replace #…. with the code below:

DOWN_LEFT = 1
DOWN_RIGHT = 2
UP_LEFT = 3
UP_RIGHT = 4
MOVEMENT_SPEED = 4

BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

b1 = {'rect': pygame.Rect(300, 80, 50, 100), 'color':RED, 'dir':UP_RIGHT}
b2 = {'rect': pygame.Rect(200, 200, 20, 20), 'color':GREEN, 'dir':UP_LEFT}
b3 = {'rect': pygame.Rect(100, 150, 60, 60), 'color':BLUE, 'dir':DOWN_LEFT}
blocks = [b1, b2, b3]

What we’re going to do is create three boxes, with three different colors: red, green, blue, moving in different ways. The first box, initialized at position (left, top) = (300, 80), width = 50 and height = 100, color is RED and direction = UP_RIGHT. Same goes for b2 and b3. After creating three boxes, we put them in to a list, so that we can draw all of them by using a loop.

Put this code inside the game loop, same intended level with for loop to get events.

    window_surface.fill(BLACK) # set background color of window to black

    for b in blocks:
        # move the block
        if b['dir'] == DOWN_LEFT:
            b['rect'].left -= MOVEMENT_SPEED
            b['rect'].top += MOVEMENT_SPEED
        if b['dir'] == DOWN_RIGHT:
            b['rect'].left += MOVEMENT_SPEED
            b['rect'].top += MOVEMENT_SPEED
        if b['dir'] == UP_LEFT:
            b['rect'].left -= MOVEMENT_SPEED
            b['rect'].top -= MOVEMENT_SPEED
        if b['dir'] == UP_RIGHT:
            b['rect'].left += MOVEMENT_SPEED
            b['rect'].top -= MOVEMENT_SPEED

        # check out of bound
        if b['rect'].top < 0: # over the top of window                                       
            if b['dir'] == UP_LEFT:                                                   
                b['dir'] = DOWN_LEFT                                      
            if b['dir'] == UP_RIGHT:                                                   
                b['dir'] = DOWN_RIGHT                           
        if b['rect'].bottom > WINDOW_HEIGHT: # below the bottom of window
            if b['dir'] == DOWN_LEFT:
                b['dir'] = UP_LEFT
            if b['dir'] == DOWN_RIGHT:
                b['dir'] = UP_RIGHT
        if b['rect'].left < 0: # out of left side                                       
            if b['dir'] == DOWN_LEFT:                                                  
                b['dir'] = DOWN_RIGHT                                       
            if b['dir'] == UP_LEFT:                                                   
                b['dir'] = UP_RIGHT                           
        if b['rect'].right > WINDOW_WIDTH: # out of right side
            if b['dir'] == DOWN_RIGHT:
                b['dir'] = DOWN_LEFT
            if b['dir'] == UP_RIGHT:
                b['dir'] = UP_LEFT
        # draw the block onto the surface
        pygame.draw.rect(window_surface, b['color'], b['rect'])
        time.sleep(0.02) # pause 0.02 second

We draw all the boxes we create earlier on the window_surface, but before we do that, we calculate their direction and check if they’re out of bound. Pygame uses Cartesian coordinate system, but the origin is not at the bottom left corner, instead, it’s located at the top left corner of the screen. Like this:

computer_coordinates_2d

The first four if is used to move the blocks base on their direction, the second four if is used to check if a block is out of bound. If it is, update its direction base on its current direction.
Final result (screenshot): three boxes bouncing around inside the window.

capture

Feel free to donate

Advertisements