python – pygame:检测操纵杆断开连接,并等待它重新连接

我正在使用pygame.joystick.Joystick对象,并且希望能够打印一条消息,要求用户在拔下插头后重新连接usb游戏杆.

现在我(大致):

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()

但它没有正确地重新连接,idk究竟是在做什么,但这绝对是错误的.任何方向都会有所帮助

最佳答案 不得不启动旧的xbox pad,但我做了一个功能,检查断开连接,似乎工作正常:

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

因此,如果您在主循环中运行此函数,它将继续运行,直到它获得操纵杆连接.它适用于我发现的小测试代码:

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

还发现:

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

在我偷了这个想法的地方,他没有任何蹩脚的代码示例

最后,因为你应该经常查看文档:

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

点赞