Search code examples
pythonpygamejoystickgamepad

pygame: detect Joystick disconnect, and wait for it to be reconnected


I'm using a pygame.joystick.Joystick object and want to be able to print a message asking the user to reconnect a usb joystick once it's been unplugged.

right now I have (roughly):

js = pygame.joystick.Joystick(0)
#... some game code and stuff
pygame.joystick.quit()
pygame.joystick.init()
while pygame.joystick.get_count() == 0:
    print 'please reconnect joystick'
    pygame.joystick.quit()
    pygame.joystick.init()

js = pygame.joystick.Joystick(0)
js.init()

but it doesn't reconnect properly, idk what exactly it's doing, but it's definitely wrong. Any direction on this would be helpful


Solution

  • Here is pygame events for device add and remove.

    joystick = pygame.joystick.Joystick(0)
    
    while True:
        event = pygame.event.wait()
    
        if event.type == pygame.JOYDEVICEREMOVED:
            joystick.quit()
    
        elif event.type == pygame.JOYDEVICEADDED:
            joystick.init()
    

    https://www.pygame.org/docs/ref/joystick.html