Hello there, fellow adventurers and aspiring game developers! Have you ever dreamed of creating your own video game, even if it’s just a simple one? Well, today is your lucky day! We’re going to embark on an exciting journey to build a basic platformer game using Python and a fantastic library called Pygame.
Platformer games are a classic genre where you control a character who runs, jumps, and sometimes climbs across different platforms to reach a goal. Think Super Mario Bros. or Celeste! They’re not only incredibly fun to play but also a great starting point for learning game development because they introduce fundamental concepts like player movement, gravity, and collision detection.
By the end of this guide, you’ll have a simple but functional game where you can control a little rectangle (our hero!) that can jump and move across a basic ground platform. Ready to bring your ideas to life? Let’s dive in!
What You’ll Need
Before we start coding, we need to make sure you have the right tools. Don’t worry, it’s pretty straightforward!
- Python: You’ll need Python installed on your computer. We recommend Python 3. If you don’t have it, you can download it from the official Python website: python.org.
- Pygame: This is a powerful library that makes game development with Python much easier. It handles things like graphics, sounds, and user input.
Installing Pygame
Once Python is installed, opening your computer’s terminal or command prompt and running a single command will install Pygame.
pip install pygame
pip(Package Installer for Python): This is Python’s standard package manager, used to install and manage software packages (libraries) written in Python.
If the installation is successful, you’re all set!
Game Basics: The Window and Game Loop
Every game needs a window to display its visuals and a “game loop” that continuously runs to update the game world and handle player actions.
Setting up Pygame and the Display
First, we’ll initialize Pygame and create our game window.
import pygame
import sys
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My Simple Platformer")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
The Heart of the Game: The Game Loop
The game loop is an endless cycle where the game checks for inputs (like keyboard presses), updates game elements (like player position), and then draws everything on the screen.
running = True
while running:
# 1. Event Handling: Check for user input (keyboard, mouse, closing window)
for event in pygame.event.get():
if event.type == pygame.QUIT: # If the user clicks the 'X' to close the window
running = False # Stop the game loop
# Technical Term: Event Handling - This is how our game listens for and responds to anything that happens, like a key press or mouse click.
# Technical Term: pygame.QUIT - This is a specific event that occurs when the user tries to close the game window.
# 2. Update game state (we'll add player movement here later)
# 3. Drawing: Clear the screen and draw game objects
SCREEN.fill(BLUE) # Fill the background with blue (our sky)
# (We'll draw our player and ground here soon!)
# 4. Update the display to show what we've drawn
pygame.display.flip()
# Technical Term: pygame.display.flip() - This updates the entire screen to show everything that has been drawn since the last update.
pygame.quit()
sys.exit()
If you run this code now, you’ll see a blue window pop up and stay there until you close it. That’s our basic game structure!
Our Player: A Simple Rectangle
Let’s give our game a hero! For simplicity, our player will be a red rectangle. We’ll define its size, position, and properties needed for movement.
player_width = 30
player_height = 50
player_x = SCREEN_WIDTH // 2 - player_width // 2 # Start in the middle
player_y = SCREEN_HEIGHT - player_height - 50 # Start a bit above the bottom
player_velocity_x = 0 # Horizontal speed
player_velocity_y = 0 # Vertical speed (for jumping and gravity)
player_speed = 5
jump_power = -15 # Negative because y-axis increases downwards
gravity = 0.8
is_grounded = False # To check if the player is on a surface
Now, let’s add code to draw our player inside the game loop, right before pygame.display.flip().
player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
pygame.draw.rect(SCREEN, RED, player_rect)
Bringing in Gravity and Jumping
Gravity is what makes things fall! We’ll apply it to our player, and then allow the player to defy gravity with a jump.
Implementing Gravity
Gravity will constantly pull our player downwards by increasing player_velocity_y.
player_velocity_y += gravity
player_y += player_velocity_y
If you run this now, our red rectangle will fall off the screen! We need a ground to land on.
Making a Ground
Let’s create a green rectangle at the bottom of the screen to serve as our ground.
ground_height = 20
ground_x = 0
ground_y = SCREEN_HEIGHT - ground_height
ground_width = SCREEN_WIDTH
ground_rect = pygame.Rect(ground_x, ground_y, ground_width, ground_height)
pygame.draw.rect(SCREEN, GREEN, ground_rect)
Collision Detection: Player and Ground
Our player currently falls through the ground. We need to detect when the player’s rectangle hits the ground’s rectangle and stop its vertical movement.
if player_rect.colliderect(ground_rect):
player_y = ground_y - player_height # Place player on top of ground
player_velocity_y = 0 # Stop vertical movement
is_grounded = True # Player is now on the ground
else:
is_grounded = False # Player is in the air
Now your player should fall and stop on the green ground!
Adding the Jump
We’ll make the player jump when the spacebar is pressed, but only if they are is_grounded.
if event.type == pygame.KEYDOWN: # If a key is pressed down
if event.key == pygame.K_SPACE and is_grounded: # If it's the spacebar and player is on ground
player_velocity_y = jump_power # Apply upward velocity for jump
is_grounded = False # Player is no longer grounded
Try it out! Your player can now jump!
Horizontal Movement
What’s a platformer without being able to move left and right? We’ll use the left and right arrow keys.
Pygame has a convenient function, pygame.key.get_pressed(), which tells us which keys are currently held down. This is great for continuous movement.
keys = pygame.key.get_pressed()
player_velocity_x = 0 # Reset horizontal velocity each frame
if keys[pygame.K_LEFT]:
player_velocity_x = -player_speed
if keys[pygame.K_RIGHT]:
player_velocity_x = player_speed
player_x += player_velocity_x
Now, combine everything, and you’ve got a basic platformer!
Putting It All Together: The Complete Code
Here’s the full code for our simple platformer game. Copy and paste this into a Python file (e.g., platformer.py) and run it!
import pygame
import sys
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My Simple Platformer")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
player_width = 30
player_height = 50
player_x = SCREEN_WIDTH // 2 - player_width // 2 # Start in the middle horizontally
player_y = SCREEN_HEIGHT - player_height - 50 # Start a bit above the bottom
player_velocity_x = 0
player_velocity_y = 0
player_speed = 5
jump_power = -15
gravity = 0.8
is_grounded = False
ground_height = 20
ground_x = 0
ground_y = SCREEN_HEIGHT - ground_height
ground_width = SCREEN_WIDTH
ground_rect = pygame.Rect(ground_x, ground_y, ground_width, ground_height)
running = True
clock = pygame.time.Clock() # For controlling frame rate
while running:
# 8. Event Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and is_grounded:
player_velocity_y = jump_power
is_grounded = False
# 9. Handle horizontal movement with continuous key presses
keys = pygame.key.get_pressed()
player_velocity_x = 0 # Reset horizontal velocity each frame
if keys[pygame.K_LEFT]:
player_velocity_x = -player_speed
if keys[pygame.K_RIGHT]:
player_velocity_x = player_speed
# 10. Update player's horizontal position
player_x += player_velocity_x
# 11. Apply gravity
player_velocity_y += gravity
player_y += player_velocity_y
# 12. Create player rectangle for collision detection and drawing
player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
# 13. Collision detection with ground
if player_rect.colliderect(ground_rect):
player_y = ground_y - player_height # Place player on top of ground
player_velocity_y = 0 # Stop vertical movement
is_grounded = True # Player is now on the ground
else:
is_grounded = False # Player is in the air
# 14. Keep player within screen bounds horizontally
if player_x < 0:
player_x = 0
if player_x > SCREEN_WIDTH - player_width:
player_x = SCREEN_WIDTH - player_width
# 15. Drawing
SCREEN.fill(BLUE) # Fill background with blue
pygame.draw.rect(SCREEN, GREEN, ground_rect) # Draw the ground
pygame.draw.rect(SCREEN, RED, player_rect) # Draw the player
# 16. Update the display
pygame.display.flip()
# 17. Cap the frame rate (e.g., to 60 FPS)
clock.tick(60) # This makes sure our game doesn't run too fast
# Technical Term: FPS (Frames Per Second) - How many times the game updates and draws everything in one second. 60 FPS is generally a smooth experience.
pygame.quit()
sys.exit()
Next Steps for Fun & Experiments!
You’ve built the foundation of a platformer! Now the real fun begins: customizing and expanding your game. Here are some ideas:
- Add more platforms: Instead of just one ground, create multiple
pygame.Rectobjects for platforms at different heights. - Collectibles: Draw small squares or circles that disappear when the player touches them.
- Enemies: Introduce simple enemies that move back and forth, and figure out what happens when the player collides with them.
- Sprites: Replace the plain red rectangle with actual character images (sprites). Pygame makes it easy to load and display images.
- Backgrounds: Add a fancy background image instead of a solid blue color.
- Level design: Create more complex layouts for your platforms.
- Game over conditions: What happens if the player falls off the bottom of the screen?
Conclusion
Congratulations! You’ve successfully built your very first platformer game from scratch using Python and Pygame. You’ve learned about game loops, event handling, player movement, gravity, and collision detection – all core concepts in game development.
This project is just the beginning. Game development is a creative and rewarding field, and with the basics you’ve learned today, you have a solid foundation to explore more advanced techniques and build even more amazing games. Keep experimenting, keep coding, and most importantly, have fun! Happy coding!
Leave a Reply
You must be logged in to post a comment.