Pygame Examples Tutorial – Complete Guide

Escaping into the world of games is a treat many enjoy but have you ever wondered about the sheer joy and satisfaction of creating your own game? This notion can seem daunting, especially if you’re new to programming, but python’s Pygame library comes to the rescue. It offers an excellent platform to not just dip your toes but also hone your skills in game creation, no matter your level of expertise. So let’s dive straight in!

What is Pygame?

Pygame is an open-source module of Python used for game creation. It’s built over the highly powerful SDL library and simplifies game development, making it accessible to coding novices and facilitating the learning process.

Why Pygame?

Often, beginners find themselves bogged down by complex syntax and rules when they begin coding. Pygame changes that with its simplicity and straightforwardness.

More so, with Pygame, not only can you create games but also multimedia applications. It’s a tool with vast applications!

The Allure of Pygame

Learning Pygame equips you with the ability to create simple 2D games, and as you grow, the possibilities become endless. It puts you in the driver’s seat of your game creation journey, offering an exciting creative outlet while you learn and grow as a programmer.

Moreover, Pygame stands as a stepping stone toward more advanced game development frameworks, making learning it a valuable long-term investment for those interested in game development.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Setting up Pygame

The first thing we need to do to use Pygame is to install it. Run this command in your terminal:

pip install pygame

Creating a Pygame Window

Once the installation is complete, try creating a simple Pygame window. Let’s start by importing Pygame and initiating it:

import pygame
pygame.init()

Now, let’s create a display:

win = pygame.display.set_mode((500, 500))

This will create a window of width 500 and height 500. Note that the dimensions are passed as a tuple.

Running a Pygame Window

The following snippet runs a Pygame window until it is manually closed:

run = True
while run:
    pygame.time.delay(100)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

pygame.quit()

This loop runs indefinitely, until we manually close the window. The delay function ensures that the loop does not run too quickly, and pygame.QUIT helps in handling window closing events.

Drawing on the Window

Let’s take it a step further and draw a rectangle on this window:

pygame.draw.rect(win, (255,0,0), (x, y, width, height))
pygame.display.update()

The draw.rect function takes the window on which to draw, the color of the rectangle in RGB format, and the rectangle characteristics (x and y coordinates, width, and height). Finally, we update the display to reflect the drawn rectangle.

Moving the Rectangle

Now, let’s get our rectangle moving. For this, we’ll introduce a few extra variables and modify our game loop:

x = 50
y = 50
width = 64
height = 64
vel = 5

Here, vel defines the velocity or speed of our rectangle. To make our rectangle move, we need to capture the user inputs and accordingly alter the rectangle’s position:

keys = pygame.key.get_pressed()
    
if keys[pygame.K_LEFT]:
    x -= vel
if keys[pygame.K_RIGHT]:
    x += vel
if keys[pygame.K_UP]:
    y -= vel
if keys[pygame.K_DOWN]:
    y += vel

This code checks which arrow key is pressed and accordingly increases or decreases the x or y coordinate of the rectangle, moving it in the appropriate direction.

Adding Boundaries

Currently, our rectangle can move off-screen. To prevent this, we’ll add a few conditions:

if keys[pygame.K_LEFT] and x > vel: 
    x -= vel
if keys[pygame.K_RIGHT] and x  vel: 
    y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel: 
    y += vel

These conditions check if the rectangle is within the boundaries of our window before allowing it to move.

Loading and Displaying Sprites

Now, let’s go further by introducing a sprite to our game. First, we load the sprite:

sprite = pygame.image.load('sprite.bmp')

Next, we display the sprite in our window, replacing the rectangle:

win.blit(sprite, (x, y))

The blit function draws our sprite at coordinates (x, y).

Adding Music and Sound Effects

Finally, a game is incomplete without some sound effects and background music. Load a sound effect and play it:

effect = pygame.mixer.Sound('effect.ogg')
effect.play()

To play background music, use the music.load method:

pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)

The argument -1 will loop the music indefinitely.

Handling Sprite Collision

For a more interesting gameplay, let’s introduce collision detection. To do so we will consider each sprite as a rectangle and check if these rectangles overlap.

if sprite1_rect.colliderect(sprite2_rect):
    print('Sprites have collided!')

Here, colliderect() checks if one sprite’s rectangle has collided with the other’s. We can display or trigger certain events if a collision occurs.

Controlling Sprite Animation

Our sprite may have multiple frames for animation. To display these animations, we need to cycle through them in our game loop:

sprite_frames = [pygame.image.load('sprite1.bmp'), pygame.image.load('sprite2.bmp'), 
                  pygame.image.load('sprite3.bmp')]
frame_count = 0
win.blit(sprite_frames[frame_count//3], (x, y))
frame_count = (frame_count+1)%9

We load all frames of the sprite into a list. Then, we display each frame every third loop cycle by using integer division. The modulo operation ensures frame_count doesn’t exceed 8 and loops back to 0.

Creating Background Images

Moving on, to create a background for your game, load an image and blit it before drawing our sprite:

bg = pygame.image.load('background.bmp')
win.blit(bg, (0, 0))

Creating Parallax Backgrounds

Parallax backgrounds create a sense of depth. Let’s implement this:

bg1_x = 0
bg2_x = bg_width

win.blit(bg1, (bg1_x, 0))
win.blit(bg2, (bg2_x, 0))

bg1_x -= 1
bg2_x -= 1

if bg1_x < -bg_width:
    bg1_x = bg_width
if bg2_x < -bg_width:
    bg2_x = bg_width

Two identical images are moved leftwards to create the illusion of motion. As soon as one image goes off screen, it is repositioned at the right end resulting in a seamless transition.

Adding Text to Your Game

Finally, let’s add some text to our game. Pygame allows us to use system fonts or load our own.

font = pygame.font.SysFont(None, 35)
text = font.render('Hello player!', True, (255,255,255))
win.blit(text, (250 - text.get_width()//2, 250 - text.get_height()//2))

This code centers the text on the window. The font.render() method creates a surface that can then be drawn onto our window.

So there you have it! With these tools and knowledge, you can start creating your own simple 2D games using Pygame. Immerse yourself in this world of creativity and endless possibilities!

Continuing Your Journey

You’ve made it this far and are now equipped with the initial skills needed for game creation with Pygame! But don’t stop here. Coding, like any other skill, is honed and perfected with practice. Engaging oneself in a variety of projects will ultimately provide a comprehensive understanding and proficiency in Python and game development.

At Zenva, we are committed to providing you with the opportunity to continue your journey. We offer a broad range of beginner to professional courses in programming, game development and AI, with over 250 supported courses for you to delve deeper into topics you are passionate about. One of our flagship offerings is the Python Mini-Degree, a comprehensive and flexible collection of courses that covers essential Python programming topics, as well as more specialized subjects such as game development, AI chatbots, data science, and machine learning.

Moreover, check out our broader collection of Python courses that cater to a wide range of interests and skill levels. Remember, learning coding is a marathon, not a sprint. So keep going, and happy coding!

Conclusion

Embarking on a journey with Pygame not only provides a stepping stone towards game development but also promises an exciting venture into a world defined by creativity and logic. As a beginner or an avid programmer looking to spread their wings, Pygame offers an inviting platform to dive headlong into the world of making games, animations, and even multimedia applications. Crafting games, after all, isn’t just about the end product; the journey is where the real learning and excitement lies.

We at Zenva invite you to continue this thrilling adventure. Our Python Mini-Degree offers a comprehensive and in-depth coverage of Python and its various applications, providing the perfect platform for you to explore and elevate your skills. So grab your keyboards and immerse yourself in this fascinating journey of creation!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.