Course Content
Week 1: Getting Started
In week 1 the basis goal is to get started with the basics.
0/2
Week 2: Variables & Data Types
Variables are containers that computer programs use to store information pertinent to what that computer program will do. Data Types are the different types of Variables and how Python uses these variables when building logic
0/2
Week 3: Making Decisions
In both computer programs and the AI world, computer programs need a way to make decisions. Booleans and Conditionals provide a way to make this happen.
0/2
learning Python Programming and also Intro to Games

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)