Creating a scrolling background in Pygame


Pygame is a popular Python library used for building games and multimedia applications. One of the most important aspects of game development is the ability to create scrolling backgrounds. In this article, we will cover the essential steps for creating a scrolling background in Pygame. We will also provide real-world examples and code snippets to help you understand the concepts better.

Other libraries which can also be used for game development in python −

  • Arcade − Arcade is a modern, easy-to-use library for creating 2D arcade-style games. It is designed to be easy to learn and use, and provides a range of features, including graphics, sound, and input handling.

  • PyOpenGL − PyOpenGL is a Python wrapper for the OpenGL 3D graphics library. It provides a range of features for creating 3D games, including graphics, lighting, and texture mapping.

  • Panda3D − Panda3D is a game engine and graphics framework that provides a range of features for creating 3D games. It is designed to be easy to use and supports a range of platforms, including Windows, Mac, and Linux.

  • Pyglet − Pyglet is a cross-platform gaming library that provides a range of features for creating 2D and 3D games. It is designed to be fast and efficient, and provides a range of tools for handling graphics, sound, and input.

The advantages of these libraries can vary depending on your specific needs and requirements. Some of the advantages of using these libraries can include −

  • Ease of use − Many of these libraries are designed to be easy to use and learn, making them a good choice for beginners or developers who are new to game development.

  • Flexibility − These libraries provide a range of features and tools for creating games, which can make it easier to create games that are tailored to your specific needs and requirements.

  • Performance − Some of these libraries are designed to be fast and efficient, which can help improve the performance of your games.

  • Cross-platform support − Many of these libraries support a range of platforms and operating systems, which can help make your games more accessible to a wider audience.

Prerequisites

Before we dive into the details of creating a scrolling background in Pygame, let's review some of the prerequisites.

  • pip install pygame

  • It is expected that the user will have access to any standalone IDE such as VS-Code, PyCharm, Atom or Sublime text.

  • Even online Python compilers can also be used such as Kaggle.com, Google Cloud platform or any other will do.

  • Updated version of Python. At the time of writing the article I have used 3.10.9 version.

  • Knowledge of the use of Jupyter notebook.

  • Familiarity with Pygame library

  • Basic understanding of 2D graphics and game development concepts

If you are not comfortable with any of these prerequisites, we recommend taking some time to get familiar with them before continuing.

Steps for creating a Scrolling Background

Creating a scrolling background involves several steps. We will go over each of them in detail and provide some real-world examples to help you get started.

Step 1: Setting up the game window

The first step to creating a scrolling background is to set up your game window. This can be done using the `pygame.display.set_mode()` function. Here is an example −

import pygame
pygame.init()

Set up game window

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Scrolling Background Tutorial")

In this example, we import the Pygame library and initialize it. We then set the width and height of the game window to 800 pixels and 600 pixels, respectively. Finally, we set the `screen` variable to the newly created game window with the caption "Scrolling Background Tutorial".

Step 2: Loading the background image

The next step is to load the background image that will be scrolled. This can be done using the `pygame.image.load()` function. Here is an example −

#Load background image
background_img = pygame.image.load("background.jpg")

In this example, we load the image named "background.jpg" and store it in the `background_img` variable.

Step 3: Scrolling the background

The next step is to scroll the background image. This can be done by changing the position of the background image on the game window. Here is an example −

# Scroll the background
scroll_x = 0
scroll_y = 0
background_x = 0

while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()

   # Scroll the background horizontally
   scroll_x -= 1
   background_x -= 1

   #Draw the background twice to create seamless scrolling effect
   screen.blit(background_img, (scroll_x, scroll_y))
   screen.blit(background_img, (background_x, scroll_y))

   #Reset the background position when it goes off screen
   if scroll_x <= -screen_width:
      scroll_x = screen_width

   if background_x <= -screen_width:
      background_x = screen_width

   pygame.display.update()

In this example, we set the initial position of the background image to `(0,0)`. We then create a `while` loop that will run continuously until the game is closed. Inside the `while` loop, we increment the `scroll_x` and `background_x` variables by `-1` to move the background image to the left. We then draw the background image twice using `screen.blit()` function. This creates a seamless scrolling effect.

Step 4: Adding game objects

The final step is to add game objects to the window. This can be done using the Pygame library's various drawing functions. Here is an example −

 #Add game objects
player_img = pygame.image.load("player.png")
player_x = 400
player_y = 300

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

     #Scroll the background horizontally
    scroll_x -= 1
    background_x -= 1

     #Draw the background twice to create seamless scrolling effect
    screen.blit(background_img, (scroll_x, scroll_y))
    screen.blit(background_img, (background_x, scroll_y))

     #Reset the background position when it goes off screen
    if scroll_x <= -screen_width:
        scroll_x = screen_width

    if background_x <= -screen_width:
        background_x = screen_width

     #Add game objects
    screen.blit(player_img, (player_x, player_y))

    pygame.display.update()

In this example, we add a player object to the screen using the `screen.blit()` function. We also set the initial position of the player object to `(400,300)`.

Final Program,Code

# libraries
import pygame
pygame.init()

#Setting up the window
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Scrolling Background Tutorial")

#Load background image
background_img = pygame.image.load("background.jpg")

# Scroll the background
scroll_x = 0
scroll_y = 0
background_x = 0

while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
      pygame.quit()

   # Scroll the background horizontally
   scroll_x -= 1
   background_x -= 1

   #Draw the background twice to create seamless scrolling effect
   screen.blit(background_img, (scroll_x, scroll_y))
   screen.blit(background_img, (background_x, scroll_y))

   #Reset the background position when it goes off screen
   if scroll_x <= -screen_width:
      scroll_x = screen_width

   if background_x <= -screen_width:
      background_x = screen_width

   pygame.display.update()

#Add game objects
player_img = pygame.image.load("player.png")
player_x = 400
player_y = 300

while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()

   #Scroll the background horizontally
   scroll_x -= 1
   background_x -= 1

   #Draw the background twice to create seamless scrolling effect
   screen.blit(background_img, (scroll_x, scroll_y))
   screen.blit(background_img, (background_x, scroll_y))

   #Reset the background position when it goes off screen
   if scroll_x <= -screen_width:
      scroll_x = screen_width

   if background_x <= -screen_width:
      background_x = screen_width

   #Add game objects
   screen.blit(player_img, (player_x, player_y))

   pygame.display.update()

Output

In the above section we can see that there are two outputs which shows the transition or scrolling of the background image thus the program works correctly with proper and expected output.

Conclusion

In this tutorial, we covered the essential steps for creating a scrolling background in Pygame. We also provided real-world examples and code snippets to help you understand the concepts better. With this knowledge, you should be able to create engaging games that feature scrolling backgrounds. Happy coding!

Updated on: 25-Apr-2023

995 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements