'Controller Support in PyGame

Is it possible to add a purely python code to python, more specifically in the pygame module, so that it can take direct input from a Controller (XBox One, PS4, etc.)? I have attempted to use the following code with no luck;

 win.onkey()
 win.use(sys())


Solution 1:[1]

You can use the pygame.joystick module to get button presses from any controller connected to the computer. The id you pass into pygame.joystick.Joystick(id) is the order the controller was connected to the computer, starting at 0, for most cases you can use 0.

import pygame

pygame.init()

window = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Controller")

controller = pygame.joystick.Joystick(0)

done = False

while not done:
    if controller.get_button(0): #A
        pygame.draw.rect(window, (255, 0, 0), [0, 0, 800, 600])
    if controller.get_button(1): #B
        pygame.draw.rect(window, (0, 255, 0), [0, 0, 800, 600])
    if controller.get_button(2): #X
        pygame.draw.rect(window, (0, 0, 255), [0, 0, 800, 600])
    if controller.get_button(3): #Y
        pygame.draw.rect(window, (0, 0, 0), [0, 0, 800, 600])
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.display.update()

pygame.quit()

I don't know all of the ids for the buttons, so you'll have to experiment.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zachary Milner