I managed to get my work with Noelkdโs offer, but I had a similar problem described by Ryan Heinin
At first I had something like this, but it does not work, because it loses traces of the action of the gamepads with all quiting and initing. This works first to check if the controller is connected at all, but not to check efficiently during operation
I also had this problem. I think you're right, when you call quit too often, it does not give the pad enough time to reinitialize - at least on my computer. I found that if you limit the number of calls per second, this works.
This can lead to a temporary disconnection of the player's input, so any calls to joystick will not work.
It is best to run this code only if you find that for a while there was no input (say, 5 seconds or something else). This way you wonโt quit when the user actually uses 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
Using
# ... 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!
source share