Display Surface Quit Pygame Tutorial – Complete Guide

Welcome to this comprehensive tutorial on handling display and quit events in Pygame. If you already have a beginner level understanding of Python, then this lesson is perfect for you!

What is a display surface in Pygame?

Pygame is a widely used open source Python library for making 2D games. In Pygame, a display surface represents the visible portion of the game – the screen where all the action is displayed.

What is Pygame Quit?

The Pygame Quit function is used to safely exit Pygame. This function closes everything and cleans up the Pygame library to ensure your code finishes properly.

Why Learn About Display Surface and Pygame Quit?

Managing the game display and handling quit events are crucial for creating an interactive and user-friendly game. Whether you intend to be an indie game developer, or whether you’re just passionate about game programming, understanding how these components work in Pygame is essential.

They ensure the flexibility and robustness of your game by handling accidental shutdowns or exits and maintaining the optimal screen for gameplay.

Applying Pygame in Real Time

From simple games like Pong to more complex projects, Pygame equips you with a range of tools needed for building games. It’s beginner-friendly, and understanding Display Surface and Pygame Quit teaches you the fundamentals of handling user interactions and creating smooth gameplay.

There’s no limit to what you can achieve once you master these skills. So, buckle up, and let’s dive into some exciting examples!

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

Creating a Display in Pygame

In Pygame, we start with creating a display surface. This is essentially what we see on the screen during the gameplay.

import pygame

# Initialize Pygame
pygame.init()

# Set the size of the display
screen_width = 800
screen_height = 600

# Create the display surface
display_surface = pygame.display.set_mode((screen_width, screen_height))

In the above example, we first import and initialize Pygame. Then, we define our screen’s width and height. Finally, we create the display surface using the pygame.display.set_mode() function, which takes in a tuple representing the screen’s dimensions.

Coloring the Display Surface

Let’s now color our display surface. We’ll use the RGB (Red Green Blue) color model where every color can be obtained by combining red, green, and blue values.

import pygame

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))

# Define the RGB color
white = (255, 255, 255)

# Fill the display surface with the color
display_surface.fill(white)

pygame.display.update()

# Create a game loop to prevent the program from stopping
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

In this snippet, we’ve defined an RGB representation for white color and used the fill() function to apply that color to our display surface. We then update the display with pygame.display.update(). The game continues running in the while loop until the user quits.

Handling Pygame Quit Events

As a developer, it’s important to give players the ability to exit your game properly. This is where Pygame’s QUIT event comes into play.

import pygame

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

Here, we have a while loop that continuously checks for any events. If the Pygame QUIT event is triggered (by clicking on the close button), it calls the pygame.quit() function to exit the game.

Combining Display Setup and Event Handling

We can combine the steps to establish the display and to handle the quit event into one game loop.

import pygame

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))
white = (255, 255, 255)
display_surface.fill(white)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    pygame.display.update()

This final snippet demonstrates a complete game loop that creates a display, fills it with a color, checks for a quit event, and updates the display surface. If Pygame detects a QUIT event, it calls pygame.quit() to exit the game properly.

Adding Sprites to the Display

Moving on, let’s add a sprite (a 2D visual object) to our display. This adds more depth to our Pygame programming skills. For this example, we will be using Pygame’s built-in Sprite class.

import pygame

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))
white = (255, 255, 255)
display_surface.fill(white)

# Create a sprite
sprite = pygame.sprite.Sprite()

# Set the sprite's image
sprite.image = pygame.image.load("path_to_your_image_file")

# Set the sprite's position
sprite.rect = sprite.image.get_rect()
sprite.rect.topleft = (100, 100)

# Create a sprite group and add the sprite
group = pygame.sprite.Group(sprite)

# Draw the group on the display
group.draw(display_surface)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    pygame.display.update()

In this example, we’ve added a sprite into our game. We set an image to our sprite and position it using the topleft attribute. We then create a sprite group and draw it on the display surface. It’s always a good practice to organize your sprites into groups for easier management.

Handling Keyboard Inputs

Now that we have a visual display with our sprite, let’s make the game more interactive by handling keyboard inputs. This will allow us to control the sprite’s movement using arrow keys.

import pygame

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))
white = (255, 255, 255)
display_surface.fill(white)

sprite = pygame.sprite.Sprite()
sprite.image = pygame.image.load("path_to_your_image_file")
sprite.rect = sprite.image.get_rect()
sprite.rect.topleft = (100, 100)

group = pygame.sprite.Group(sprite)
group.draw(display_surface)

