Lesson 14: Handling Player Input
Topics Covered:
- Detecting keyboard input in Pygame
- Moving objects based on key presses
- Basic game loop structure
Detecting Keyboard Input
Pygame lets you detect when keys are pressed or released using event handling.
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("Left arrow pressed")
elif event.key == pygame.K_RIGHT:
print("Right arrow pressed")
Moving an Object with the Keyboard
import pygame
import sys
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Move the Square")
x, y = 300, 220 # Starting position
speed = 5 # Movement speed
square_size = 50
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
screen.fill((0, 0, 0)) # Clear screen with black
pygame.draw.rect(screen, (0, 255, 0), (x, y, square_size, square_size)) # Draw square
pygame.display.flip() # Update screen
pygame.quit()
sys.exit()
Activity: Control the Square
- Use arrow keys to move the square around the window
- Try changing the speed and size of the square
- Prevent the square from moving outside the window edges (challenge)