I managed to get mine working with Noelkd's suggestion, but I had a similar issue described by Ryan Haining
I had something like this at first, but it doesn't work because the it loses track of the gamepads actions with all the quiting and initing. This works initially to check if a controller is plugged in at all, but not to effectively check while running
I had this issue too. I think you are correct, calling quit
too often doesn't give the pad enough time to re-initialise - at least on my computer. I found that if you limit the calls to every second, it works.
It can cause the player input to temporarily disconnect though, so any calls on a joystick
won't work.
It's better to only run this code if you detect that there has been no input for a while (say 5 seconds or something). This way you won't quit
while a user is actually using the device
import pygame
import time
INACTIVITY_RECONNECT_TIME = 5
RECONNECT_TIMEOUT = 1
class ControllerInput():
def __init__(self):
pygame.joystick.init()
self.lastTime = 0
self.lastActive = 0
def getButtons(self, joystickId):
joystick = pygame.joystick.Joystick(joystickId)
joystick.init()
buttons = {}
for i in range(joystick.get_numbuttons()):
buttons[i] = joystick.get_button(i)
if buttons[i]:
self.lastActive = time.time()
return buttons
def hasController(self):
now = time.time()
if now - self.lastActive > INACTIVITY_RECONNECT_TIME and now - self.lastTime > RECONNECT_TIMEOUT:
self.lastTime = now
pygame.joystick.quit()
pygame.joystick.init()
return pygame.joystick.get_count() > 0
Usage
# ... some constructor
controller = ControllerInput()
# ... game loop
if not controller.hasController():
# handle disconnect
print('reconnect')
return
buttons = controller.getButtons(0)
if buttons[0]:
# buttons[0] was pressed!