Creating a simple platformer game in Python can be efficiently done using the pygame library, which is designed for writing video games. Below is a step-by-step guide along with complete code to create a basic platformer where the player starts at a fixed position, aims to reach a goal, and must navigate past traps and enemies.
Prerequisites
-
Python Installed: Ensure you have Python 3.x installed on your system.
-
Pygame Installed: Install pygame using pip if you haven't already:
pip install pygame
Game Overview
- Player: Can move left, right, and jump.
- Platforms: Static platforms where the player can stand.
- Enemies: Move back and forth on platforms. Colliding with them resets the player.
- Traps: Static hazards that also reset the player upon collision.
- Goal: Reaching the goal ends the game successfully.
Game Structure
- Initialize Pygame and Set Up the Window
- Define Game Entities: Player, Platform, Enemy, Trap, Goal.
- Handle Input: Player movement and jumping.
- Update Game State: Move enemies, handle collisions.
- Render Everything: Draw all game entities on the screen.
- Game Loop: Continues until the player reaches the goal or quits.
Complete Code
Here's the complete code for the described platformer game:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
GRAY = (100, 100, 100)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# Create the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Simple Platformer")
# Clock to control FPS
clock = pygame.time.Clock()
# Define classes
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.width = 40
self.height = 60
self.image = pygame.Surface((self.width, self.height))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.vel_y = 0
self.speed = 5
self.jump_strength = 15
self.on_ground = False
def update(self, platforms):
keys = pygame.key.get_pressed()
dx = 0
dy = 0
# Horizontal movement
if keys[pygame.K_LEFT]:
dx -= self.speed
if keys[pygame.K_RIGHT]:
dx += self.speed
# Jump
if keys[pygame.K_SPACE] and self.on_ground:
self.vel_y = -self.jump_strength
self.on_ground = False
# Apply gravity
self.vel_y += 0.8 # Gravity
if self.vel_y > 20:
self.vel_y = 20
dy += self.vel_y
# Collision detection
self.on_ground = False
for platform in platforms:
# Check horizontal collision
if platform.rect.colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
dx = 0
# Check vertical collision
if platform.rect.colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
if self.vel_y > 0:
dy = platform.rect.top - self.rect.bottom
self.vel_y = 0
self.on_ground = True
elif self.vel_y < 0:
dy = platform.rect.bottom - self.rect.top
self.vel_y = 0
# Update position
self.rect.x += dx
self.rect.y += dy
# Keep player within screen bounds
if self.rect.left < 0:
self.rect.left = 0
if self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
if self.rect.top > SCREEN_HEIGHT:
reset_player()
def reset_position(self):
self.rect.topleft = (50, SCREEN_HEIGHT - 100)
self.vel_y = 0
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color=GRAY):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y, patrol_width):
super().__init__()
self.width = 40
self.height = 40
self.image = pygame.Surface((self.width, self.height))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.start_x = x
self.patrol_width = patrol_width
self.speed = 2
self.direction = 1 # 1: right, -1: left
def update(self):
self.rect.x += self.speed * self.direction
if self.rect.x > self.start_x + self.patrol_width or self.rect.x < self.start_x:
self.direction *= -1
class Trap(pygame.sprite.Sprite):
def __init__(self, x, y, width=40, height=40):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
class Goal(pygame.sprite.Sprite):
def __init__(self, x, y, width=50, height=60):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
# Initialize sprites
player = Player(50, SCREEN_HEIGHT - 100)
platforms = pygame.sprite.Group()
enemies = pygame.sprite.Group()
traps = pygame.sprite.Group()
everything = pygame.sprite.Group()
everything.add(player)
# Create a predefined map
# Ground platform
platforms.add(Platform(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40))
everything.add(platforms)
# Other platforms
platforms_list = [
(200, SCREEN_HEIGHT - 150, 200, 20),
(450, SCREEN_HEIGHT - 250, 200, 20),
(150, SCREEN_HEIGHT - 350, 200, 20),
(400, SCREEN_HEIGHT - 450, 200, 20),
]
for plat in platforms_list:
p = Platform(*plat)
platforms.add(p)
everything.add(p)
# Enemies
enemy_positions = [
(250, SCREEN_HEIGHT - 190, 150),
(500, SCREEN_HEIGHT - 290, 150),
(200, SCREEN_HEIGHT - 390, 150),
]
for pos in enemy_positions:
e = Enemy(*pos)
enemies.add(e)
everything.add(e)
# Traps
trap_positions = [
(350, SCREEN_HEIGHT - 40 - 40), # On ground
(600, SCREEN_HEIGHT - 150 - 40), # On first platform
(300, SCREEN_HEIGHT - 250 - 40), # On second platform
]
for pos in trap_positions:
t = Trap(*pos)
traps.add(t)
everything.add(t)
# Goal
goal = Goal(SCREEN_WIDTH - 100, SCREEN_HEIGHT - 500 - 60)
everything.add(goal)
# Function to reset player position
def reset_player():
player.reset_position()
# Font for displaying messages
font = pygame.font.SysFont(None, 48)
# Game state
game_over = False
game_won = False
# Main game loop
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not game_over and not game_won:
# Update sprites
player.update(platforms)
enemies.update()
# Check collision with enemies
if pygame.sprite.spritecollide(player, enemies, False):
reset_player()
# Check collision with traps
if pygame.sprite.spritecollide(player, traps, False):
reset_player()
# Check collision with goal
if pygame.sprite.collide_rect(player, goal):
game_won = True
# Draw everything
screen.fill(WHITE)
everything.draw(screen)
if game_won:
text = font.render("You Win!", True, GREEN)
screen.blit(text, (SCREEN_WIDTH//2 - text.get_width()//2, SCREEN_HEIGHT//2))
elif game_over:
text = font.render("Game Over!", True, RED)
screen.blit(text, (SCREEN_WIDTH//2 - text.get_width()//2, SCREEN_HEIGHT//2))
pygame.display.flip()
# Quit Pygame
pygame.quit()
sys.exit()
How to Run the Game
-
Save the Code: Copy the above code into a Python file, e.g., platformer.py.
-
Run the Game:
python platformer.py
Game Controls
- Left Arrow (
←): Move the player to the left.
- Right Arrow (
→): Move the player to the right.
- Spacebar: Make the player jump.
Game Features
- Fixed Map: The map is predefined with specific platforms, enemies, and traps.
- Player Mechanics: The player can move left/right and jump. Gravity affects the player, and collision detection ensures the player lands on platforms.
- Enemies: Enemies patrol back and forth on their designated platforms. Contact with an enemy resets the player's position.
- Traps: Static hazards placed on certain platforms. Colliding with a trap also resets the player.
- Goal: A green block placed at a specific location. Reaching the goal displays a "You Win!" message.
Customization
You can customize the game by modifying the following:
- Map Layout: Adjust the
platforms_list to change the position and size of platforms.
- Enemy Positions: Modify
enemy_positions to place enemies on different platforms or adjust their patrol widths.
- Trap Positions: Change
trap_positions to add or remove traps.
- Player Starting Position: Adjust the
Player initialization parameters.
- Graphics: Replace the simple colored rectangles with images by loading sprites using
pygame.image.load().
Adding Enhancements
Here are some ideas to enhance the game further:
- Multiple Levels: Create different levels with varying difficulty.
- Scoring System: Implement a scoring system based on time taken or enemies avoided.
- Health System: Instead of resetting upon collision, have the player lose health and allow multiple attempts.
- Sound Effects: Add background music and sound effects for actions like jumping and collisions.
- Animations: Use sprite sheets to animate the player and enemies for more visual appeal.
Resources
- Pygame Documentation: https://www.pygame.org/docs/
- Pygame Tutorials: There are numerous tutorials online that can help you dive deeper into game development with Pygame.
Enjoy building and customizing your platformer game!