Creating a scrolling background in Pygame
If you’re making a game using Python and Pygame, you may want to create a scrolling background to give the illusion of movement. In this tutorial, we’ll show you how to create a simple scrolling background in Pygame.
Step 1: Set up
First, make sure Pygame is installed. You can do this by running pip install pygame
.
Create a new Pygame project and import the necessary libraries:
import pygame
import os
Set up the game window:
pygame.init()
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Scrolling Background")
Step 2: Load the background image
Find a suitable background image for your game. In this tutorial, we’ll use a simple grass texture.
Load the image and create a Surface object:
background_img = pygame.image.load(os.path.join('img', 'grass.png')).convert()
background = pygame.Surface((WINDOW_WIDTH * 2, WINDOW_HEIGHT))
The convert() method converts the image to a format that Pygame can easily work with. The background Surface is twice the width of the window so we can scroll it later.
Step 3: Scroll the background
Pygame has a built-in function for scrolling Surfaces: blit(). We’ll use this to create the scrolling effect.
Create a variable to keep track of the current scrolling position:
scroll_x = 0
In the game loop, use blit() to copy a portion of the background Surface to the screen. Then increment scroll_x
to scroll the background:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255,255,255))
# Copy a portion of the background to the screen
screen.blit(background, (0, 0), (scroll_x, 0, WINDOW_WIDTH, WINDOW_HEIGHT))
screen.blit(background, (WINDOW_WIDTH, 0), (scroll_x, 0, WINDOW_WIDTH, WINDOW_HEIGHT))
# Scroll the background
scroll_x -= 1
if scroll_x < -WINDOW_WIDTH:
scroll_x = 0
pygame.display.flip()
The first blit() copies the left half of the background Surface to the left half of the screen. The second blit() copies the right half of the background Surface to the right half of the screen. The third argument to blit() specifies the portion of the background Surface to copy.
After blitting, scroll_x is decremented by 1. If it goes below -WINDOW_WIDTH (the width of the window), reset it to 0. This creates an infinite scrolling effect.
Conclusion
That’s it – you now have a simple scrolling background in Pygame! You can experiment with different images and scroll speeds to create the effect you want. Happy coding!