How to get keyboard input in PyGame?


For building video games and multimedia applications, Python users frequently use the Pygame library. Any game must incorporate human input, which is one of its most important components. For many games, user input from the keyboard is a crucial source.

Keyboard input is the term used in Pygame to describe the process of capturing keyboard input and using it to control game elements. Python's "pygame.event" module is a convenient tool provided by Pygame for receiving keyboard input. When a key on the keyboard is pushed, this module's "pygame.KEYDOWN" event is launched.

Algorithm to Get Keyboard Input in Pygame

In Pygame, there are a few steps you must take to receive keyboard input. Here are some recommendations to get you going −

Step1 − Pygame must first be initialised before continuing: This can be accomplished by using the "pygame.init()" function. Each Pygame module that will be used by your game is initialised by this function.

  • Set the display mode − After Pygame has been initialised, the display mode must be set. Calling the "pygame.display.set_mode()" function will accomplish this. The Surface object that this function produces serves as a representation of the Pygame window that was created.

    The first stage is to build a game loop, which is a loop that runs continually while watching for occurrences. Making a while loop that uses the "pygame.event.get()" function will enable you to accomplish this. A list of every event since it was last called is returned by this method.

  • Handle events − The events returned by the "pygame.event.get()" function must be handled within the game loop. If any of the events on the list are keyboard events, you can determine this by iteratively going over the list of events.

  • Handle keyboard events − To handle a keyboard event that you see in the list of events, look up the key that was pushed. The "event.type" attribute of the event object can be used to accomplish this. You can obtain the key that was pressed if the type is "pygame.KEYDOWN" by accessing the "event.key" attribute.

Update the game state: After handling keyboard input, you must update the state of the game. This might be accomplished by relocating game items, updating the score, or carrying out any other actions that are linked to the game.

Update the display: To complete the process, execute the "pygame.display.update()" function to update the display. The Pygame window's content is updated by this function.

You may use keyboard input to create interactive games in Pygame by following these steps.

Approaches to Get Keyboard Input in Pygame

In this approach, we will explain that we occasionally need to utilise the keyboard input when utilising the Python pygame module for tasks like moving a character in a specific direction. We must observe all of the occurrences in order to accomplish this. We can see that Pygame keeps track of occurrences by looking at the events.the get() method.

Pygame.event() queues the pygame.KEYDOWN and pygame.KEYUP events, respectively, whenever a key is pressed or released.

For instance, if we want to determine if a key was pressed or not, we will monitor whether any pygame.KEYDOWN events occurred or not. As a result, we will learn whether a key was pushed or not. The code for determining whether a key was depressed or not can be expressed as follows −

Approach I : Detecting if a key is pressed

# importing pygame module
import pygame

# importing sys module
import sys

# initialising pygame
pygame.init()

# creating display
display = pygame.display.set_mode((300, 300))

# creating a running loop
while True:
	
	# creating a loop to check events that
	# are occurring
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
		
		# checking if keydown event happened or not
		if event.type == pygame.KEYDOWN:
		
			# if keydown event happened
			# than printing a string to output
			print("A key has been pressed")

Output

A key has been pressed
A key has been pressed
A key has been pressed
A key has been pressed

After running this code, it is observed that the string "A key has been pressed" is printed on the terminal each time a key has been depressed.

Approach II : Detecting which key was pressed

In the second approach, we must examine the event in order to determine which key was pressed.This pygame key relates to the key variable. For instance, we shall compare events if the pygame key for the letter "A" is "K_a".If the key with K and A is the same, the key "A" was pressed.

The different keyboard keys and associated pygame keys are as follows −

Create a code, for instance, to determine whether key "A" or "J" or "P" or "M" was depressed or not. The verification code will be −

# importing pygame module
import pygame

# importing sys module
import sys

# initialising pygame
pygame.init()

# creating display
display = pygame.display.set_mode((300, 300))

# creating a running loop
while True:
	
	# creating a loop to check events that
	# are occurring
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
		
		# checking if keydown event happened or not
		if event.type == pygame.KEYDOWN:
			
			# checking if key "A" was pressed
			if event.key == pygame.K_a:
			   print("Key A has been pressed")
			
			# checking if key "J" was pressed
			if event.key == pygame.K_j:
			   print("Key J has been pressed")
			
			# checking if key "P" was pressed
			if event.key == pygame.K_p:
			   print("Key P has been pressed")
			
			# checking if key "M" was pressed
			if event.key == pygame.K_m:
			   print("Key M has been pressed")

Output

key P has been pressed
key J has been pressed
key M has been pressed
key M has been pressed
key J has been pressed
key P has been pressed
key P has been pressed

The corresponding strings will be printed on the terminal when this code is run and the specified keys are pressed.

Conclusion

You can use the keyboard input to control game aspects once you've recorded it. For instance, you may use the arrow keys to move or the spacebar to jump a player character. The method of recording keyboard input and using it to control game objects is known as keyboard input in Pygame. Using the "pygame.event" module, which features a "pygame.KEYDOWN" event that is triggered when a key is hit on the keyboard, Pygame offers a simple method to obtain keyboard input. You may make your games more interactive and interesting for the user by recording keyboard input.

Updated on: 24-Jul-2023

957 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements