Search code examples
pythonpython-2.7keyboardpygame

pygame continuous and simultaneous key inputs


I am stuck again and cannot find any valid solutions online. I am trying to use pygame and its key inputs to control various things. Now I need to use several keys simultaneously. My code is as follows:

pygame.key.set_reapeat(50,50)
bProgramLoop = True
while (bProgramLoop == True):

    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            bProgramLoop = False
        if (pygame.key.get_pressed()[pygame.K_LEFT]):
            EXECUTE_FUNCTION1()
            print "left"
        if (pygame.key.get_pressed()[pygame.K_RIGHT]):
            EXECUTE_FUNCTION2()
            print "right"

Now the problem that I have is: When I hold down "LEFT of RIGHT" it correctly and continuously registers that I pressed left/right. BUT when I hold in "LEFT" and just tap "RIGHT", it registers that left and right were pressed but it then stops to register that "LEFT" is still being pressed.

Any ideas anyone? Any help would be greatly appreciated. Misha


Solution

  • In my code the "repeat" is correctly spelt.

    I found the work around for my problem. The above code needs to be modified.

    pygame.key.set_repeat(50,50)
    bProgramLoop = True
    while (bProgramLoop == True):
    
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                bProgramLoop = False
            if (event.type == pyame.KEYDOWN):
                if (event.key == pygame.K_a)   # if A is pressed
                    bKeyA = True               # set the Boolean True
                if (event.key == pygame.K_s)   
                    bKeyS = True
            if (event.type == pyame.KEYDOWN):
                if (event.key == pygame.K_a)   # if A is released
                    bKeyA = False# set the Boolean False
                if (event.key == pygame.K_s)   
                    bKeyS = False
    
        if (bKeyA == True):
            Execute_function1()
        if (bKeyB == True):
            Execute_function2()
    

    I double checked, the repeat is correctly spelt and it would not continue a keyboard input once another one was tapped. The problem is, as far as I can figure it out, and even occurs once at the point when a key is pressed. When another key is simultaneously pressed the event is lost.

    Thus the solution is to set a variable true until the key is lifted up, and thus the variable is set false.