Pygame Display Tutorial – Complete Guide

Understanding Pygame Display

Welcome to our tutorial on Pygame Display! If you are interested in creating stunning visuals for games using Python, you’re in the right place. Not only will you learn about a key concept in game development, but you’ll also gather the knowledge required to make your games visually pleasing and interactive.

What is Pygame Display?

Pygame Display is a module in the Pygame library, used primarily for game development. This handy module lets you create and manage the game window in which your game will be running and seen by players.

Why Should I Learn Pygame Display?

The knowing your way around Pygame Display is crucial for aspiring game developers or those seeking to improve their Python skills. Here’s why:

  • It establishes the groundwork for high-quality games by helping you manage the game screen.
  • Understanding Pygame Display guides you in implementing essential aspects such as changing the screen resolution or adding full-screen modes to your games.
  • Most importantly, knowledge of Pygame Display makes it easier to understand the visual aspects of game creation in Python.

Developing a strong grasp of Pygame Display will give you the edge in making your games visually immersive and dynamic. In the upcoming sections, we delve deeper into its practical aspects and share some examples that will bring it closer to reality.

An Introductory Journey into Pygame Display

In this first part of our coding tutorial, let’s begin our journey by creating a simple window using Pygame and Pygame Display. Note how we comment on every line to explain the process:

import pygame
pygame.init() # we initialize all the modules required for Pygame

# Set the dimensions for the game window
screen_width, screen_height = 800, 600
game_window = pygame.display.set_mode((screen_width, screen_height))

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

pygame.quit()

This simple piece of code creates an 800 x 600 window for our hypothetical game, that can be closed when the player is done. The Pygame Display takes center stage in setting up the scene for players to dive in!

Diving Deeper into Pygame Display

As we progress, let’s learn to customize our game window a little more. Remember, customizing your game screen can enhance the player’s experience and make your game stand out.

A fetching feature is changing the title of the game window, which we can achieve by using pygame.display.set_caption():

import pygame
pygame.init()

# Set the dimensions for the game window
screen_width, screen_height = 800, 600
game_window = pygame.display.set_mode((screen_width, screen_height))

# Setting a custom title for the game window
pygame.display.set_caption('My Awesome Game')

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

pygame.quit()

This snippet titles our game window as ‘My Awesome Game’, lending it a personal touch and enhancing recognition.

Adding Finishing Touches to Our Game Window

In addition to setting a custom title, Pygame Display offers ways to manage visibility or even change the game’s icon. We’ll explore both of these aspects, helping to make the game feel like our distinctive creation.

import pygame
pygame.init()

# Set the dimensions for the game window
screen_width, screen_height = 800, 600
game_window = pygame.display.set_mode((screen_width, screen_height))

# Setting a custom title for the game window
pygame.display.set_caption('My Awesome Game')

# Setting a custom icon for the game window
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

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

pygame.quit()

With this, we have set a custom icon and created an impressive game window, all with the help of Pygame Display.

Continue Learning with Zenva

Feeling excited about what you’ve learned so far? Now imagine mastering these skills and creating games that others can’t wait to play. We at Zenva help those at the start of their coding journey and beyond, with a wide range of content, tutorials, and resources such as our Python Mini-Degree. Our Python Mini-Degree is a comprehensive curriculum designed to teach Python from scratch and apply it in actual projects, including game development.

Conclusion

By comprehending Pygame Display and understanding its important role in game development, you have unlocked a powerful feature of Python that can significantly enhance the visual appeal of your games. We learned what Pygame Display is, the various functionalities it offers, and how to use it effectively to create and customize game windows.

But why stop your learning journey here? Dive deeper into Python and accelerate your game development skills by checking our comprehensive Python Mini-Degree. Remember, your path to game development mastery is only a course away!

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

Handling Screen Modes with Pygame Display

Moving on from the title and icon, Pygame Display introduces an exciting feature: different screen modes. We can alter these modes to suite the purpose of our game, enhancing player comfort and experience.

The set_mode() function takes in additional arguments that let us change screen modes. Let’s have a look:

import pygame
pygame.init()

# Fullscreen mode
game_window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

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

pygame.quit()

