![]()
Here’s a step-by-step guide to Building a Simple Game with Pygame .
Step 1: Install Pygame
First, ensure you have Pygame installed. Run:
pip install pygame
Check the installation:
import pygame
print(pygame.__version__)
Step 2: Set Up the Game Window
Create a basic game window with width, height, and a game loop.
import pygame
# Initialize pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Pygame Game")
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Quit pygame
pygame.quit()
✔ Creates a game window
✔ Listens for the close event
Step 3: Add a Player (Character)
Load an image for the player and display it.
# Load player image
player_img = pygame.image.load("player.png") # Add an image file in the same folder
player_x, player_y = 100, 100 # Initial position
while running:
screen.fill((255, 255, 255)) # Clear the screen
# Draw player
screen.blit(player_img, (player_x, player_y))
pygame.display.flip() # Refresh screen
✔ Loads and displays a player sprite
✔ Clears the screen before redrawing
Step 4: Move the Player
Use arrow keys to move the player.
speed = 5 # Player speed
while running:
screen.fill((255, 255, 255)) # Clear screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Get key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: player_x -= speed
if keys[pygame.K_RIGHT]: player_x += speed
if keys[pygame.K_UP]: player_y -= speed
if keys[pygame.K_DOWN]: player_y += speed
screen.blit(player_img, (player_x, player_y))
pygame.display.flip()
✔ Moves the player using arrow keys
Step 5: Add an Enemy
Let’s add an enemy that moves left and right.
enemy_img = pygame.image.load("enemy.png")
enemy_x, enemy_y = 400, 300
enemy_speed = 3
while running:
screen.fill((255, 255, 255))
# Enemy movement
enemy_x += enemy_speed
if enemy_x >= WIDTH - 50 or enemy_x <= 0:
enemy_speed *= -1 # Change direction
screen.blit(enemy_img, (enemy_x, enemy_y))
screen.blit(player_img, (player_x, player_y))
pygame.display.flip()
✔ Adds an enemy that moves left and right
Step 6: Collision Detection
Detect if the player touches the enemy.
# Collision detection
player_rect = pygame.Rect(player_x, player_y, 50, 50)
enemy_rect = pygame.Rect(enemy_x, enemy_y, 50, 50)
if player_rect.colliderect(enemy_rect):
print("Game Over")
running = False
✔ Ends the game when the player collides with the enemy
Step 7: Add Score & Display Text
Keep track of the score and display it.
font = pygame.font.Font(None, 36) # Load font
score = 0
while running:
screen.fill((255, 255, 255))
score_text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(score_text, (10, 10))
screen.blit(player_img, (player_x, player_y))
screen.blit(enemy_img, (enemy_x, enemy_y))
pygame.display.flip()
✔ Displays the score at the top-left
Step 8: Winning and Losing Conditions
Let’s add a win condition and restart on loss.
if player_x > WIDTH - 50: # Reached the right side
print("You Win!")
running = False
if player_rect.colliderect(enemy_rect): # Collided with enemy
print("Game Over")
running = False
✔ Ends the game if the player wins or loses
Step 9: Add Background Music & Sound Effects
Load and play background music and effects.
pygame.mixer.init()
pygame.mixer.music.load("background.mp3")
pygame.mixer.music.play(-1) # Loop indefinitely
jump_sound = pygame.mixer.Sound("jump.wav")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jump_sound.play() # Play jump sound
✔ Plays music and jump sound effects
Final Game Code (Complete)
Here’s a full playable version.
import pygame
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Game")
# Load images
player_img = pygame.image.load("player.png")
enemy_img = pygame.image.load("enemy.png")
# Player attributes
player_x, player_y = 100, 500
speed = 5
# Enemy attributes
enemy_x, enemy_y = 400, 500
enemy_speed = 3
# Score
font = pygame.font.Font(None, 36)
score = 0
# Game loop
running = True
while running:
screen.fill((255, 255, 255))
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: player_x -= speed
if keys[pygame.K_RIGHT]: player_x += speed
# Enemy movement
enemy_x += enemy_speed
if enemy_x >= WIDTH - 50 or enemy_x <= 0:
enemy_speed *= -1 # Reverse direction
# Collision detection
player_rect = pygame.Rect(player_x, player_y, 50, 50)
enemy_rect = pygame.Rect(enemy_x, enemy_y, 50, 50)
if player_rect.colliderect(enemy_rect):
print("Game Over")
running = False
# Display score
score_text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# Draw player and enemy
screen.blit(player_img, (player_x, player_y))
screen.blit(enemy_img, (enemy_x, enemy_y))
pygame.display.flip() # Refresh screen
pygame.quit()
✔ Full playable game with movement, enemy, score, and collision detection
