Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 282
Ryan Haining Avatar asked Oct 05 '22 12:10

Ryan Haining


1 Answers

Had to fire up the old xbox pad but I made a function that checks for disconnections and seems to work ok:

discon = False
def check_pad():
    global discon
    pygame.joystick.quit()
    pygame.joystick.init()
    joystick_count = pygame.joystick.get_count()
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()
    if not joystick_count: 
        if not discon:
           print "reconnect you meat bag"
           discon = True
        clock.tick(20)
        check_pad()
    else:
        discon = False

So if you run this function in your main loop it'll just keep running itself until it gets a joystick connection back. It works for the little test code I found:

http://programarcadegames.com/python_examples/show_file.php?file=joystick_calls.py

Also found:

http://demolishun.net/?p=21

Where I stole the idea from, he didn't have any code examples which was lame

And lastly, because you should always check the docs:

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

like image 133
Noelkd Avatar answered Oct 13 '22 11:10

Noelkd