Pygame Basic Window Tutorial – Complete Guide

The realm of game development is expansive and full of potential. It is a consistently innovating field, combining imagination with technical execution. One of the tools available to us that can act as a gateway to this exciting universe is Pygame.

What is Pygame?

Pygame is a set of Python modules designed specifically for game development. It provides us with the necessary tools to create fully featured video games and multimedia programs, all freely available and open source. Pygame is versatile and can be paired with many other Python libraries to further extend functionality.

What Can You Do With Pygame?

With Pygame, you can create a plethora of games ranging from simple 2D puzzles to complex interactive video games. It provides tools for sound and visual effects, enabling extensive game personalization. You’re also able to create window interfaces and handle events in your gaming applications, which is exactly what we’ll be looking at in this tutorial.

Why Learn Pygame?

Aspiring game developers, listen up! Pygame offers an accessible entry into game development. Learning Pygame equips you with the foundational skills required in game design by teaching important concepts like game loops, sprite animation, and event handling.

For experienced Python coders who haven’t braved the gaming realm just yet, Pygame presents a fun and engaging challenge to push boundaries and learn something new – after all, who doesn’t love playing games? Now you’ll be able to build your own.

Sure, cracking a complicated algorithm has its thrill. But watching your code transform into a lively, interactive game – that’s magic. Who knows, you just might be the one to design the next big indie game!

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

Installing Pygame

Before we dive into the coding, let’s first install and setup Pygame. If you have Python already installed, installing Pygame is as easy as running the following command in your terminal.

pip install pygame

On completing the installation, you can check if Pygame has installed correctly by importing it in a Python program.

import pygame

If there are no errors, congratulations! You are all set to start developing with Pygame.

Initializing Pygame and Creating a Window

The first step in creating a Pygame application is initializing the Pygame modules using pygame.init() and creating a window where our game will display.

import pygame
pygame.init()

# Create a window with width=800 and height=600
window = pygame.display.set_mode((800, 600))

Game Loop in Pygame

The heart of any game is its game loop. In Pygame, the game loop controls the game flow and checks for various events like mouse clicks or key presses. Here’s how a basic game loop looks in Pygame.

import pygame

pygame.init()
window = pygame.display.set_mode((800, 600))
running = True

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

Loading and Displaying Images in Pygame

To make our game visually appealing, we can use Pygame’s functionality to load and display images. Below is the code to display an image on our Pygame window.

import pygame

pygame.init()

window = pygame.display.set_mode((800, 600))
cat_img = pygame.image.load('cat.png')

window.blit(cat_img, (0, 0))
pygame.display.update()

running = True

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

pygame.quit()

Ensure that the image ‘cat.png’ is in the same directory as your Python script. If the image loads up properly, you can see it displayed on your Pygame window when you run the script.

In the next part of our guide, we’ll be teaching you how to handle player interaction by detecting and responding to keyboard events. Stay tuned!

Handling Keyboard Input in Pygame

Most games require user interaction. In Pygame, we can listen for keyboard input within our game loop using the pygame.key.get_pressed() function. Let’s move our image in response to arrow key presses with the following added code:

import pygame

pygame.init()

window = pygame.display.set_mode((800, 600))
cat_img = pygame.image.load('cat.png')
cat_x = 0
cat_y = 0

running = True

#game loop
while running:
    pressed_keys = pygame.key.get_pressed()
    if pressed_keys[pygame.K_UP]: cat_y -= 5
    if pressed_keys[pygame.K_DOWN]: cat_y += 5
    if pressed_keys[pygame.K_LEFT]: cat_x -= 5
    if pressed_keys[pygame.K_RIGHT]: cat_x += 5

    window.fill((0, 0, 0))
    window.blit(cat_img, (cat_x, cat_y))
    pygame.display.update()

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

pygame.quit()

In this code, we’ve added variables for cat_x and cat_y, which represent the position of our cat image. Then inside our game loop, we check for key presses and adjust the image’s coordinates accordingly.

Playing Sounds in Pygame

Sound effects and audio can greatly enhance gameplay. Pygame allows us to easily play sound files. Let’s add a meow sound that plays whenever the cat moves.

First, load the sound file:

meow_sound = pygame.mixer.Sound('meow.wav')

Then, play the sound whenever the cat moves:

if pressed_keys[pygame.K_UP]: 
    cat_y -= 5
    meow_sound.play()

Do the same for the other movements.

Implement Collision Detection

Collision detection is vital in many game scenarios that require interactions between game objects. Let’s implement a simple collision between our cat and a new dog image.

Firstly, load the dog image and set its position:

dog_img = pygame.image.load('dog.png')
dog_rect = dog_img.get_rect(topleft=(400, 300))

Then, create a similar rectangular object for the cat.

cat_rect = cat_img.get_rect(topleft=(cat_x, cat_y))

