Subscribe
How to Build a 2D Platformer Game with Pygame

By: vishwesh

How to Build a 2D Platformer Game with Pygame

Are you interested in creating your own 2D platformer game using Pygame? Pygame is a Python library that allows you to create 2D games and multimedia applications. In this tutorial, we will walk you through the process of building a 2D platformer game with Pygame.

Getting Started

To start building your 2D platformer game, you will need to install Pygame. You can do this by running the following command in your terminal:

pip install pygame

Once you have installed Pygame, you can start building your game.

Creating the Game Window

The first step in building a 2D platformer game is to create the game window. To do this, we will import the Pygame library and create a Pygame window.

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the screen (width, height).
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the title of the window
pygame.display.set_caption("2D Platformer Game")

# Run the game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

In the code above, we first import the Pygame library and initialize it. We then set the width and height of the game window and create the window using the pygame.display.set_mode() function. We also set the title of the window using the pygame.display.set_caption() function. Finally, we create a game loop that will handle events and update the display.

Creating the Player

The next step in building a 2D platformer game is to create the player. To do this, we will create a class for the player and add it to the game.

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

In the code above, we create a Player class that inherits from the pygame.sprite.Sprite class. We then define the __init__() function for the Player class. In this function, we create a surface for the player using the pygame.Surface() function and fill it with the color red. We then set the player's position using the self.rect.x and self.rect.y variables.

Adding the Player to the Game

Now that we have created the player, we need to add it to the game. To do this, we will create a group for the player and add it to the game loop.

# Create the player
player = Player(100, 100)

# Create a sprite group for the player
player_group = pygame.sprite.Group()
player_group.add(player)

# Run the game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Draw the player
    player_group.draw(screen)

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

In the code above, we create the player using the Player class and set its position to (100, 100). We then create a sprite group for the player using the pygame.sprite.Group() function and add the player to the group using the add() method. Finally, we draw the player using the draw() method of the player group.

Adding Movement to the Player

Now that we have added the player to the game, we need to add movement to the player. To do this, we will add some code to handle keyboard input.

# Run the game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Handle keyboard input
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.rect.x -= 5
    if keys[pygame.K_RIGHT]:
        player.rect.x += 5
    if keys[pygame.K_UP]:
        player.rect.y -= 5
    if keys[pygame.K_DOWN]:
        player.rect.y += 5

    # Draw the player
    player_group.draw(screen)

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

In the code above, we first check for keyboard input using the pygame.key.get_pressed() function. We then check if the left arrow key is pressed and move the player to the left by decreasing its rect.x variable. Similarly, we check for other arrow keys and move the player accordingly.

Adding Platforms to the Game

Now that we have added movement to the player, we need to add platforms to the game. Platforms are objects that the player can stand on or jump off of. To do this, we will create a Platform class and add it to the game.

class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill((0, 255, 0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

In the code above, we create a Platform class that inherits from the pygame.sprite.Sprite class. We then define the __init__() function for the Platform class. In this function, we create a surface for the platform using the pygame.Surface() function and fill it with the color green. We then set the platform's position and size using the self.rect.x, self.rect.y, width, and height variables.

Adding Multiple Platforms to the Game

Now that we have created the Platform class, we need to add multiple platforms to the game. To do this, we will create a list of platforms and add them to the game loop.

# Create a list of platforms
platforms = [
    Platform(0, screen_height - 40, screen_width, 40),
    Platform(screen_width/2 - 50, screen_height*3/4, 100, 20),
    Platform(150, screen_height*2/3, 100, 20),
    Platform(screen_width - 250, screen_height*2/3, 100, 20),
]

# Create a sprite group for the platforms
platform_group = pygame.sprite.Group()
for platform in platforms:
    platform_group.add(platform)

# Run the game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Handle keyboard input
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.rect.x -= 5
    if keys[pygame.K_RIGHT]:
        player.rect.x += 5
    if keys[pygame.K_UP]:
        player.rect.y -= 5
    if keys[pygame.K_DOWN]:
        player.rect.y += 5

    # Check for collisions between the player and the platforms
    if pygame.sprite.spritecollide(player, platform_group, False):
        player.rect.y -= 5

    # Draw the platforms and the player
    platform_group.draw(screen)
    player_group.draw(screen)

    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()

In the code above, we create a list of platforms and add them to the game loop. We then create a sprite group for the platforms using the pygame.sprite.Group() function and add the platforms to the group using a for loop. Finally, we draw the platforms using the draw() method of the platform group.

We also check for collisions between the player and the platforms using the pygame.sprite.spritecollide() function. If a collision is detected, we move the player up by decreasing its rect.y variable.

Conclusion

Congratulations! You have successfully built a 2D platformer game with Pygame. You learned how to create a window, add a player, handle keyboard input, add platforms, and detect collisions between the player and the platforms. You can now use your newfound knowledge to create your own games and expand upon the game you just created. Happy coding!

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories