Pygame is a cross-platform set of Python modules designed for writing video games. It is built on top of the Simple DirectMedia Layer (SDL) library and provides easy-to-use functions and classes for game development. With Pygame, you can handle graphics, sound, input devices, and other game-related functionalities.
Before starting, ensure that you have Pygame installed. You can install it using pip:
pip install pygame
To get started, we need to import the Pygame module and other required libraries:
import pygame
import random
import sys
Next, we need to initialize Pygame to use its features:
pygame.init()
Let's create the game window and set its dimensions:
# Set the window dimensions
WINDOW_WIDTH, WINDOW_HEIGHT = 800, 600
# Create the game window
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Basic 2D Game")
In this step, we will load the player's image and display it on the screen:
# Load the player image
player_image = pygame.image.load("player.png")
# Get the rect of the player image for positioning
player_rect = player_image.get_rect()
# Position the player at the center of the screen vertically and near the bottom horizontally
player_rect.midbottom = (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 20)
# Function to draw the player on the screen
def draw_player():
screen.blit(player_image, player_rect)
Now, let's implement the logic to handle user input and move the player:
# Player movement speed
player_speed = 5
# Function to update player movement
def update_player():
# Get the state of the keyboard keys
keys = pygame.key.get_pressed()
# Move player left
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.x -= player_speed
# Move player right
if keys[pygame.K_RIGHT] and player_rect.right < WINDOW_WIDTH:
player_rect.x += player_speed
Let's create enemy sprites that will be randomly spawned:
# Load the enemy image
enemy_image = pygame.image.load("enemy.png")
# List to store enemy rectangles
enemies = []
# Function to create a new enemy
def create_enemy():
enemy_rect = enemy_image.get_rect()
enemy_rect.topleft = (random.randint(0, WINDOW_WIDTH - enemy_rect.width), 0)
enemies.append(enemy_rect)
Now, we will randomly spawn enemies at regular intervals:
# Enemy spawn timer
SPAWN_ENEMY_EVENT = pygame.USEREVENT
pygame.time.set_timer(SPAWN_ENEMY_EVENT, 1000) # Spawn an enemy every 1000 milliseconds
# Function to update enemy positions and spawn new enemies
def update_enemies():
for enemy_rect in enemies[:]:
enemy_rect.y += 5 # Move enemy down
if enemy_rect.top > WINDOW_HEIGHT:
enemies.remove(enemy_rect)
for event in pygame.event.get():
if event.type == SPAWN_ENEMY_EVENT:
create_enemy()
Implement collision detection between the player and enemies:
def check_collision():
for enemy_rect in enemies:
if player_rect.colliderect(enemy_rect):
return True
return False
A game loop is a fundamental concept in game development. It is responsible for updating the game state and rendering the game elements.
# Game loop variables
FPS = 60
clock = pygame.time.Clock()
Now, let's update the game elements inside the game loop:
def update_game():
update_player()
update_enemies()
if check_collision():
# Game over logic (to be implemented later)
pass
Finally, we will draw the game elements to the screen inside the game loop:
def draw_game():
screen.fill((0, 0, 0)) # Fill the screen with black color
draw_player()
for enemy_rect in enemies:
screen.blit(enemy_image, enemy_rect)
# Update the display
pygame.display.flip()
Let's implement a simple scoring mechanism:
score = 0
SCORE_FONT = pygame.font.Font(None, 36)
def update_score():
global score
score += 1
Show the score on the game window:
def draw_score():
score_surface = SCORE_FONT.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(score_surface, (10, 10))
Let's create a game over screen and end the game when the player collides with an enemy:
def show_game_over():
game_over_surface = SCORE_FONT.render("Game Over", True, (255, 0, 0))
screen.blit(game_over_surface, (WINDOW_WIDTH // 2 - 100, WINDOW_HEIGHT // 2))
pygame.display.flip()
pygame.time.delay(2000) # Show the game over screen for 2 seconds
pygame.quit()
sys.exit()
import pygame
import random
import sys
pygame.init()
# Set the window dimensions
WINDOW_WIDTH, WINDOW_HEIGHT = 800, 600
# Create the game window
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Basic 2D Game")
# Load the player image
player_image = pygame.image.load("player.png")
player_rect = player_image.get_rect()
player_rect.midbottom = (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 20)
player_speed = 5
# Load the enemy image
enemy_image = pygame.image.load("enemy.png")
enemies = []
# Enemy spawn timer
SPAWN_ENEMY_EVENT = pygame.USEREVENT
pygame.time.set_timer(SPAWN_ENEMY_EVENT, 1000)
# Game loop variables
FPS = 60
clock = pygame.time.Clock()
# Score
score = 0
SCORE_FONT = pygame.font.Font(None, 36)
def create_enemy():
enemy_rect = enemy_image.get_rect()
enemy_rect.topleft = (random.randint(0, WINDOW_WIDTH - enemy_rect.width), 0)
enemies.append(enemy_rect)
def update_enemies():
for enemy_rect in enemies[:]:
enemy_rect.y += 5
if enemy_rect.top > WINDOW_HEIGHT:
enemies.remove(enemy_rect)
for event in pygame.event.get():
if event.type == SPAWN_ENEMY_EVENT:
create_enemy()
def draw_player():
screen.blit(player_image, player_rect)
def draw_score():
score_surface = SCORE_FONT.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(score_surface, (10, 10))
def check_collision():
for enemy_rect in enemies:
if player_rect.colliderect(enemy_rect):
return True
return False
def update_player():
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.x -= player_speed
if keys[pygame.K_RIGHT] and player_rect.right < WINDOW_WIDTH:
player_rect.x += player_speed
def update_score():
global score
score += 1
def show_game_over():
game_over_surface = SCORE_FONT.render("Game Over", True, (255, 0, 0))
screen.blit(game_over_surface, (WINDOW_WIDTH // 2 - 100, WINDOW_HEIGHT // 2))
pygame.display.flip()
pygame.time.delay(2000)
pygame.quit()
sys.exit()
def update_game():
update_player()
update_enemies()
update_score()
if check_collision():
show_game_over()
def draw_game():
screen.fill((0, 0, 0))
draw_player()
for enemy_rect in enemies:
screen.blit(enemy_image, enemy_rect)
draw_score()
pygame.display.flip()
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
update_game()
draw_game()
clock.tick(FPS)
No terms have been published for this module.
Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.
Skip to the Next Question