Since I published a snippet for accessing game controllers on Linux from Python, I figured I’d also make one for doing the same on Windows.
It’s not as robust as the Linux code since it doesn’t fetch a button mapping from the driver (I couldn’t find a way to fetch it via the API, let me know if you find a way) so I hardcoded the button map of my own gamepad.
It uses the WinMM API via ctypes. This is a little-known way of accessing the joysticks, and is the easiest to instrument from Python. An alternative is via the raw input API, which I also have code for, let me know if you want it.
One thing to keep in mind is that the Windows joystick drivers don’t allow the use of both triggers at the same time, since the triggers are seen as a single axis (which is -1 when the left trigger is pressed but 1 when the right trigger is pressed, but 0 when both are pressed because they cancel each other out).
Here’s the code. It’s raw, proof-of-concept code that should be a good start for implementing it into your game.
(If you’re using an XBox 360 controller, you can use XInput instead, which is easier to interface with and does allow reading the two triggers individually. (example))