The joystick module manages the joystick devices on a computer.
Joystick devices include trackballs and video-game-style
gamepads, and the module allows the use of multiple buttons and "hats".
Computers may manage multiple joysticks at a time.
Each instance of the Joystick class represents one gaming device plugged
into the computer. If a gaming pad has multiple joysticks on it, then the
joystick object can actually represent multiple joysticks on that single
game device.
For a quick way to initialise the joystick module and get a list of Joystick instances
use the following code:
Note that in pygame 2, joysticks events use a unique "instance ID". The device index
passed in the constructor to a Joystick object is not unique after devices have
been added and removed. You must call Joystick.get_instance_id() to find
the instance ID that was assigned to a Joystick on opening.
The event queue needs to be pumped frequently for some of the methods to work.
So call one of pygame.event.get, pygame.event.wait, or pygame.event.pump regularly.
To be able to get joystick events and update the joystick objects while the window
is not in focus, you may set the SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS environment
variable. See environment variables for more details.
Create a new joystick to access a physical device. The id argument must be a
value from 0 to pygame.joystick.get_count()-1.
Joysticks are initialised on creation and are shut down when deallocated.
Once the device is initialized the pygame event queue will start receiving
events about its input.
Changed in pygame 2.0.0: Joystick objects are now opened immediately on creation.
Returns the original device index for this device. This is the same
value that was passed to the Joystick() constructor. This method can
safely be called while the Joystick is not initialized.
Deprecated since pygame 2.0.0: The original device index is not useful in pygame 2. Use
get_instance_id() instead. Will be removed in Pygame 2.1.
Returns the system name for this joystick device. It is unknown what name
the system will give to the Joystick, but it should be a unique name that
identifies the device. This method can safely be called while the
Joystick is not initialized.
Returns the number of input axes are on a Joystick. There will usually be
two for the position. Controls like rudders and throttles are treated as
additional axes.
The pygame.JOYAXISMOTION events will be in the range from -1.0
to 1.0. A value of 0.0 means the axis is centered. Gamepad devices
will usually be -1, 0, or 1 with no values in between. Older
analog joystick axes will not always use the full -1 to 1 range,
and the centered value will be some area around 0.
Analog joysticks usually have a bit of noise in their axis, which will
generate a lot of rapid small motion events.
Returns the current position of a joystick axis. The value will range
from -1 to 1 with a value of 0 being centered. You may want
to take into account some tolerance to handle jitter, and joystick drift
may keep the joystick from centering at 0 or using the full range of
position values.
The axis number must be an integer from 0 to get_numaxes()-1.
When using gamepads both the control sticks and the analog triggers are
usually reported as axes.
Returns the number of trackball devices on a Joystick. These devices work
similar to a mouse but they have no absolute position; they only have
relative amounts of movement.
The pygame.JOYBALLMOTION event will be sent when the trackball is
rolled. It will report the amount of movement on the trackball.
Returns the number of joystick hats on a Joystick. Hat devices are like
miniature digital joysticks on a joystick. Each hat has two axes of
input.
The pygame.JOYHATMOTION event is generated when the hat changes
position. The position attribute for the event contains a pair of
values that are either -1, 0, or 1. A position of (0,0)
means the hat is centered.
Returns the current position of a position hat. The position is given as
two values representing the x and y position for the hat. (0,0)
means centered. A value of -1 means left/down and a value of 1 means
right/up: so (-1,0) means left; (1,0) means right; (0,1) means
up; (1,1) means upper-right; etc.
This value is digital, i.e., each coordinate can be -1, 0 or 1
but never in-between.
The hat number must be between 0 and get_numhats()-1.
Start a rumble effect on the joystick, with the specified strength ranging
from 0 to 1. Duration is length of the effect, in ms. Setting the duration
to 0 will play the effect until another one overwrites it or
Joystick.stop_rumble() is called. If an effect is already
playing, then it will be overwritten.
importpygamepygame.init()# This is a simple class that will help us print to the screen.# It has nothing to do with the joysticks, just outputting the# information.classTextPrint:def__init__(self):self.reset()self.font=pygame.font.Font(None,25)deftprint(self,screen,text):text_bitmap=self.font.render(text,True,(0,0,0))screen.blit(text_bitmap,(self.x,self.y))self.y+=self.line_heightdefreset(self):self.x=10self.y=10self.line_height=15defindent(self):self.x+=10defunindent(self):self.x-=10defmain():# Set the width and height of the screen (width, height), and name the window.screen=pygame.display.set_mode((500,700))pygame.display.set_caption("Joystick example")# Used to manage how fast the screen updates.clock=pygame.time.Clock()# Get ready to print.text_print=TextPrint()# This dict can be left as-is, since pygame will generate a# pygame.JOYDEVICEADDED event for every joystick connected# at the start of the program.joysticks={}done=Falsewhilenotdone:# Event processing step.# Possible joystick events: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,# JOYBUTTONUP, JOYHATMOTION, JOYDEVICEADDED, JOYDEVICEREMOVEDforeventinpygame.event.get():ifevent.type==pygame.QUIT:done=True# Flag that we are done so we exit this loop.ifevent.type==pygame.JOYBUTTONDOWN:print("Joystick button pressed.")ifevent.button==0:joystick=joysticks[event.instance_id]ifjoystick.rumble(0,0.7,500):print(f"Rumble effect played on joystick {event.instance_id}")ifevent.type==pygame.JOYBUTTONUP:print("Joystick button released.")# Handle hotpluggingifevent.type==pygame.JOYDEVICEADDED:# This event will be generated when the program starts for every# joystick, filling up the list without needing to create them manually.joy=pygame.joystick.Joystick(event.device_index)joysticks[joy.get_instance_id()]=joyprint(f"Joystick {joy.get_instance_id()} connencted")ifevent.type==pygame.JOYDEVICEREMOVED:deljoysticks[event.instance_id]print(f"Joystick {event.instance_id} disconnected")# Drawing step# First, clear the screen to white. Don't put other drawing commands# above this, or they will be erased with this command.screen.fill((255,255,255))text_print.reset()# Get count of joysticks.joystick_count=pygame.joystick.get_count()text_print.tprint(screen,f"Number of joysticks: {joystick_count}")text_print.indent()# For each joystick:forjoystickinjoysticks.values():jid=joystick.get_instance_id()text_print.tprint(screen,f"Joystick {jid}")text_print.indent()# Get the name from the OS for the controller/joystick.name=joystick.get_name()text_print.tprint(screen,f"Joystick name: {name}")guid=joystick.get_guid()text_print.tprint(screen,f"GUID: {guid}")power_level=joystick.get_power_level()text_print.tprint(screen,f"Joystick's power level: {power_level}")# Usually axis run in pairs, up/down for one, and left/right for# the other. Triggers count as axes.axes=joystick.get_numaxes()text_print.tprint(screen,f"Number of axes: {axes}")text_print.indent()foriinrange(axes):axis=joystick.get_axis(i)text_print.tprint(screen,f"Axis {i} value: {axis:>6.3f}")text_print.unindent()buttons=joystick.get_numbuttons()text_print.tprint(screen,f"Number of buttons: {buttons}")text_print.indent()foriinrange(buttons):button=joystick.get_button(i)text_print.tprint(screen,f"Button {i:>2} value: {button}")text_print.unindent()hats=joystick.get_numhats()text_print.tprint(screen,f"Number of hats: {hats}")text_print.indent()# Hat position. All or nothing for direction, not a float like# get_axis(). Position is a tuple of int values (x, y).foriinrange(hats):hat=joystick.get_hat(i)text_print.tprint(screen,f"Hat {i} value: {str(hat)}")text_print.unindent()text_print.unindent()# Go ahead and update the screen with what we've drawn.pygame.display.flip()# Limit to 30 frames per second.clock.tick(30)if__name__=="__main__":main()# If you forget this line, the program will 'hang'# on exit if running from IDLE.pygame.quit()
Controller mappings are drawn from the underlying SDL library which pygame uses and they differ
between pygame 1 and pygame 2. Below are a couple of mappings for three popular controllers.
The Nintendo Switch Left Joy-Con has 4 axes, 11 buttons, and 0 hats. The values for the 4 axes never change.
The controller is recognized as "Wireless Gamepad"
The Nintendo Switch Right Joy-Con has 4 axes, 11 buttons, and 0 hats. The values for the 4 axes never change.
The controller is recognized as "Wireless Gamepad"
The PlayStation 5 controller mapping has 6 axes, 13 buttons, and 1 hat.
The controller is recognized as "Sony Interactive Entertainment Wireless Controller".