how do i put a variable in a pygame key detector?

pygame.event.get() will not work if you don’t handle the events in the loop. See pygame.event.get() respectively pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

def wait_for_key(key):
    pressed=0
    while pressed==0:
    
        pygame.event.pump()
    
        # [...]
        

If you want to wait kor SPACE you have to pass the key pygame.K_SPACE to wait_for_key (see pygame.key). Test the state of argument key:

wait_for_key(pygame.K_SPACE)
def wait_for_key(key):
    pressed=0
    while pressed==0:
        pygame.event.pump()
        keys=pygame.key.get_pressed()
        if keys[key]:
            pressed=1

However, if you just want to get if a key is pressed, you can use the KEYDOWN event (see pygame.event):

def wait_for_key(key):
    pressed=0
    while pressed==0:

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == key: 
                    pressed = 1

pygame.key.name() returns the name of a key identifier. Use it if you want to pass the name of a key to the function wait_for_key:

wait_for_key("space")
def wait_for_key(key_name):
    pressed=0
    while pressed==0:

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if pygame.key.name(event.key) == key_name: 
                    pressed = 1

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top