Pygame screen.blit example
Here in this tutorial, we will learn how to use the blit() function in pygame with an example in Python.
The blit() function in pygame is used when we want to copy one surface over another. Here we will take a look at how to add an image onto a pygame screen using the blit() function.
Blit function with example
import pygame background = pygame.display.set_mode((700, 500)) image = pygame.image.load('sky.png') while True: for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() exit() background.blit(image, (150, 100)) pygame.display.update()
First of all, we have defined the surface of our game using
pygame.display.set_mode() using the variable ‘background’.
Then we have taken an image that I already saved in the same folder as the game file and imported it using pygame.image.load(“the name by which the image is saved”) in the variable ‘image’.
Now for adding the image to the screen we have used the blit function with the background and the coordinates where we want the image to be placed on the screen. That is background.blit(image,(x-coordinate,y-coordinate).
For the rest of the game,
- we have taken a while loop which will iterate through the game until the user exits.
pygame.display.update()will update the screen corresponding to the changes made.
Thus we have seen how to implement the blit() function with the help of an example.