Building Games with Python and Pygame library — A Beginner’s Guide

Daily Dose of Python
6 min readFeb 12, 2023

--

Python is a popular programming language known for its simplicity and versatility.

It is widely used in a variety of applications, from web development to data analysis, and even game development.

In this blog post, we will be exploring game development using Python and the Pygame library.

Pygame:

  1. Is a set of Python modules designed for writing video games.
  2. Provides functionality for creating games, including graphics, sound, and user input.
  3. Is open-source and free, making it a great choice for beginners and hobbyists.
Image Credit @pygame of wheels and Robots

Let’s walk through the process of building a simple game using Pygame.

1. Installing Pygame

2. Setting up our environment and creating the game window

3. Adding graphics.

4. Implementing user input, sound effects, and scoring.

5. Finally, put everything together and test our game.

1. Installing Pygame

To start, we need to install Pygame.

You can install Pygame using the following command in your terminal or command prompt:

pip install pygame

2. Setting up our environment and creating the game window

Once Pygame is installed, we can start by importing the Pygame library and initializing the game window.

import pygame

pygame.init()

# Set the window size
window = pygame.display.set_mode((500, 500))

# Set the window caption
pygame.display.set_caption("My Game")

# Start the game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Quit the game
pygame.quit()

This code creates a new window with a width of 500 and a height of 500.

The caption of the window is set to “My Game”. The while loop is the main game loop, and it will run until the user closes the window.

3. Adding Graphics

Now that we have our window set up, we can start adding graphics to the game. We will use Pygame’s built-in Surface class to create a background for our game.

import pygame

pygame.init()

# Set the window size
window = pygame.display.set_mode((500, 500))

# Set the window caption
pygame.display.set_caption("My Game")

# Load the background image
background = pygame.image.load("background.png").convert()

# Load game assets
ball_image = pygame.image.load("ball.png")
target_image = pygame.image.load("target.png")

# Start the game loop
running = True
while running:
# Draw the background
window.blit(background, (0, 0))

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Update the screen
pygame.display.update()

# Quit the game
pygame.quit()

In this code, we load an image file “background.png” using Pygame’s image.load method.

We also load images for the ball and target using our own image files.

We then use the blit method to draw the background on the window.

The update method is used to update the screen and display the changes.

Finally, the game quits when the user closes the window.

4. Implementing user input, sound effects, and scoring

To make our game more interactive, we can add some sound effects, user inputs and a scoring mechanism in our game.

In this example, we will add a way for the player to control the movement of the ball by using the arrow keys on their keyboard.

We can accomplish this by using the pygame.key.get_pressed() method, which returns a dictionary of all currently pressed keys.

In our game loop, we can check the value of the relevant keys in the dictionary and update the ball’s position accordingly.

Here is the updated code for our game loop:

# Set up sound effects
hit_sound = pygame.mixer.Sound("hit.wav")
# Set up game clock
clock = pygame.time.Clock()

# Define ball properties
ball_width = 40
ball_height = 40
ball_x = window_size[0] // 2
ball_y = window_size[1] // 2
ball_speed = 5
ball_direction = [random.choice([1, -1]), random.choice([1, -1])]

# Define target properties
target_width = 50
target_height = 50
target_x = random.randint(0, window_size[0] - target_width)
target_y = random.randint(0, window_size[1] - target_height)

# Set up score
score = 0

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ball_x -= ball_speed
if keys[pygame.K_RIGHT]:
ball_x += ball_speed
if keys[pygame.K_UP]:
ball_y -= ball_speed
if keys[pygame.K_DOWN]:
ball_y += ball_speed

# Move the ball
ball_x += ball_direction[0] * ball_speed
ball_y += ball_direction[1] * ball_speed

# Check for ball collision with window edges
if ball_x > window_size[0] - ball_width or ball_x < 0:
ball_direction[0] *= -1
if ball_y > window_size[1] - ball_height or ball_y < 0:
ball_direction[1] *= -1