In the snippet above, we established a game window that opens in fullscreen mode. Notice how we don’t specify the dimensions of the window. Instead, we input 0,0 in place of the dimensions.

Changing Screen Modes During Game

The flexibility of Pygame Display allows us to alter screen modes during the gameplay. This means the player can switch to different modes like fullscreen, windows mode, or resizable window mode on the fly!

import pygame
pygame.init()

# Fullscreen mode
game_window = pygame.display.set_mode((800, 600))

# Our game's Main Loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_f:
                pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
            elif event.key == pygame.K_w:
                pygame.display.set_mode((800, 600))
        elif event.type == pygame.QUIT:
            running = False

pygame.quit()

When the player hits the ‘f’ key, our game switches to fullscreen mode, and when the ‘w’ key is pressed, it reverts back to window mode. This interactive feature accommodates various user preferences, immensely improving user experience.

Introducing Pygame Double Buffer

Double buffering is a technique where computations are performed on a hidden buffer while displaying another finished buffer on the screen. This technique reduces visible distortions that can occur while updating the screen.

import pygame
pygame.init()

# Fullscreen mode with double buffering
game_window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN <a href="https://gamedevacademy.org/pygame-fullscreen-tutorial-complete-guide/" title="Pygame Fullscreen Tutorial – Complete Guide" target="_blank" rel="noopener">| pygame</a>.DOUBLEBUF)

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

pygame.quit()

Notice how we added pygame.DOUBLEBUF parameter to our set_mode() method. This addition will implement double buffering on our game window.

Implementing Hardware Acceleration with Pygame Display

Lastly, Pygame Display lets you boost up your game performance by introducing hardware acceleration. This feature transfers the graphical functions to the dedicated GPU, where it operates much faster.

import pygame
pygame.init()

# Fullscreen mode with hardware acceleration
game_window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.HWSURFACE)

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

pygame.quit()

We’ve added the pygame.HWSURFACE parameter to our set_mode() method which enables hardware acceleration.

Whether it’s modifying screen modes or implementing hardware acceleration, Pygame Display proves to be quite the powerful tool in your game development ventures. Fingers crossed for the next part of our tutorial, as we continue to unravel more coding secrets!

Adding Content to Our Game Window

Up until now, our game windows have been entirely blank. Let’s start filling these windows with color by using the fill() method:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

# Filling the game window with a color
game_window.fill((255, 0, 0)) # RGB value for the color red

pygame.display.flip()  # Update the full display

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

pygame.quit()

In the above snippet, we filled the entire game window with the color red. This is accomplished by calling the fill() method on our game window and passing in the RGB value for the color red.

Working with Images

Next, let’s learn how to load images to our game window. Images can take the role of player avatars, game backgrounds, enemies, or any other elements that appear in the game:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

# Loading an image
image = pygame.image.load('my_image.png')

# Placing the image at a specific location on the game screen
game_window.blit(image, (50, 50))

pygame.display.flip()

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

pygame.quit()

In the script above, we first loaded an image using pygame.image.load() and then placed it on the game screen at coordinates (50,50) using the blit() function.

Animating Images

Pygame Display also lets you animate images, making your game more visually interactive. Here, we will move an image from the left edge of the window to the right:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()  # Create a clock object to control the frames per second

# Loading an image
image = pygame.image.load('my_image.png')
x = 0

# Our game's Main Loop
running = True
while running:
    game_window.fill((255, 255, 255))
    game_window.blit(image, (x, 50))
    pygame.display.flip()
    clock.tick(60)  # Limit the while loop to a max of 60 times per second

    x += 5  # Increment the x coordinate for the image
    if x > 800:  # If image has moved off the screen, reset the x coordinate
        x = 0

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

pygame.quit()

This script displays an image on our game window and moves it from left to right. We created a clock object to control the frames per second, ensuring the animation runs smoothly.

Loading Text onto the Game Window

Lastly, let’s add some text to our game window. You can use this to design the game’s title, scoreboard, or any instructions for the user:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

# Creating a Font object
font = pygame.font.Font(None, 36)

# Creating a text surface
text = font.render("Hello, Zenva!", True, (255, 255, 255))

