We will fix a program where pressing the 'R' key should change the background color to red, but it doesn't. We will use print()
to see what the computer thinks you are pressing and then fix the code.
We will fix a program where pressing the 'R' key should change the background color to red, but it doesn't. We will use print()
to see what the computer thinks you are pressing and then fix the code.
Let's check if your program is working. We do this by running a special test. Open your terminal and type this command:
pytest module-1.2/blueprint-PY-1.2-BP6/quest-10
What you will see:
test_background_remains_white_without_r_key
test_background_changes_to_red_on_r_key
test_background_does_not_change_on_other_key
test_print_statement_is_called_on_keydown
These tests will show a red X because your code is not finished yet.
Open the main.py
file. You need to add a print()
line to see what key is being pressed. Then, fix the code so the background changes to red when you press the 'R' key.
Here's how you can print what key is pressed:
import pygame
# Inside your game loop, after checking for KEYDOWN:
if event.type == pygame.KEYDOWN:
print(f"Key pressed: {event.key}")
To change a color, you can set a variable to a new color:
current_color = (255, 255, 255) # White
new_color = (255, 0, 0) # Red
current_color = new_color
To check if a key is a specific key, use pygame.K_
followed by the key name:
import pygame
# Inside your game loop, after checking for KEYDOWN:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print("Spacebar pressed!")
Use these examples to help you fix the program.
Now that you've written your code, let's check it again. Type this command in your terminal:
pytest module-1.2/blueprint-PY-1.2-BP6/quest-10
test_background_remains_white_without_r_key
test_background_changes_to_red_on_r_key
test_background_does_not_change_on_other_key
test_print_statement_is_called_on_keydown
This document provides a quick reference for key concepts and techniques covered in this blueprint, focusing on finding and fixing errors (debugging) and improving code structure (refactoring).
A bug is an error in a computer program that causes it to produce an incorrect or unexpected result, or to behave in an unintended way. Bugs are a normal part of the software development process.
Debugging is the process of finding and resolving defects or problems within a computer program.
Debugging involves investigating your code to understand why it isn't behaving as expected.
Using print()
statements is a fundamental technique to inspect the state of your program and understand its execution flow.
print()
calls with descriptive messages and variable values where you suspect an issue might be occurring.# Example: Checking a variable's value inside a loop
count = 0
while count < 5:
print(f"Current count: {count}") # Check the value of count
# ... other code ...
count += 1
print("Loop finished.") # Confirm the loop completed
Your code editor (like VS Code) has powerful, built-in tools for debugging.
Refactoring is the process of restructuring existing computer code without changing its external behavior. The goal is to improve nonfunctional attributes of the software, such as readability, maintainability, and simplicity.
Refactoring is like simplifying an algebraic expression; the value is the same, but the form is cleaner and easier to work with.
If a block of code performs a single, well-defined task, move it into its own function.
# Before Refactoring (example)
# ... inside a loop ...
# Calculate area
width = 10
height = 20
area = width * height
print(f"Area: {area}")
# ... rest of loop ...
# After Refactoring (example)
def calculate_area(width, height):
"""Calculates the area of a rectangle."""
area = width * height
return area
# ... inside the loop ...
width = 10
height = 20
area = calculate_area(width, height) # Call the new function
print(f"Area: {area}")
# ... rest of loop ...
Write code that is easy for others (and your future self) to understand.
total_price
instead of tp
).# Less readable (example)
# Calculate final price with tax
p = 100
t = p + (p * 0.08)
final = round(t, 2)
# More readable (example)
# Calculate final price with tax
subtotal = 100
tax_rate = 0.08
tax_amount = subtotal * tax_rate
total_price = subtotal + tax_amount
final_price_rounded = round(total_price, 2)
In Pygame, the event loop processes user input and system events.
event.type
attribute to identify the type of event (e.g., pygame.QUIT
, pygame.KEYDOWN
, pygame.MOUSEBUTTONDOWN
).pygame.KEYDOWN
, pygame.KEYUP
), use event.key
to identify which key was pressed (e.g., pygame.K_r
).pygame.MOUSEBUTTONDOWN
, pygame.MOUSEBUTTONUP
), use event.pos
to get the mouse coordinates.# Example Pygame event loop structure
import pygame
# ... setup ...
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
# Check event.key here
pass
if event.type == pygame.MOUSEBUTTONDOWN:
# Access event.pos here
pass
# ... drawing and update ...
In graphics programming, the order in which you draw is crucial. Objects drawn later appear on top of objects drawn earlier.
pygame.display.flip()
or pygame.display.update()
) to show the completed frame.# Example Pygame drawing order
# ... inside the game loop ...
# 1. Draw background
screen.fill(BACKGROUND_COLOR)
# 2. Draw game elements
pygame.draw.rect(screen, PLAYER_COLOR, player_rect)
# ... draw other objects ...
# 3. Update display
pygame.display.flip()
# ...
Variables defined outside of any function are called global variables. To modify a global variable from inside a function, you must use the global
keyword.
global
keyword.global
keyword inside the function.# Example using global
counter = 0 # Global variable
def increment_counter():
global counter # Declare intent to modify the global 'counter'
counter += 1
def read_counter():
# No 'global' needed to just read the value
print(f"Current counter value: {counter}")
# ...
increment_counter()
read_counter() # Output: Current counter value: 1
Adding sound effects can make an application more engaging.
import pygame
pygame.mixer.init()
pygame.mixer.Sound
object.
# Assumes 'sound.wav' is in the same directory
sound_effect = pygame.mixer.Sound("sound.wav")
.play()
method on the sound object when the corresponding action occurs.
# Example inside a function triggered by an event
def on_action():
# ... perform action ...
sound_effect.play() # Play the sound