Keyword Example

Using the keyboard with a Pygame program is straightforward.


Tasks:


1. Add this code to the file to set-up the program and the pygame window

# Window setup
import pygame
pygame.init()
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

2. Next you are going to add a game loop

# Game Loop
done = False
while not done:
    keys = pygame.key.get_pressed()
    # Display message when pressed
    if keys[pygame.K_w]:
        print("Hello")
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    clock.tick(32)
pygame.quit()

Challenges:


1. Change the message that is displayed when the w key is pressed

2. Change the actionable key to z

3. What are the identities of the following keys i) Backspace ii) Space iii) Enter


Solution:


If the embed is blocked, open directly: Open on YouTube

Python Editor

Output

Loading Python runtime...