Search code examples
pythonpython-3.xpygamehotkeys

Keys in Pygame instead of numbers in the actual key


I want to make a menu point where I can change the hotkeys and also show which are used, but when I put them into a variable the output is in numbers. I had the idee to set the varibles when pressing the key as following:

if event.key == pygame.K_d:
    varibleright = d

This I would have to do for all the keys is there a better way or should I just do it for all the keys?


Solution

  • The KEYDOWN and KEYUP event provides the unicode attribute (see pygame.event module). The unicode attribute provides the Unicode representation of the keyboard input. A user friendly name of a key can be get by pygame.key.name():

    if event.type == pygame.KEYDOWN:
        print(event.unicode)
        print(pygame.key.name(event.key))
    

    You can use the functions to compare the key with a unicode character or string:

    if event.type == pygame.KEYDOWN:
        if event.unicode == 'a':
            print('a')
    
    if event.type == pygame.KEYDOWN:
        if pygame.key.name(event.key) == 'd':
            print('d')
        if pygame.key.name(event.key) == 'right':
            print('right')
    

    This allows you to define variables for the keys

    key_up = 'up'
    key_down = 'down'
    
    if event.type == pygame.KEYDOWN:
        if pygame.key.name(event.key) == key_up:
            print('move up')
        if pygame.key.name(event.key) == key_down:
            print('move down')
    

    Minimal example:

    import pygame
    
    pygame.init()
    window = pygame.display.set_mode((400, 400))
    clock = pygame.time.Clock()
    
    rect = pygame.Rect(190, 190, 20, 20)
    key_left = 'left'
    key_right = 'right'
    key_up = 'up'
    key_down = 'down'
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
            if event.type == pygame.KEYDOWN:
                if event.type == pygame.KEYDOWN:
                    if pygame.key.name(event.key) == key_left:
                        rect.x -= 20
                    if pygame.key.name(event.key) == key_right:
                        rect.x += 20
                    if pygame.key.name(event.key) == key_up:
                        rect.y -= 20
                    if pygame.key.name(event.key) == key_down:
                        rect.y += 20
    
        window.fill(0)
        pygame.draw.rect(window, 'red', rect)
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    exit()