Python for Game Developers in a Week
Introduction to Pygame
Your First Game Window
So far, we've covered the building blocks of Python. Now, let's use them to create something visual. We'll use a library called Pygame, which is a collection of pre-written code that makes it much easier to build games. It handles the complicated parts of drawing graphics, playing sounds, and getting input from the keyboard and mouse.
First, you need to install it. Open your terminal or command prompt and type the following command. This uses pip, Python's package manager, to download and install Pygame.
pip install pygame
Once it's installed, you can start coding. The first step in any Pygame program is to import the library and initialize it. Then, we'll create a window to hold our game.
import pygame
# Initialize all the Pygame modules
pygame.init()
# Set screen dimensions
screen_width = 800
screen_height = 600
# Create the game window
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('My First Game Window')
Let's break that down:
import pygamemakes the library's code available to our program.pygame.init()is a crucial step that starts up all the background modules Pygame needs to run.pygame.display.set_mode()creates the actual window. We pass it a tuple(width, height)to define its size. This function returns aSurfaceobject, which is like a blank canvas we can draw on. We store this in a variable calledscreen.pygame.display.set_caption()sets the text that appears in the title bar of the window.
If you run this code, a black window will pop up and immediately disappear. That's because the program finishes instantly. To keep the window open, we need a game loop.
The Game Loop
Every game, from the simplest to the most complex, is built around a central concept: the game loop. It's a loop that runs continuously as long as the game is active. Its job is to keep things moving and responding to you, the player.
A game loop performs three main tasks over and over, many times per second:
- Handle Events: Check for any input from the player, like key presses, mouse clicks, or closing the window.
- Update State: Change the game's data based on the input or passage of time. For example, moving a character or decreasing a timer.
- Draw: Render all the game elements onto the screen based on their current state.
In Python, we can create this with a while loop. We'll use a variable, let's call it running, to control the loop. When we want the game to end, we just set running to False.
import pygame
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('My First Game Window')
# Game loop variable
running = True
while running:
# --- Event Handling ---
# Check for every event in the queue
for event in pygame.event.get():
# If the user clicks the window's close button
if event.type == pygame.QUIT:
running = False
# --- Drawing ---
# Fill the background with a color (R, G, B)
screen.fill((255, 255, 255)) # White
# Update the full display surface to the screen
pygame.display.flip()
# Quit Pygame and the program
pygame.quit()
Running this new code will create a white window that stays open until you click the close button. Here's what the new parts do:
running = True: This boolean variable controls ourwhileloop.for event in pygame.event.get():: This is the event handling part. Pygame records all user actions (mouse moves, key presses) as events and puts them in a queue. Thisforloop goes through every event in the queue.if event.type == pygame.QUIT:: We check the type of each event.pygame.QUITis the event that happens when you click the window's 'X' button. If that happens, we setrunningtoFalse, and thewhileloop will terminate on the next check.screen.fill((255, 255, 255)): This is our drawing section. We're filling the entirescreensurface with a color. Colors are represented by RGB tuples.(255, 255, 255)is white.pygame.display.flip(): This is crucial. After you've drawn everything for the current frame, this command updates the contents of the entire screen. Without it, you wouldn't see any of your changes.pygame.quit(): Once the loop ends, this line uninitializes the Pygame modules. It's the opposite ofpygame.init().
What is the primary purpose of the Pygame library?
After importing Pygame, what function must be called to initialize all its required modules?