Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...