Everyone, from amateurs to experienced gamers, enjoys an immersive gaming experience. One feature that significantly elevates this experience is the full-screen mode. In Python, we can achieve this with the Pygame library. If you’re interested in creating more engaging visuals, this tutorial on Pygame Fullscreen is for you.
Table of contents
What is Pygame Fullscreen?
Pygame Fullscreen is a feature of the Pygame library in Python. Pygame is a popular and robust Python library used in game development. The fullscreen feature allows developers to expand their game display over the entire screen, providing a more immersive experience to the players.
Why Should I Learn It?
Integration of fullscreen mode in your games is an excellent skill to level up your game development journey. Not only does this augment the visual appeal of the game, but more importantly, it enhances the user experience. Thus, learning how to implement Pygame Fullscreen can significantly improve the quality of your gaming projects.
What is it for?
Working with Pygame Fullscreen is beneficial as it makes the game navigation smoother and the gameplay more enjoyable. Whether your game is simplistic or complex, implementing a fullscreen feature can make a noticeable difference by making your game appear more professional and user-friendly.
Setting Up Pygame
Before we delve into implementing fullscreen mode, let’s first set up a basic Pygame window. If you haven’t yet installed Pygame, you can do so by using pip:
pip install pygame
Now, let’s write the code to create a simple Pygame window:
import pygame # Initialize Pygame pygame.init() # Set window size win = pygame.display.set_mode((800, 600)) # Game loop run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit()
This code sets up a basic Pygame window with size 800×600. The game loop is where all events will be processed, and the pygame.QUIT event is used to handle the closure of the window.
Switching to Fullscreen
Now that we have a basic window set up, let’s learn how to switch it to fullscreen mode. For this, we will utilize pygame.display.set_mode() again, but this time with the pygame.FULLSCREEN flag as follows:
# Switch to fullscreen mode win = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
The (0, 0) makes Pygame use the resolution of your computer screen. Pygame will update the game display to cover the entire screen.
Handling Fullscreen Toggle
It’s a good idea to allow players to toggle fullscreen mode. This can be done by processing a specific event, like pressing the F11 key, to switch between windowed and fullscreen mode:
... # Game loop run = True fullscreen = False while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # Toggle fullscreen when F11 is pressed elif event.type == pygame.KEYDOWN: if event.key == pygame.K_F11: fullscreen = not fullscreen if fullscreen: win = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) else: win = pygame.display.set_mode((800, 600)) pygame.quit()
This addition to the code will enable the user to switch to and from fullscreen mode by pressing the F11 key.
Exiting From Fullscreen
The last part of this tutorial shows how to safely exit fullscreen mode. This is important for cleanly closing the game, preventing any potential software or hardware issues:
... # Game loop run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_F11): run = False # Switch back to windowed mode before exiting pygame.display.set_mode((800, 600)) ...
Now, whether the player quits the game or simply toggles off the fullscreen mode, the game will neatly switch back to windowed mode before exiting.
Handling Mouse and Keyboard Input
A crucial part of game development is catering to user input. In fullscreen mode, both mouse and keyboard inputs are usually processed in the same way they would be in windowed mode. However, with Pygame it is essential to know how to handle these inputs.
To detect mouse clicks, we use the pygame.MOUSEBUTTONDOWN event and to process keyboard inputs, we use the pygame.KEYDOWN event.
... # Game loop run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.MOUSEBUTTONDOWN: # Process mouse click pos = pygame.mouse.get_pos() print("Mouse clicked at position:", pos) elif event.type == pygame.KEYDOWN: # Process key press key = pygame.key.name(event.key) print("Key pressed:", key) ...
This snippet adds a couple of events to help process user inputs. Now, whenever a mouse button is clicked or a key is pressed, we will get an informational printout in our console.
Managing Game Elements in Fullscreen
Managing game elements such as sprites, characters, and backgrounds in fullscreen mode is no different from doing so in windowed mode. Let’s see how to add a simple sprite in our fullscreen window.
Assuming we have an image named ‘sprite.png’ in the same directory as our script, we can load this sprite and draw it on our screen:
... # Load sprite image sprite = pygame.image.load('sprite.png') # Game loop run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_F11: ... # Draw sprite win.blit(sprite, (0, 0)) # Update display pygame.display.flip() ...
This simple addition to our code will display the sprite in the top-left corner of the screen. Note the pygame.display.flip() line, this updates the entire screen and is essential to reflect the drawn elements onto it.
Using Sound and Music
Pygame supports sound and music. This will work in fullscreen mode just like it operates under windowed mode. Here’s how to easily play a music file:
... # Load music file and set volume pygame.mixer.music.load('background.mp3') pygame.mixer.music.set_volume(0.5) # Start playing music pygame.mixer.music.play(-1) # Game loop run = True while run: ... ...
The snippet above will start playing ‘background.mp3’ at 50% volume and will loop indefinitely.
We have embarked on a journey into creating an immersive fullscreen game using Pygame. Feel free to experiment with these snippets and create your own fascinating games!
Loading and Using Fonts
No game is complete without awesome text elements. Pygame allows you to use any TrueType font from your computer. Let’s add some text to our game!
... # Load font font = pygame.font.Font(None, 55) # Create text surface text = font.render('Learn with Zenva', True, (255, 255, 255)) # Game loop run = True while run: ... # Draw text win.blit(text, (350, 250)) ... ...
The snippet above loads the default pygame font at a size of 55. It then creates a surface with the text “Learn with Zenva” in white color. Here, this text is drawn to the screen at position (350,250).
Adjusting Screen Resolution
Not all screens have the same dimensions. By adjusting your game’s resolution based on the player’s screen size, your game will look great on any device!
To do this, we can use pygame’s display.get_surface() method to get the size of the current screen:
... # Get screen size screen = pygame.display.get_surface() width, height = screen.get_size() # Game loop run = True while run: # Switch fullscreen/resolution when F11 is pressed if fullscreen: win = pygame.display.set_mode((width, height), pygame.FULLSCREEN) else: win = pygame.display.set_mode((800, 600)) ...
The snippet above sets the fullscreen resolution to the size of the player’s screen. The pygame.display.set_mode() function ensures the game always fits the screen properly both in fullscreen and window mode.
Handling Multiple Sizable Game Elements
Games often include more than one game object. Let’s create a function to handle the loading and resizing of multiple images:
from pygame import transform def load_image(filename, width, height): # Load image img= pygame.image.load(filename) # Scale image scaled_img = transform.scale(img, (width, height)) return scaled_img # Load and scale images background = load_image('background.png', width, height) player = load_image('player.png', 100, 100) # Game loop run = True while run: ... # Draw images win.blit(background, (0, 0)) win.blit(player, (width//2, height//2)) ...
This function loads an image file and rescales it to the specified dimensions. Now it’s very easy to use many game assets that automatically adjust to the player’s screen size!
Animating Game Objects
Finally, Pygame allows you to animate game objects. Here’s an example of how to move an object around the screen:
... # Load player image and set speed player = load_image('player.png', 100, 100) player_speed = 2 # Player position player_x = width // 2 player_y = height // 2 # Game loop run = True while run: ... # Move player keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] or keys[pygame.K_a]: player_x -= player_speed if keys[pygame.K_RIGHT] or keys[pygame.K_d]: player_x += player_speed if keys[pygame.K_UP] or keys[pygame.K_w]: player_y -= player_speed if keys[pygame.K_DOWN] or keys[pygame.K_s]: player_y += player_speed # Draw player win.blit(player, (player_x, player_y)) ...
By pressing the arrow keys or WASD, we can move our player around! This simple example sets the cornerstone of how player control can be implemented in Python Pygame platform.
With these basics, you can now embark on your journey to create your own immersive fullscreen games with Python and Pygame. Remember, practice is key in mastering these skills. Happy coding!
Where to Go Next
With your newfound knowledge on implementing fullscreen mode in Pygame, you may be wondering where to go next. Fortunately, Python offers a breadth of possibilities in both game development and broader programming contexts. Indeed, your learning journey has only just begun!
At Zenva, we encourage our learners to keep exploring the infinite avenues of coding. We highly recommend checking out our Python Mini-Degree. This comprehensive collection of courses has been meticulously designed for beginners and covers everything from coding basics to more complex topics such as algorithms, object-oriented programming, and even game and app development. By progressing through these courses, you will get the opportunity to build your own games, algorithms, and real-world apps, thereby creating a robust portfolio of Python projects.
Consider taking your Python skills to another level by exploring our broad collection of Python courses. Whatever your goal or passion might be, whether it’s game development, data science, AI, or machine learning, we are here to support your journey in achieving the skills you need for the future you want. Remember, keep practicing, keep experimenting, and Happy Coding!
Interactive game development is an exciting sphere that combines creativity, logic, and most importantly, the joy of crafting something from scratch. Mastering Pygame and understanding key features such as fullscreen mode equips you with the indispensable tools needed to create captivating gaming experiences. But remember, the world of Python extends far beyond game development.
Whether you aim to become a Python developer, create immersive video games or explore the burgeoning field of AI and machine learning, your journey is just beginning. We invite you to dive deeper into Python, explore its vast potential, and keep adding those programming feathers to your cap. Check out our comprehensive Python Mini-Degree to further your learning journey. Remember – with patience, practice, and dedication, you are well on your way to mastering the art of coding!
FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.