We want to make our Pygame program stop nicely when we tell it to. This means when you click the 'X' button on the window, the program should close down properly.
Here's how the program should quit and release resources:
We want to make our Pygame program stop nicely when we tell it to. This means when you click the 'X' button on the window, the program should close down properly.
Here's how the program should quit and release resources:
Before we start, let's run a special check to see what parts of our code are not working yet. This helps us know what to fix.
Run this command:
pytest module-1.2/blueprint-1/quest-50
Here's what we expect to see:
test_quit_event_triggers_graceful_exit
test_loop_ignores_other_events
Now it's your turn to write the code in main.py
!
Your job is to make the game stop when the player clicks the 'X' button on the window. You'll need to look at each event that happens and see if it's the 'QUIT' event. If it is, you need to tell the game to stop running.
Here are some examples of how to check for different events, but remember, these are just examples! You'll need to use pygame.QUIT
to check for the correct event.
import pygame
# Example 1: Checking for a key press event
def check_key_press_example():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
print("A key was pressed!")
# Example 2: Checking for a mouse click event
def check_mouse_click_example():
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
print("Mouse was clicked!")
# Example 3: A game loop that stops when a condition is met
def controlled_game_loop_example():
game_is_on = True
while game_is_on:
for event in pygame.event.get():
# Imagine some condition here that makes game_is_on False
if event.type == pygame.K_ESCAPE: # This is just an example condition
game_is_on = False
# More game code would go here
Now that you've written your code, let's check if it works!
Run this command again:
pytest module-1.2/blueprint-1/quest-50
Here's what we want to see:
test_quit_event_triggers_graceful_exit
test_loop_ignores_other_events
This document provides a quick reference for fundamental Pygame concepts covered in the initial setup of a game window and basic event handling.
Before using Pygame, the library must be imported and initialized.
pygame.init()
: Prepares all the Pygame modules for use. This function should be called once at the very beginning of a Pygame program.pygame.quit()
: Shuts down all the Pygame modules. This function should be called once at the very end, typically after the main game loop has finished.The visual output of a Pygame program appears in a window, referred to as the display surface.
screen = pygame.display.set_mode((width, height))
: Creates the main window with the specified dimensions (width and height in pixels). The function returns a Surface
object representing the window, which is commonly stored in a variable named screen
.pygame.display.set_caption("Your Title")
: Sets the text that appears in the window's title bar.A game program typically runs continuously, checking for input, updating game elements, and drawing to the screen many times per second. This is managed by a main loop.
The game loop keeps the program running. A common structure uses a variable to control the loop's execution.
running = True
while running:
# Code inside the loop runs repeatedly
pass # Placeholder for game logic
# Code outside the loop runs after the loop finishes
When the condition controlling the while
loop becomes False
, the loop terminates, and the program can proceed to shut down.
Events are how Pygame detects user input (like key presses, mouse movement, window closing) and other occurrences.
pygame.event.get()
: This function retrieves all events that have occurred since the last time it was called. It returns a list of event objects. This should be called once per frame inside the game loop.The standard approach is to loop through the list of events obtained from pygame.event.get()
and check the type
attribute of each event.
for event in pygame.event.get():
# Check the type of the event
if event.type == SOME_EVENT_TYPE:
# Respond to this specific event
pass
Pygame defines constants for different event types:
pygame.QUIT
: Triggered when the user clicks the window's close button (the 'X').pygame.KEYDOWN
: Triggered when a keyboard key is pressed down.pygame.MOUSEMOTION
: Triggered when the mouse cursor moves within the window.for event in pygame.event.get():
# Check if the user clicked the window's 'X' button
if event.type == pygame.QUIT:
# Handle quitting
pass
# Check if any key was pressed down
if event.type == pygame.KEYDOWN:
# Handle key press
pass
# Check if the mouse was moved
if event.type == pygame.MOUSEMOTION:
# Handle mouse movement
pass
Event objects carry additional information as attributes.
Inspecting All Data: To see all data associated with an event, you can print its internal dictionary using the __dict__
attribute. This is useful for exploration and debugging.
if event.type == pygame.KEYDOWN:
# Prints all data associated with the key press event
print(event.__dict__)
Accessing Specific Attributes: Specific event types have specific attributes. For example, the MOUSEMOTION
event has a pos
attribute, which is a tuple (x, y)
representing the mouse coordinates.
if event.type == pygame.MOUSEMOTION:
# Prints the current (x, y) coordinates of the mouse
print(event.pos)
Drawing in Pygame involves preparing the visual content and then making it visible on the screen.
Drawing is typically a two-step process per frame:
surface.fill(COLOR)
: Fills the entire surface (like the main screen
surface) with a single color. This is often used at the beginning of each frame to clear the screen and set the background color. COLOR
is usually an RGB tuple like (255, 0, 0)
for red.pygame.display.flip()
: Updates the entire screen to show everything that has been drawn since the last update. This function should be called once per frame after all drawing operations are complete.