Reputation: 29
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())
Upvotes: 2
Views: 2369
Reputation: 1
In addition to the previous answer, you don't need to experiment to find the buttons because the pygame.joystick documentation ( https://www.pygame.org/docs/ref/joystick.html ) includes mapping for various controllers.
Upvotes: 0
Reputation: 333
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.
Upvotes: 1