while True:
    # Fill the display surface with white color in every loop
    display_surface.fill(white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                sprite.rect.move_ip(0, -5)
            elif event.key == pygame.K_DOWN:
                sprite.rect.move_ip(0, 5)
            elif event.key == pygame.K_LEFT:
                sprite.rect.move_ip(-5, 0)
            elif event.key == pygame.K_RIGHT:
                sprite.rect.move_ip(5, 0)

    # Redraw the sprite at its new position
    group.draw(display_surface)
    pygame.display.update()

We have modified the game loop to handle keyboard inputs in this code snippet. If an arrow key is pressed, we move the sprite in that direction using move_ip() method on the sprite’s rect.

Notice that we fill the display surface with white color again before we redraw the sprite at its new position. This is necessary to clean up the old image of the sprite after it moves.

Adding Multiple Sprites and Collisions

Next, let’s add more sprites to our game and handle collisions between them. For this, we’ll create a player sprite and enemy sprites and enhance our game loop to handle collisions between them.

import pygame
import random

pygame.init()

screen_width = 800
screen_height = 600
display_surface = pygame.display.set_mode((screen_width, screen_height))
white = (255, 255, 255)
display_surface.fill(white)

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("path_to_your_player_image_file")
        self.rect = self.image.get_rect()
        self.rect.topleft = (100, 100)
        
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("path_to_your_enemy_image_file")
        self.rect = self.image.get_rect()
        self.rect.topleft = (random.randrange(screen_width), random.randrange(screen_height))

player = Player()
enemies = pygame.sprite.Group(Enemy() for _ in range(5))

all_sprites = pygame.sprite.Group(player, *enemies)

In this snippet, we have created two sprite classes: Player and Enemy. The Player sprite represents our main character, while the Enemy sprites serve as our adversaries. Enemies are randomly positioned on the display surface.

We then create a universal all_sprites group that holds all of the sprites in our game.

while True:
    display_surface.fill(white)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player.rect.move_ip(0, -5)
            elif event.key == pygame.K_DOWN:
                player.rect.move_ip(0, 5)
            elif event.key == pygame.K_LEFT:
                player.rect.move_ip(-5, 0)
            elif event.key == pygame.K_RIGHT:
                player.rect.move_ip(5, 0)
    
    # Handle collisions
    if pygame.sprite.spritecollideany(player, enemies):
        pygame.quit()

    all_sprites.draw(display_surface)
    pygame.display.update()

In our enhanced game loop, we’re controlling the Player sprite with our arrow keys and checking for collisions between it and the Enemy sprites using the function pygame.sprite.spritecollideany(). If a collision is detected, the game is quit.

Adding Sound Effects and Music

Lastly, let’s enhance the player’s experience by adding sound effects and music to our game.

To begin with, Pygame must be initialized with the mixer module.

# Initialize Pygame with the mixer module
pygame.mixer.init()
pygame.init()

Now let’s add background music to our game.

# Load and play background music
pygame.mixer.music.load("path_to_your_music_file")
pygame.mixer.music.play(-1)

Here, we first load our music file, then we play it. The -1 argument makes the music play in a loop.

Next, we’ll add a collision sound effect to our game that will play whenever our player collides with an enemy.

# Load collision sound
collision_sound = pygame.mixer.Sound("path_to_your_sound_effect")

# Play collision sound on collision
if pygame.sprite.spritecollideany(player, obstacles):
    collision_sound.play()
    pygame.quit()

In this final snippet, we’ve typical sound effect into our game. The sound will play when a collision between the player and an enemy occurs.

With all of these techniques, you’re now equipped with the knowledge to program a basic yet interactive game using Pygame! Remember, Pygame provides many more opportunities for added creativity and complexity, so feel free to experiment and create amazing new games!

What Next?

We have equipped you with some essential knowledge on handling display and quit events in Pygame. However, your journey to becoming a seasoned Python game developer doesn’t stop here. As you take your first bold steps into the world of programming, there are endless resources and learning paths ready to take you from a beginner to professional.

If you want to dig deeper into Python programming, we recommend checking out our Python Mini-Degree. This extensive program is not just about theories but the practical application of the learned skills. Our comprehensive set of courses cover a broad range of topics including coding basics, algorithms, object-oriented programming, game development, and app development. The courses are designed to provide practical skills that can be immediately applied in the job market. It comes with step-by-step projects to help you build your own Python portfolio.

Additionally, you can explore our broader range of Python courses providing a multitude of opportunities to grow as a Python developer. With Zenva, we aim to ignite your passion for learning and help propel you further into the world of Python coding and game creation.

Conclusion

In this tutorial, we’ve unlocked the fundamentals of Pygame, from crafting intuitive game displays to handling quit events, adding sprites, dealing with collisions, and enriching the player’s experience with sound effects and music. Yet, the vast realm of Python game development still holds many untapped mysteries and unexplored areas for you to dive into.

Equip yourself with the tools to shape tomorrow’s gaming landscape. Join us in our Python Mini-Degree for a deep dive into Python programming, or explore our broader range of Python courses. Exciting adventures and groundbreaking creations await you. Forge your path and create the unimaginable with Zenva!

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.