# BGE get controller/joystick count in python

I am making bge games and want them full controller support and I have already scripted the input, but the axis and the buttons index is changing when having different amount of controllers. Here is what I mean:

#joystick for buttons, joystickaxis for axis

#2 controller

#controller 1
joystick = bge.logic.joysticks[0]
joystickaxis = bge.logic.joysticks[1]

#controller 2
joystick = bge.logic.joysticks[1]
joystickaxis = bge.logic.joysticks[0]

#4 controller

#controller 4
joystick = bge.logic.joysticks[3]
joystickaxis = bge.logic.joysticks[0]
#controller 3
joystick = bge.logic.joysticks[2]
joystickaxis = bge.logic.joysticks[1]
#controller 2
joystick = bge.logic.joysticks[1]
joystickaxis = bge.logic.joysticks[2]
#controller 2
joystick = bge.logic.joysticks[0]
joystickaxis = bge.logic.joysticks[3]

#3 controller

#controller 3
joystick = bge.logic.joysticks[2]
joystickaxis = bge.logic.joysticks[0]
#controller 2
joystick = bge.logic.joysticks[1]
joystickaxis = bge.logic.joysticks[1]
#controller 1
joystick = bge.logic.joysticks[0]
joystickaxis = bge.logic.joysticks[2]

#1 controller

joystick = bge.logic.joysticks[0]
joystickaxis = bge.logic.joysticks[0]


Now I need my script to know how many controllers are registered in bge and I would like to know if there is a python function for that, I mean bge seems at least to know how many there are.

• Just to let you know: Code repetition is no good design. It makes development and maintenance really hard. I suggest to use common programming techniques, like looping, encapsulation, parameters and so on. – Monster Feb 13 '18 at 7:16
• Thank you for the suggestion, I will try to keep that in mind. – Georg Egner Feb 13 '18 at 10:27

bge.logic.joysticks gives a list of the max number of controllers (eight), now if there is not a controller the list will have None in that slot.
connected_controllers  = 8 - bge.logic.joysticks.count(None)