1

I'd like users to be able to define which keys they'd like to use during a pygame session. I include a short example below where I'd like to change the current working event_handler() function so that it can utilise a user-defined key to quit during the loop:

A more advanced python user might also be able to advise me as to how the user could choose a function key or the up/down/left/right arrows of the keyboard too?

import pygame
from pygame.locals import *
pygame.init()
size = display_width, display_height = 200,100
DS = pygame.display.set_mode((400,200))

userQuitKey = "K_"+"q"
print(userQuitKey)

def event_handler():      
    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_q):
        #if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == userQuitKey):
            pygame.quit()
            quit()   

for r in range(210,255):
    for g in range(210,255):
        for b in range(210,255):
            event_handler()
            DS.fill((r,g,b))
            pygame.display.update()
print("Loops have ended!")
pygame.quit()
quit()  
thescoop
  • 504
  • 5
  • 20
  • One of the answers from your link suggests that this is done: input_map = {'move right': pygame.K_d, 'move left': pygame.K_a} I don't understand why my proposed solution of userQuitKey = "K_"+"q" wouldn't essentially do the same thing. – thescoop Sep 30 '18 at 11:20
  • 1
    `"K_"+"q"` is a string, but you need the pygame constant `K_q` which is actually an int (`113`). If you want to use a string to get the value of `K_q`, you can use the `getattr` function: `userQuitKey = getattr(pygame, "K_"+"q")`. – skrx Sep 30 '18 at 11:36
  • 1
    Thanks Skrx, this last comment of yours, together with the link you posted above have clarified everything! – thescoop Sep 30 '18 at 11:48
  • 1
    Here's a list of the key constants: http://www.pygame.org/docs/ref/key.html – skrx Oct 01 '18 at 14:37
  • where did you get "K_q which is actually an int (113)" ? – thescoop Oct 01 '18 at 14:38
  • 1
    I just printed it. – skrx Oct 01 '18 at 14:48

0 Answers0