How to add moving platforms in PyGame?


In various games that contain platforms, moving platforms are mainly essential elements of the gameplay to make the game more interactive and challenging. PyGame is a popular Python library that is widely used to create 2-dimensional games. In this article, we will discuss how to add moving platforms to a game using PyGame and will see an example program to demonstrate the process.

What are moving platforms?

A moving platform is a flat and solid surface on which the player can walk or jump. These platforms are often used in games that contain platforms so that they can provide new challenges to the players, such as reaching high levels or crossing the gaps.

How to add moving platforms in PyGame?

Below are the steps we will follow to add moving platforms in Pygame −

  • Import pygame module − First we need to import the pygame module in our Python file by adding the below code.

import pygame
  • Define the moving platform class − Next step is to define a new sprite class that mainly represents the moving platform in the game. We can do this by creating a class that inherits from the Pygame Sprite class.

  • Create a Sprite Group − Next step is to create a sprite group. In pygame, sprite groups are collections of sprites that can be updated or modified and drawn together. We need to create a new sprite group to add the moving platforms.

  • Add the platform to the Sprite Group − Next step after creating the Sprite group is we need to create a new instance of the moving platform class and add it to the Sprite group.

  • Update the Platform’s position in the gaming loop − The last step is to update the moving platform’s position in the game loop. In pygame, the game loop is responsible for updating the game state, and handling the user input and game graphics. To do the same we need to call its update method once per frame.

Example

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set the screen dimensions

screen_width = 800
screen_height = 600

# Create the screen
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Moving Platforms")

# Set up the clock
clock = pygame.time.Clock()

# Define the Moving Platform Class
class MovingPlatform(pygame.sprite.Sprite):
   def __init__(self, x, y, width, height, speed):
      super().__init__()
      self.image = pygame.Surface((width, height))
      self.image.fill((0, 255, 0)) # Set the platform color to green
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.speed = speed
      
   def update(self):
      self.rect.x += self.speed
      if self.rect.right >= screen_width or self.rect.left <= 0:
         self.speed = -self.speed

# Create a sprite group for the moving platforms
moving_platforms = pygame.sprite.Group()

# Create some moving platforms and add them to the sprite group

platform1 = MovingPlatform(200, 300, 200, 20, 2)
moving_platforms.add(platform1)

platform2 = MovingPlatform(500, 200, 200, 20, -3)
moving_platforms.add(platform2)

# Start the game loop
while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()
         sys.exit()

   # Update the moving platforms
   moving_platforms.update()

   # Draw the moving platforms and other game elements
   screen.fill((255, 255, 255))
   moving_platforms.draw(screen)

   # Update the screen
   pygame.display.flip()

   # Control the frame rate
   clock.tick(60)

Output

In the above program, we first initialized Pygame and then set up the dimensions of the screen. After that, we created the screen and set the caption for the window.

In the next step, we defined the MovingPlatform class, which inherits from the pygame.sprite.Sprite class. In pygame a moving platform in a game is defined by this particular class. It takes the x and y coordinates, width, height, and speed of the platform as input parameters. We have created a surface for the platform with the given width and height given by the user, fill it with the green color, and set the position of the surface on the screen in the constructor. We have also set the platform speed.

The update() method of the MovingPlatform class is called every frame. It updates the platform’s position by adding its speed to its x-coordinate. If the platform goes off the screen on either side then we reverse its direction by setting the speed of the screen to its negative value.

After we have defined the MovngPlatform class, we created a sprite group for the moving platforms using the function pygame.sprite.Group(). Then, we created two instances of the MovingPlatform class with different coordinates, speeds, and sizes, and added them to the sprite group using the method add().

In the last step, we started the game loop using the while loop that runs for an infinite time until the player quits the game. We have handled the events by checking if the user has clicked the close button inside the game loop. We then updated the moving platforms by calling their update() method, drawing them on the screen using the method draw() of the sprite group, and then updating the screen using pygame.display.flip(). We also controlled the frame rate using the method clock.tick().

Conclusion

In conclusion, adding a moving platform to the game using pygame is the best way to make the platform-based game more challenging and dynamic. We have seen that we can easily update and draw them on the screen in the game loop by creating a class for moving platforms and adding them to the sprite group. It’s relatively simple to create moving platforms with custom sizes, speeds, and colors with the help of the Pygame library.

Updated on: 31-May-2023

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements