Pygame Events

Keyboard Event Handling

In the program below, we add keyboard press events (left arrow key and right arrow key). If the left arrow key is pressed, the ball image moves to the left by 10 pixels.  If, however, the right arrow key is pressed, the ball moves to the right by ten pixels.

The program uses the following functions:

  1. Calls pygame.event.get() to retrieve any new  Event objects
  2. Pygame.KEYDOWN for event type key pressed down
  3. Pygame.KEYUP for event type key released
  4. Pygame.K_LEFT for event type left arrow key pressed
  5. Pygame.K_RIGHT for event type right arrow key pressed
PROGRAM EXAMPLE: KEYBOARD EVENT HANDLING

Program: pygame_event_keyboard_move.py

Image: ball.png

import pygame       			       #1)
pygame.init()				       #2)
# ‘screen’ is a pygame object
screen = pygame.display.set_mode((640, 480))   #3)
BLACK = (0, 0, 0)			       #4)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#
pygame.display.set_caption('BallMoveKeyboard')	#5)
#
clock = pygame.time.Clock()		       #6)
#
ballImage = pygame.image.load('ball.png')	#7)
#
x = 0					       #8)
y = 0
#
x_move = 0				       #8a)

def ball(x, y):
    screen.blit(ballImage, (x, y))	       #9)
    
#Main Loop				       #10
while True:
    for event in pygame.event.get():	       #10a)
        if event.type == pygame.KEYDOWN:       #10b)
            if event.key == pygame.K_LEFT:     #10c)
                x_move = -10
            elif event.key == pygame.K_RIGHT:  #10d)
                x_move = 10

        if event.type == pygame.KEYUP:	       #10e)
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
# 10f)
                x_move = 0
# End of Main Loop
    x = x + x_move			       #10g)
#
    screen.fill(WHITE)			       #11
    ball(x, y)				       #12
    pygame.display.update()		       #13
    clock.tick(60)			       #14

pygame.quit()				       #15
quit()

Detailed Line-by-line Program Explanation:

Steps 1) through 9) are the same as in program example “pygame_ball_display.py“.

Steps 10a) through 10g) are the event handling code in the main loop, which iterates continuously.

10a) pygame.event.get()

This function looks for any event that happened since the last iteration of the loop.

10b) if event.type == pygame.KEYDOWN:

If the event type is KEYDOWN, meaning the user has pressed a key.

10c) if event.key == pygame.K_LEFT:

This line of the code checks if the pressed key is the LEFT arrow (K_LEFT). If that is the case, the code subtracts 10 pixels from the ball’s x-coordinate; so the ball image moves to the left. 

10d) elif event.key == pygame.K_RIGHT:

If it was not the left-arrow key, the code checks if the pressed key is the RIGHT arrow (K_RIGHT).  If it is, the code adds 10 pixels to the ball x-coordinate, so the ball image moves to the right.

10e) if event.type == pygame.KEYUP:

The code then checks if the user has released the key by checking the event type “KEYUP”.

10f) if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:

If the pressed key has been released, the code sets x_move = 0, so that the ball does not move anymore.

10g) x = x + x_move.

This line of code calculates the new value of x (ball position) by adding x_move to the previous ball position. x_move may be +10, or -10 depending on the Right-arrow key or Left_arrow key that was pressed. x_move is zero when the key has been released. Earlier in step 8a), we had defined a variable x_move and assigned it value = 0. x_move is the amount by which the ball moves at each KEYDOWN event.

11) through 15) are the same as in the program example “ballDisplay”.

Let Us Now Add Boundary Checks to the Program

Note that in the above program, we have not set any boundaries on ball movement.  If you keep on pressing the LEFT arrow key repeatedly (or the RIGHT arrow key repeatedly), the ball will move out of the display surface.  We will fix this in the next program so that the ball does not go out of the surface.

PROGRAM EXAMPLE: KEYBOARD EVENT HANDLING WITH BOUNDARY CHECK

Program Name: pygame_event_keyboard_move_boundary_c

heck.py

Image Name: ball.png

import pygame					# 1
# Pygame module needs to be imported before we can use.
pygame.init()					# 2
#
screen = pygame.display.set_mode((640, 480))	# 3
BLACK = (0, 0, 0)				# 4
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#
ball_width = 99
#
pygame.display.set_caption('BallMoveKeyboardBoundaryCheck')# 5
#
clock = pygame.time.Clock()			# 6
#
ballImage = pygame.image.load('ball.png’)	# 7
#
x = 0						# 8
y = 0
#
x_move = 0					# 8a

def ball(x, y):
    screen.blit(ballImage, (x, y))		# 9
    
# Main Loop
while True:					#10
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_move = -10
            elif event.key == pygame.K_RIGHT:
                x_move = 10

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_move = 0
#
    x = x + x_move
#
    screen.fill(WHITE)				#11
    ball(x, y)					#12

    if x > 640 - ball_width:			#12a
        x = 0
    elif x < 0:
        x = 640 - ball_width
    
    pygame.display.update()			#13
    clock.tick(60)				#14

#
pygame.quit()					#15
quit()

Detailed Line-by-line Program Explanation:

Steps 1 through 15) are the same as in Program “ballMoveKeyboard.py”.

12a) Check if the ball has crossed the screen’s left or right boundary. If the ball has reached the right boundary, change the ball’s x-coordinate to zero. If the ball has moved beyond the left boundary of the screen, change the x-coordinate of the ball to 640.

Verified by MonsterInsights