Now, we can check for collision inside our game loop:

if cat_rect.colliderect(dog_rect):
    print("Cat collided with the dog!")

If the collision is true, this prints a collision message.

Building a Complete Game

So far, we’ve covered key concepts: displaying images, handling keyboard inputs, playing sounds, and detecting collisions. The final step is putting it all together to create an engaging game; maybe a game where a cat has to avoid a dog while collecting points. The possibilities are endless, and we encourage you to use your creativity and explore more Pygame concepts. Happy gaming!

Animating Sprites in Pygame

Creating frame-based animations is a key aspect of game programming. Pygame makes animating sprites (game characters or objects) simple. Let’s expand on our game and make our ‘cat’ perform a basic animation.

First, we need to load a series of images for the cat. We can have different images of the cat where each image represents a unique position of the cat’s movement. For example:

cat_frames = [pygame.image.load(f'cat_{i}.png') for i in range(4)]

This code assumes that we have 4 images – ‘cat_0.png’, ‘cat_1.png’, ‘cat_2.png’, and ‘cat_3.png’ – each representing the different stages of the cat’s movement.

Next, we’ll want to display a different frame for preset intervals. This is accomplished by implementing a frame counter, like so:

clock = pygame.time.Clock()
frame_count = 0

# inside the game loop
while running:
    clock.tick(30) # this locks the game to 30 frames per second 
    frame_count += 1
    window.blit(cat_frames[frame_count % 4], (cat_x, cat_y))

This uses Pygame’s clock object to manage the frame rate of our game and uses the modulus operator to cycle through our cat frame images.

Game Score and Display Text

Most games maintain a scoring system. Let’s display a score that increases as the cat moves around the screen.

To display text in Pygame, you’ll need to choose a font and size, and then render the text. Here’s how you can create a score counter:

font = pygame.font.Font(None, 36)
score = 0

# Inside the game loop, under the key events
if pressed_keys[pygame.K_UP]: 
    cat_y -= 5
    score += 1
    meow_sound.play()

# At the end of the game loop
text = font.render(f'Score: {score}', True, (255, 255, 255))
window.blit(text, (10, 10))
pygame.display.flip()

In this code, the score increases by one each time the cat moves up. The score is then rendered as a white text object and displayed on the top left of the window.

Game Over and Restarting Game

A basic “Game Over” mechanism can be implemented in our game. Here’s how we can display a “Game Over” message when the cat collides with the dog:

font = pygame.font.Font(None, 72)
game_over_text = font.render('Game Over', True, (255, 0, 0))

# Inside the collision check
if cat_rect.colliderect(dog_rect):
    window.blit(game_over_text, (250, 250))
    pygame.display.flip()
    pygame.time.wait(2000)
    running = False

This code prints a “Game Over” message at the center of the screen when the cat collides with the dog, pauses for two seconds, and then sets ‘running’ to False to exit the game loop.

Games usually provide an option to try again after game over. This could be as simple as wrapping your game loop in another loop, and restarting whenever the player chooses to continue.

Moving On From Here

We’ve now introduced core gaming concepts with Pygame. However, the great thing about game programming is that there’s always more to learn! You can explore more advanced topics in Pygame, such as blitting and scrolling, creating tile-based games, adding artillery and obstacles, loading and saving game state, and even transitioning to 3D games. Happy coding, devs!

Where to Go Next

Congrats on making it this far! By now, you’ve gotten a taste of what game development with Pygame entails and you may wonder, what’s next? You’re just getting started on your exciting journey of understanding game creation and there’s a limitless world waiting for you to code it into existence!

To further your learning, we recommend you to explore our comprehensive Python Mini-Degree at Zenva Academy. This collection of courses covers an array of Python programming topics, from the basics to advanced concepts. You’ll learn about object-oriented programming, coding algorithms, and also game and app development. The curriculum offers an immersive learning experience with real-world projects, including designing arcade games and chatbots. The program caters to both beginners and experienced programmers, ensuring everyone can learn at their own pace.

Additionally, to expand your Python acumen even more, check out our wide collection of Python courses. Each course is designed to be engaging, practical, and up-to-date with the latest industry needs.

Flourish your coding abilities and unfold unlimited opportunities in the realm of Python with us. Happy coding!

Conclusion

Now you’re informed about Pygame and have taken your first steps into game development! It’s an exciting space to be in, with so much more to learn and experiment. And remember, behind every great game is a development team full of creativity, technical skill, and perseverance. You’re now part of this vibrant community!

Whether you’re looking to create the next big indie game, or simply want a fun way to enhance your Python skills, at Zenva Academy, we are here to help you reach your goals. Consider joining our comprehensive Python Mini-Degree program to expand your programming abilities further and step into exciting new challenges. Happy coding, and let the game development journey continue!

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.