How to use Xbox controller with Pygame

Pygame is a Python library used for game development. It provides functionality for handling various game-related tasks, including input from different devices like keyboards, mouse, and game controllers.

To use an Xbox 360 controller with Pygame, you'll need to install the pygame library and then set up the controller input.

Here's a step-by-step guide:

  1. Install Pygame: If you haven't installed Pygame yet, you can do so using pip. Open your terminal or command prompt and run the following command:

pip install pygame
Command to install pygame
  1. Connect the Xbox controller: Connect your Xbox 360 controller to your computer using a USB cable or a wireless adapter (for wireless controllers).

  2. Import the required libraries: In your Python script, import the necessary libraries:

import pygame
  1. Initialize Pygame and the controller: Before you can use the Xbox controller, you need to initialize Pygame and the joystick module. Add the following code at the beginning of your script:

pygame.init()
pygame.joystick.init()
  1. Check for available controllers: You can check if any controllers are connected and get a reference to the first one (which will be your Xbox controller).

num_joysticks = pygame.joystick.get_count()
if num_joysticks > 0:
controller = pygame.joystick.Joystick(0)
controller.init()
print("Controller connected:", controller.get_name())
else:
print("No controller detected.")
  1. Read input from the controller: You can now read input from the controller's axes and buttons. The exact mapping of axes and buttons may vary depending on the type of Xbox controller you're using. You can check the pygame documentation for the specific controller mappings.

# To get the number of axes, buttons, and hats on the controller
num_axes = joystick.get_numaxes()
num_buttons = joystick.get_numbuttons()
num_hats = joystick.get_numhats()
# To read the input from the axes
axis_0 = joystick.get_axis(0)
axis_1 = joystick.get_axis(1)
# ...
# To read the input from the buttons (returns 1 if pressed, 0 if not pressed)
button_0 = joystick.get_button(0)
button_1 = joystick.get_button(1)
# ...
# To read the input from the hats (returns a tuple in the form (x, y))
hat_0 = joystick.get_hat(0)
  1. Control your game: You can use these inputs to control your game or application. For example, you can create a loop to continuously check for input:

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Read input from the Xbox controller
# Do something with the input (e.g., move a character, fire a weapon, etc.)
pygame.display.flip()
pygame.quit()

Note: Remember to adjust the game logic according to your specific use case.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved