Creating a Simple Platformer Game with Pygame
Here's a complete, runnable platformer game implemented with Pygame. The game features a player character that can move, jump, and collect coins while avoiding enemies.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Platformer")
# Colors
SKY_BLUE = (135, 206, 235)
GROUND_COLOR = (34, 139, 34)
PLATFORM_COLOR = (139, 69, 19)
PLAYER_COLOR = (220, 20, 60)
ENEMY_COLOR = (75, 0, 130)
COIN_COLOR = (255, 215, 0)
TEXT_COLOR = (255, 255, 255)
BACKGROUND_COLOR = (30, 30, 50)
GOAL_COLOR = (0, 200, 0)
# Game variables
gravity = 0.8
player_speed = 5
jump_strength = -15
scroll_threshold = 200
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 30
self.height = 50
self.vel_y = 0
self.vel_x = 0
self.jumping = False
self.direction = 1 # 1 for right, -1 for left
self.on_ground = False
self.score = 0
self.lives = 3
self.invincible = 0
self.animation_count = 0
def move(self, platforms):
# Reset horizontal movement
self.vel_x = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.vel_x = -player_speed
self.direction = -1
if keys[pygame.K_RIGHT]:
self.vel_x = player_speed
self.direction = 1
# Apply gravity
self.vel_y += gravity
if self.vel_y > 10:
self.vel_y = 10
# Update position
self.x += self.vel_x
self.y += self.vel_y
# Check for collisions with platforms
self.on_ground = False
for platform in platforms:
# Horizontal collision
if (self.y + self.height > platform.y and
self.y < platform.y + platform.height and
self.x + self.width > platform.x and
self.x < platform.x + platform.width):
if self.vel_x > 0: # Moving right
self.x = platform.x - self.width
elif self.vel_x < 0: # Moving left
self.x = platform.x + platform.width
# Vertical collision
if (self.x + self.width > platform.x and
self.x < platform.x + platform.width and
self.y + self.height > platform.y and
self.y < platform.y + platform.height):
if self.vel_y > 0: # Falling
self.y = platform.y - self.height
self.vel_y = 0
self.on_ground = True
self.jumping = False
elif self.vel_y < 0: # Jumping
self.y = platform.y + platform.height
self.vel_y = 0
# Keep player on screen
if self.x < 0:
self.x = 0
if self.x > WIDTH - self.width:
self.x = WIDTH - self.width
if self.y > HEIGHT - self.height:
self.y = HEIGHT - self.height
self.vel_y = 0
self.on_ground = True
# Update invincibility timer
if self.invincible > 0:
self.invincible -= 1
def jump(self):
if self.on_ground:
self.vel_y = jump_strength
self.jumping = True
self.on_ground = False
def draw(self, screen):
# Draw player body
color = PLAYER_COLOR
if self.invincible > 0 and self.invincible % 5 < 3: # Flash when invincible
color = (255, 255, 255)
# Draw player with simple animation
offset = 0
if not self.on_ground:
offset = -5
elif abs(self.vel_x) > 0:
self.animation_count = (self.animation_count + 1) % 20
offset = 3 if self.animation_count < 10 else 0
pygame.draw.rect(screen, color, (self.x, self.y + offset, self.width, self.height - offset))
# Draw eyes
eye_size = 5
eye_offset_x = 5 if self.direction > 0 else self.width - 15
pygame.draw.circle(screen, (0, 0, 0), (self.x + eye_offset_x, self.y + 15), eye_size)
def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)
class Platform:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self, screen):
pygame.draw.rect(screen, PLATFORM_COLOR, (self.x, self.y, self.width, self.height))
# Add some texture
for i in range(0, self.width, 10):
pygame.draw.line(screen, (101, 67, 33), (self.x + i, self.y), (self.x + i, self.y + self.height), 1)
class Enemy:
def __init__(self, x, y, width, height, move_range=100):
self.x = x
self.y = y
self.width = width
self.height = height
self.direction = 1
self.move_range = move_range
self.start_x = x
self.speed = random.randint(1, 3)
def update(self):
self.x += self.direction * self.speed
# Change direction if reached move range
if abs(self.x - self.start_x) > self.move_range:
self.direction *= -1
def draw(self, screen):
pygame.draw.rect(screen, ENEMY_COLOR, (self.x, self.y, self.width, self.height))
# Draw eyes
eye_offset = 5 if self.direction > 0 else self.width - 15
pygame.draw.circle(screen, (255, 0, 0), (self.x + eye_offset, self.y + 10), 4)
def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)
class Coin:
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = 10
self.collected = False
self.animation = 0
def update(self):
self.animation = (self.animation + 0.1) % 6.28 # Use 2π for full rotation
def draw(self, screen):
if not self.collected:
# Draw coin with a shine effect
pygame.draw.circle(screen, COIN_COLOR, (self.x, self.y), self.radius)
shine_offset = 3
pygame.draw.circle(screen, (255, 255, 200),
(self.x - shine_offset + self.animation * 2,
self.y - shine_offset),
self.radius // 2)
def get_rect(self):
return pygame.Rect(self.x - self.radius, self.y - self.radius,
self.radius * 2, self.radius * 2)
class Goal:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self, screen):
pygame.draw.rect(screen, GOAL_COLOR, (self.x, self.y, self.width, self.height))
# Draw flag
pygame.draw.rect(screen, (255, 255, 255), (self.x + self.width//2 - 2, self.y, 4, 30))
pygame.draw.polygon(screen, (200, 0, 0), [
(self.x + self.width//2, self.y),
(self.x + self.width//2 + 20, self.y + 10),
(self.x + self.width//2, self.y + 20)
])
def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)
# Create game objects
player = Player(50, 300)
platforms = [
Platform(0, HEIGHT - 40, WIDTH, 40), # Ground
Platform(100, 500, 200, 20),
Platform(400, 450, 150, 20),
Platform(200, 350, 200, 20),
Platform(500, 300, 150, 20),
Platform(100, 250, 150, 20),
Platform(350, 200, 200, 20),
Platform(600, 150, 150, 20),
]
enemies = [
Enemy(300, 480, 30, 20, 150),
Enemy(450, 330, 30, 20, 100),
Enemy(150, 230, 30, 20, 120),
]
coins = [
Coin(150, 500),
Coin(450, 400),
Coin(250, 300),
Coin(400, 150),
Coin(650, 100),
]
goal = Goal(700, 100, 30, 50)
# Create clouds for background
clouds = []
for _ in range(10):
x = random.randint(0, WIDTH)
y = random.randint(20, 200)
clouds.append((x, y))
# Game state
game_state = "playing" # "playing", "win", "game_over"
font = pygame.font.SysFont(None, 36)
# Main game loop
clock = pygame.time.Clock()
scroll_offset = 0
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if game_state == "playing":
player.jump()
else:
# Reset game
player = Player(50, 300)
for coin in coins:
coin.collected = False
game_state = "playing"
if event.key == pygame.K_ESCAPE:
running = False
if game_state == "playing":
# Update game objects
player.move(platforms)
for enemy in enemies:
enemy.update()
for coin in coins:
coin.update()
# Check for coin collection
for coin in coins:
if not coin.collected and player.get_rect().colliderect(coin.get_rect()):
coin.collected = True
player.score += 10
# Check for enemy collision
for enemy in enemies:
if player.get_rect().colliderect(enemy.get_rect()) and player.invincible == 0:
player.lives -= 1
player.invincible = 60 # 1 second of invincibility
if player.lives <= 0:
game_state = "game_over"
# Check for goal collision
if player.get_rect().colliderect(goal.get_rect()):
game_state = "win"
# Drawing
screen.fill(BACKGROUND_COLOR)
# Draw clouds
for cloud in clouds:
pygame.draw.circle(screen, (220, 220, 220), (cloud[0], cloud[1]), 30)
pygame.draw.circle(screen, (220, 220, 220), (cloud[0] + 20, cloud[1] - 10), 25)
pygame.draw.circle(screen, (220, 220, 220), (cloud[0] + 40, cloud[1]), 30)
# Draw platforms
for platform in platforms:
platform.draw(screen)
# Draw coins
for coin in coins:
coin.draw(screen)
# Draw enemies
for enemy in enemies:
enemy.draw(screen)
# Draw goal
goal.draw(screen)
# Draw player
player.draw(screen)
# Draw UI
score_text = font.render(f"Score: {player.score}", True, TEXT_COLOR)
lives_text = font.render(f"Lives: {player.lives}", True, TEXT_COLOR)
screen.blit(score_text, (10, 10))
screen.blit(lives_text, (WIDTH - 120, 10))
# Draw instructions
controls_text = font.render("Arrow Keys: Move | Space: Jump", True, TEXT_COLOR)
screen.blit(controls_text, (WIDTH//2 - controls_text.get_width()//2, HEIGHT - 30))
# Draw game over or win message
if game_state == "game_over":
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 180))
screen.blit(overlay, (0, 0))
game_over_text = font.render("GAME OVER", True, (255, 50, 50))
restart_text = font.render("Press SPACE to Restart", True, TEXT_COLOR)
screen.blit(game_over_text, (WIDTH//2 - game_over_text.get_width()//2, HEIGHT//2 - 50))
screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 10))
elif game_state == "win":
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 50, 0, 180))
screen.blit(overlay, (0, 0))
win_text = font.render("LEVEL COMPLETE!", True, (50, 255, 50))
score_text = font.render(f"Final Score: {player.score}", True, TEXT_COLOR)
restart_text = font.render("Press SPACE to Play Again", True, TEXT_COLOR)
screen.blit(win_text, (WIDTH//2 - win_text.get_width()//2, HEIGHT//2 - 50))
screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, HEIGHT//2))
screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 50))
# Update display
pygame.display.flip()
# Cap the frame rate
clock.tick(60)
pygame.quit()
sys.exit()
How to Play
- Use the LEFT and RIGHT arrow keys to move your character
- Press SPACE to jump
- Collect all the gold coins for points
- Avoid the purple enemies or you'll lose a life
- Reach the green flag at the top right to win
- You have 3 lives - if you lose them all, the game ends
- Press SPACE to restart after game over or winning
- Press ESC to quit the game
Game Features
- Player movement with physics (gravity, jumping)
- Platforms to jump on
- Collectible coins with animation
- Moving enemies to avoid
- Lives system
- Win condition (reach the flag)
- Game over screen
- Score tracking
- Visual feedback for player actions
- Animated elements (coins, player movement)
- Background elements (clouds)
This game demonstrates the core concepts of a platformer game. You can extend it by adding more levels, power-ups, different enemy types, or sound effects.