[파이썬] pygame 무한 스크롤링 백그라운드

In this blog post, we will explore how to create a scrolling background effect in Pygame, a popular Python library for game development. We will implement an infinite scrolling background where the image repeatedly scrolls horizontally, giving the illusion of an endless background.

Prerequisites

Before we begin, make sure you have Pygame installed. You can install Pygame using the following pip command:

pip install pygame

Step 1: Setting up the project

First, let’s create a new Pygame project. Import the necessary libraries and initialize the game window:

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set the dimensions of the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Infinite Scrolling Background")

# Set the clock to control the frame rate
clock = pygame.time.Clock()

Step 2: Load the background image

Next, we need to load the background image that we want to scroll. Make sure to have an image file ready to use. For this example, let’s assume the image file is named “background.jpg” and is located in the same directory as your Python script:

# Load the background image
background_image = pygame.image.load("background.jpg").convert()

Step 3: Create a scrolling effect

To create the scrolling effect, we will continuously move the background image horizontally and reset its position once it reaches the end of the screen. We can achieve this by updating the x-coordinate of the background image in each game loop iteration:

# Set the initial x-coordinate of the background image
background_x = 0

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

    # Scroll the background
    background_x -= 1

    # Reset the background position
    if background_x <= -background_image.get_width():
        background_x = 0

    # Render the background image on the game window
    window.blit(background_image, (background_x, 0))

    # Update the display
    pygame.display.update()

    # Control the frame rate
    clock.tick(60)

In the above code, we continuously decrease the background_x variable by 1 on each game loop iteration, which causes the background image to move leftwards. Once the background_x value becomes less than or equal to the negative width of the background image, we reset it to 0, restarting the scrolling effect from the beginning.

Conclusion

Congratulations! You have successfully implemented an infinite scrolling background effect in Pygame. Feel free to customize and enhance this code to suit your specific game or application requirements.