Search code examples
pythoninputpygamekeyboard

User key keyboard input


How do I get a user keyboard input with python and print the name of that key ?

e.g:

user clicked on "SPACE" and output is "SPACE" user clicked on "CTRL" and output is "CTRL".

for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to use only keys on my dict. i dont know how to add the other keyboard keys.

see example:

class KeyboardSettings():
    def __init__(self,description,keyboard):
        self.keyboard = keyboard
        self.default = keyboard
        self.description = description
        self.active = False

    def activate_change(self,x,y):
        fixed_rect = self.rect.move(x_fix,y_fix)
        pos = pygame.mouse.get_pos()

        if fixed_rect.collidepoint((pos)):
            if pygame.mouse.get_pressed()[0]:
                self.active = True   
        elif pygame.mouse.get_pressed()[0]:
                self.active = False               

This is a part of my class. in my script i loading all related object to that class. the related object are the optional keys in the game.

e.g

SHOOT1 = KeyboardSettings("SHOOT","q")
move_right = KeyboardSettings("move_right","d")
#and more keys 

key_obj_lst = [SHOOT1,move_right....]

#also i built a dict a-z, 0,9
dict_key = { 'a' : pygame.K_a,
             'b' : pygame.K_b,
             'c' : pygame.K_c,
              ...
             'z' : pygame.K_z,
              
             '0' : pygame.K_0,
             ...
             '1' : pygame.K_1,
             '9' : pygame.K_9,

then in game loop:

for event in pygame.event.get():
   if event.type == pygame.KEYDOWN:
     for k in key_obj_lst:
     #define each key by user 
        if k.active:
            k.keyboard  = event.unicode
            default = False

         if k.keyboard in dict_key:
            if event.key == dict_key[k.keyboard]:
               if k.description == 'Moving Right':
                    moving_right = True
               if k.description == 'SHOOT':
                            SHOOT = True

The code worked perfectly but i trully dont know how to add keys that not letters and numbers such as "ENTER","SPACE" etc.


Solution

  • pygame provides a function for getting the name of the key pressed:

    pygame.key.name

    And so you can use it to get the name of the key, there is no need to use a dictionary for this:

    import pygame
    
    
    pygame.init()
    screen = pygame.display.set_mode((500, 400))
    
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == pygame.KEYDOWN:
                key_name = pygame.key.name(event.key)
                print(key_name)