How to blit a surface onto an already blitted surface in Pygame?
The blit() method in
blit() one surface onto another
To blit() one surface onto another, we need to create a new surface that combines the contents of both surfaces, and then blit() the combined surface onto the display surface.
To blit() a surface onto an already blitted surface in Pygame, we can use the following code:
import pygame
pygame.init()
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
# Create the first surface
surface1 = pygame.Surface((400, 400))
surface1.fill((255, 0, 0)) # Fills the surface with red color
# Create the second surface
surface2 = pygame.Surface((200, 200))
surface2.fill((0, 255, 0)) # Fills the surface with green color
# Blit the second surface onto the first surface
surface1.blit(surface2, (25, 25))
# Blit the combined surface onto the screen surface
screen.blit(surface1, (100, 100))
# Update the display to show the changes
pygame.display.update()
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()Code explanation
Line 1–3: Here, we import the
pygamemodule and initialize it.Line 4: This line defines the
screen_widthandscreen_heightvariables to specify the dimensions of the game window.Line 5: Here, we create a game window using the
pygame.display.set_mode()function and pass the dimensions of the screen as a tuple.Line 8: This line creates the first surface (a rectangular area) using the
pygame.Surface()method and provide its width and height as parameters.Line 9: Using
fill(), we fill the first surface with red color and pass a tuple representing the RGB values for red.Line 12: This line will create the second surface with a smaller size than the first surface.
Line 13: Again, we will use the
fill()method to fill the second surface with green color and pass a tuple representing the RGB values for green.Line 16: In this line,
blit()draws the second surface onto the first surface. The second surface will be placed at coordinates(25, 25)on the first surface.Line 19: Here, we draw the combined surface onto the screen surface by calling the
blit()method using thescreenobject. The combined surface will be placed at coordinates(100, 100)on the screen.Line 22: Now we will update the display to show the changes made to the screen using the
display.update()function.Line 25: Here, we set the variable
runningtoTrueto start the game loop.Line 26–29: This is the game loop where events are handled.
Line 27–28: Here, we iterate over the
pygame.eventarray and check if there's any event that has typepygame.QUIT. If so, we will set therunningvariable toFalseto exit the game loop.Line 31: This line will quit the
pygamemodules and close the game window.
Free Resources