What is Pygame?
Pygame is a popular Python library used for creating 2D games and multimedia applications. It provides functions for graphics, sound, input handling, and game physics, making it easier to build interactive applications.
Key Features of Pygame
✔ Cross-Platform – Works on Windows, macOS, and Linux
✔ Hardware-Accelerated Graphics – Uses SDL (Simple DirectMedia Layer) for fast rendering
✔ Supports Sound and Music – Built-in modules for handling audio
✔ Handles Input Devices – Works with keyboards, mice, and game controllers
✔ Easy to Learn – Ideal for beginners and hobbyists
1. Installing Pygame
To install Pygame, run the following command:
pip install pygame
Once installed, verify by running:
import pygame
print(pygame.__version__)
✔ Displays the installed Pygame version
2. Creating a Basic Pygame Window
Every Pygame program starts with initialization and a game loop.
import pygame
# Initialize Pygame
pygame.init()
# Create a window
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My First Pygame Window")
# Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Check if the user closes the window
running = False
# Quit Pygame
pygame.quit()
✔ Creates a window with a size of 800×600 pixels
✔ Handles the close button event properly
3. Adding Colors and Shapes
You can draw shapes like rectangles, circles, and lines using pygame.draw
.
# Define colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Fill the screen with white
screen.fill(WHITE)
# Draw a red rectangle
pygame.draw.rect(screen, RED, (50, 50, 200, 100))
# Draw a blue circle
pygame.draw.circle(screen, BLUE, (400, 300), 50)
# Update display
pygame.display.flip()
✔ Displays a rectangle and a circle on the screen
4. Handling Keyboard and Mouse Events
Pygame allows you to detect key presses and mouse clicks.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN: # Detects key press
if event.key == pygame.K_w:
print("W Key Pressed!")
elif event.type == pygame.MOUSEBUTTONDOWN: # Detects mouse click
print(f"Mouse Clicked at {event.pos}")
✔ Detects when a key is pressed
✔ Prints mouse click coordinates
5. Adding Images (Sprites)
Pygame allows loading and displaying images as sprites.
# Load an image
player_image = pygame.image.load("player.png")
# Display the image
screen.blit(player_image, (100, 100))
pygame.display.flip()
✔ Loads and displays a sprite at (100,100) coordinates
6. Adding Movement
We can move a sprite using the arrow keys.
player_x, player_y = 100, 100 # Initial position
speed = 5
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed() # Get key states
if keys[pygame.K_LEFT]: # Move left
player_x -= speed
if keys[pygame.K_RIGHT]: # Move right
player_x += speed
if keys[pygame.K_UP]: # Move up
player_y -= speed
if keys[pygame.K_DOWN]: # Move down
player_y += speed
screen.fill(WHITE) # Clear the screen
screen.blit(player_image, (player_x, player_y)) # Draw player
pygame.display.flip() # Update display
✔ Moves the player using arrow keys
✔ Clears the screen and redraws the image each frame
7. Adding Sound Effects
Pygame supports sound effects and background music.
# Load sound effect
jump_sound = pygame.mixer.Sound("jump.wav")
# Play sound when spacebar is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jump_sound.play()
✔ Plays a jump sound when the spacebar is pressed
8. Game Loop and FPS (Frames Per Second)
To control game speed, we use a clock to manage FPS.
clock = pygame.time.Clock()
while running:
screen.fill(WHITE) # Clear screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip() # Refresh screen
clock.tick(60) # Limit FPS to 60
✔ Runs the game at 60 FPS for smooth performance
9. Adding Collision Detection
We can check if two objects collide using pygame.Rect
.
player_rect = pygame.Rect(player_x, player_y, 50, 50)
enemy_rect = pygame.Rect(400, 300, 50, 50)
if player_rect.colliderect(enemy_rect):
print("Collision Detected!")
✔ Detects when two rectangles overlap
10. Complete Mini-Game Example
Here’s a simple Pygame character movement example:
import pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame Character Movement")
# Colors
WHITE = (255, 255, 255)
# Load player
player = pygame.image.load("player.png")
player_x, player_y = 100, 100
speed = 5
# Game loop
running = True
while running:
screen.fill(WHITE) # Clear screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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, (player_x, player_y)) # Draw player
pygame.display.flip() # Update display
pygame.quit()
✔ Moves the player using arrow keys
✔ Handles quitting properly