# Placing the text at a specific location on the game screen
game_window.blit(text, (200, 250))

pygame.display.flip()

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

pygame.quit()

This code will display the phrase “Hello, Zenva!” onto our game window. We first created a Font object and then used that Font object to render a text string, which we then blit onto our game window.

By mastering these fundamental elements of Pygame Display, you have built a broad base to start developing engaging and visually appealing games. Keep exploring, and happy coding!

Creating Game Objects with Pygame

Now that we have firmly grasped the concepts of making the game window lively let’s proceed further. Decoding the creation of game objects is crucial while developing interactive games.

Creating a Simple Square

Our first game object will be a simple square:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

pygame.draw.rect(game_window, (255, 0, 0), pygame.Rect(50, 50, 100, 100))

pygame.display.flip()

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

pygame.quit()

In the snippet, we used pygame.draw.rect() to create a red rectangle of dimensions 100×100 at position (50,50).

Animating Our Square

Things become more interesting when we animate our square:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
x = 50

# Our game's Main Loop
running = True
while running:
    game_window.fill((0, 0, 0))
    pygame.draw.rect(game_window, (255, 0, 0), pygame.Rect(x, 50, 100, 100))
    pygame.display.flip()
    clock.tick(60)

    x += 5
    if x > 800:
        x = 0

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

pygame.quit()

The code above does something akin to our previous image animation. We have a red square moving from the left edge to the right.

Creating a Circle

Expanding our knowledge, let’s create a circle:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

pygame.draw.circle(game_window, (255, 0, 0), (400, 300), 50)

pygame.display.flip()

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

pygame.quit()

We used pygame.draw.circle() to create a red circle with a radius of 50 at position (400,300).

Other Shapes and Lines

In addition to squares and circles, you may need to create other shapes or lines. Pygame Display makes creating these objects straightforward:

import pygame
pygame.init()

game_window = pygame.display.set_mode((800, 600))

# Creating a polygon
pygame.draw.polygon(game_window, (0, 255, 0), [(100, 100), (200, 50), (300, 100)])

# Creating a line
pygame.draw.line(game_window, (0, 0, 255), (400, 300), (500, 350), 3)

pygame.display.flip()

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

pygame.quit()

We’ve drawn a green polygon by connecting three points using pygame.draw.polygon() and drawn a blue line from one point to another with a thickness of 3 using pygame.draw.line().

Creating and animating game objects are elementary steps in game development. Be it a player avatar, enemy, or any moving part of your game, mastering these fundamental codes will assist you to design them!

Now, keep practicing and stay tuned for our next tutorial where we venture deeper into the exhilarating world of Pygame. Happy gaming!

Where to Go Next and How to Keep Learning

Congratulations! You’ve made impressive strides on your journey to mastering Pygame and Python. However, don’t lose momentum now. It’s time to put your learning into overdrive and continue expanding your skillset.

At Zenva, we offer a wide range of beginner to professional courses that will supercharge your career. We cater to a community of over one million learners and developers and provide them with the resources they need in programming, game development, AI, and much more.

We highly recommend our Python Mini-Degree to continue with your Python journey. This comprehensive collection includes courses that dive deeply into Python—a versatile language famed for its simplicity. You’ll learn coding basics, algorithms, object-oriented programming, game development, and app development.

Moreover, you can explore our broader array of options in Python courses. You’ll find our courses suitable for diverse learning needs, taught by qualified instructors, designed with flexibility in mind, and offering project-based learning.

Remember, the path to mastery is an ongoing journey. So, keep pushing the boundaries of your knowledge and skills. You’re just one course away from your advancement to the next level. Keep coding and happy learning!

Conclusion

Bravo! As we wrap up this exciting tutorial, we hope that you’ve found it both enlightening and engaging. It’s truly remarkable what you’ve accomplished in such a short span of time. You now have a robust understanding of Pygame Display and the creation of game objects, crucial steps in the game development process.

There’s never an end to learning and there’s always room for development. Why not use the momentum and excitement from this article to jump-start your next learning adventure with us? Check out our comprehensive Python Mini-Degree program and continue your journey towards mastery. The future of game development awaits you!

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.