PY-1.2-BP1-MQ52

Our Goal: See What Keys Do!

We want to make our Pygame program tell us all about the keys you press on your keyboard. When you push a key down, the program should show us a special message with all the details about that key press.

Here's how a key press event triggers a print:

Check Your Work: See What's Broken

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-52

Here's what we expect to see:

  • test_prints_keydown_event_dict
  • test_handles_quit_event

Time to Code: What Did You Press?

Now it's your turn to write the code in main.py!

Your job is to make the program listen for two things:

  1. When someone closes the window (like clicking the 'X' button).
  2. When someone presses a key on the keyboard.

If a key is pressed, you need to print out all the secret information about that key press. After you print it, the program should stop. If the window is closed, the program should also stop.

Here are some examples of how to check for different events and print information, but remember, these are just examples! You'll need to use pygame.QUIT and pygame.KEYDOWN for the correct events, and event.__dict__ to get the secret information.

import pygame

# Example 1: Checking for a mouse click event
def check_mouse_click_example():
    for action in pygame.event.get():
        if action.type == pygame.MOUSEBUTTONDOWN:
            print("Mouse was clicked!")

# Example 2: Printing all details of an event
def print_event_details_example():
    for happening in pygame.event.get():
        if happening.type == pygame.MOUSEMOTION: # Just an example event type
            print(happening.__dict__)
# Example 3: Stopping a loop based on an event
def stop_loop_example():
    keep_going = True
    while keep_going:
        for thing_that_happened in pygame.event.get():
            if thing_that_happened.type == pygame.KEYUP: # Another example event
                keep_going = False

Check Your Work Again: Did It Work?

Now that you've written your code, let's check if it works!

Run this command again: pytest module-1.2/blueprint-1/quest-52

Here's what we want to see:

  • test_prints_keydown_event_dict
  • test_handles_quit_event

Debrief: Code Review Prep

Your code now handles both the QUIT event and the KEYDOWN event, and prints the event dictionary as required. This is a good point to review your work.

Be ready to explain your code to your mentor. You should be able to discuss how you used the Pygame event system to achieve the required behavior.

Documentation

Pygame Basics: Blueprint 1 Reference

This document provides a quick reference for fundamental Pygame concepts covered in the initial setup of a game window and basic event handling.

1. Getting Started

Before using Pygame, the library must be imported and initialized.

Initialization and Shutdown

  • 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.

A simple animation or diagram illustrating the init/quit process.

2. The Game Window

The visual output of a Pygame program appears in a window, referred to as the display surface.

Creating the Display Surface (Screen)

  • 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.

Setting the Window Title

  • pygame.display.set_caption("Your Title"): Sets the text that appears in the window's title bar.

An image of a blank Pygame window with a title bar.

3. The Game Loop

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.

Purpose and Basic Structure

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.

A diagram showing the game loop cycle (Events -> Update -> Draw -> Flip).

4. Handling Events

Events are how Pygame detects user input (like key presses, mouse movement, window closing) and other occurrences.

Fetching Events

  • 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.

Processing Events

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

Checking Specific Event Types

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

Inspecting Event Data

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)
    

A console showing event data being printed, possibly highlighting __dict__ or pos output.

5. Drawing

Drawing in Pygame involves preparing the visual content and then making it visible on the screen.

The Drawing Process

Drawing is typically a two-step process per frame:

  1. Draw onto a hidden surface (the 'back buffer').
  2. Swap the hidden surface with the currently visible surface (the 'front buffer') to show the completed drawing.

Filling the Background

  • 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.

Updating the Display

  • 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.

A diagram showing a hidden "back" surface being drawn on, and then the flip() operation swapping it with the visible "front" surface.