Working with Images in Pygame

Loading an image

ship = pg.image.load('images/ship.bmp')

Getting the rect object from an image

ship_rect = ship.get_rect

Positioning an image

With rects, it’s easy to position an image wherever you want on the screen, or in relation to another object. The following code positions a ship object at the bottom center of the screen.

ship_rect.midbottom = screen_rect.midbottom

Drawing an image to the screen

Once an image is loaded and positioned, you can draw it to the screen with the blit() method. The blit() method acts on the screen object, and takes the image object and image rect as arguments.

# Draw ship to screen. 
screen.blit(ship, ship_rect)

The blitme() method

Game objects such as ships are often written as classes. Then a blitme() method is usually defined, which draws the object to the screen.

def blitme(self):
    """Draw ship at current location."""
    self.screen.blit(self.image, self.rect)

Leave a Reply

Your email address will not be published. Required fields are marked *