# Check for ball collision with target
ball_rect = pygame.Rect(ball_x, ball_y, ball_width, ball_height)
target_rect = pygame.Rect(target_x, target_y, target_width, target_height)
if ball_rect.colliderect(target_rect):
hit_sound.play()
score += 1
target_x = random.randint(0, window_size[0] - target_width)
target_y = random.randint(0, window_size[1] - target_height)

screen.fill((255, 255, 255))

This code checks for a collision between the ball and the target, updates the score and plays a sound effect if there is a collision.

The score is displayed on the window and the target is reset to a new random location.

With this small change, the player can now control the movement of the ball with the arrow keys on their keyboard.

Adding user input like this is just the tip of the iceberg when it comes to building games with Python and Pygame.

You can continue to add more features and components to your game, such as obstacles, power-ups, and enemies, to make it more challenging and engaging.

Putting it all together

Here is the final and complete code for your reference:

import pygame
import random

# Initialize Pygame
pygame.init()

# Set up game window
window_size = (800, 600)
window = pygame.display.set_mode(window_size)

# Load game assets
ball_image = pygame.image.load("ball.png")
target_image = pygame.image.load("target.png")

# Set up sound effects
hit_sound = pygame.mixer.Sound("hit.wav")

# Set up game clock
clock = pygame.time.Clock()

# Define ball properties
ball_width = 40
ball_height = 40
ball_x = window_size[0] // 2
ball_y = window_size[1] // 2
ball_speed = 5
ball_direction = [random.choice([1, -1]), random.choice([1, -1])]

# Define target properties
target_width = 50
target_height = 50
target_x = random.randint(0, window_size[0] - target_width)
target_y = random.randint(0, window_size[1] - target_height)

# Set up score
score = 0

# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Check for user input
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ball_x -= ball_speed
if keys[pygame.K_RIGHT]:
ball_x += ball_speed
if keys[pygame.K_UP]:
ball_y -= ball_speed
if keys[pygame.K_DOWN]:
ball_y += ball_speed

# Move the ball
ball_x += ball_direction[0] * ball_speed
ball_y += ball_direction[1] * ball_speed

# Check for ball collision with window edges
if ball_x > window_size[0] - ball_width or ball_x < 0:
ball_direction[0] *= -1
if ball_y > window_size[1] - ball_height or ball_y < 0:
ball_direction[1] *= -1

# Check for ball collision with target
ball_rect = pygame.Rect(ball_x, ball_y, ball_width, ball_height)
target_rect = pygame.Rect(target_x, target_y, target_width, target_height)
if ball_rect.colliderect(target_rect):
hit_sound.play()
score += 1
target_x = random.randint(0, window_size[0] - target_width)
target_y = random.randint(0, window_size[1] - target_height)

# Clear the window
window.fill((255, 255, 255))

# Draw the ball and target
window.blit(ball_image, (ball_x, ball_y))
window.blit(target_image, (target_x, target_y))

# Check for ball-target collision
if ball_x >= target_x and ball_x <= target_x + target_width:
if ball_y >= target_y and ball_y <= target_y + target_height:
# Update score
score += 1
# Reset target to a new random location
target_x = random.randint(0, WIDTH - target_width)
target_y = random.randint(0, HEIGHT - target_height)
# Play a sound effect
success_sound.play()

# Display score
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
window.blit(score_text, (10, 10))

# Update display
pygame.display.update()

# Quit the game
pygame.quit()

Conclusion

In conclusion, Pygame is a great library for building games with Python.

It provides a simple and intuitive interface for creating graphical elements, handling user input, and animating your game.

Whether you are a beginner or an experienced programmer, Pygame is a great choice for building fun and engaging games.

Hope you liked this post and learned something new today :)

Do not forget to follow me *only* if you are finding any value add with my posts!

--

--

Daily Dose of Python

Come and learn something new and exciting about Python every single day! New Post every Day @ 7 PM IST.