How to take input from Keyboard in Pygame using Python
In this module, we are going to discuss how to take input from the keyboard in Pygame in Python. Like moving the character using the arrow keys i.e when we press left arrow the character moves left.
Taking Input from keyboardUsing pygame.get_pressed() in Python
To take input from keyboard we use the syntax as follows
key_input = pygame.key.get_pressed()
This method is used to identify the keypress events that are represented as follows:
There are many key events like this K_SPACE used when space is pressed on keyboard similarly K_LEFT used when left arrow is pressed.
The following code gives a complete description of above-mentioned keyboard events
import pygame import sys pygame.init() fps=30 fpsclock=pygame.time.Clock() sur_obj=pygame.display.set_mode((400,300)) pygame.display.set_caption("Rectangle") black=(0,0,0) p1=10 p2=10 step=5 while True: sur_obj.fill(black) pygame.draw.rect(sur_obj, (255,0,0), (p1, p2,70,65)) for eve in pygame.event.get(): if eve.type==pygame.QUIT: pygame.quit() sys.exit() key_input = pygame.key.get_pressed() if key_input[pygame.K_LEFT]: p1 -= step if key_input[pygame.K_UP]: p2 -= step if key_input[pygame.K_RIGHT]: p1 += step if key_input[pygame.K_DOWN]: p2 += step pygame.display.update() fpsclock.tick(fps)
We get the output as a rectangle with red in color on a black screen when we press the left arrow it is moved left similarly when we press-up it moves up.
We are filling up the screen with black color after each event update and performing the next event on that black screen.
pygame.draw.rect(sur_obj, (255,0,0), (p1, p2, 70, 65))
This method is used for creating a rectangle and it is initially located at position (p1,p2).
if key_input[pygame.K_LEFT]: p1 -= step if key_input[pygame.K_UP]: p2 -= step if key_input[pygame.K_RIGHT]: p1 += step if key_input[pygame.K_DOWN]: p2 += step
Here these are used to check which keys are pressed each perform following actions
- K_LEFT: it moves rectangle to the position (p1-5,p2). when we subtract 5 pixels from x coordinate.
- K_UP: it moves rectangle to the position (p1,p2-5). when we subtract 5 pixels from y coordinate.
- K_RIGHT: it moves rectangle to position(p1+5,p2). when we add 5 pixels to x coordinate.
- K_DOWN: it moves rectangle to position(p1,p2+5). when we add 5 pixels to y coordinate.
We used fpsclock.tick(fps) because in pygame, we are not updating the current window but creating a new window with an update. Therefore tick() helps us to achieve this task running the screen as though it is making the rectangle move.
Leave a Reply