W3cubDocs

/Pygame

pygame.joystick

Pygame module for interacting with joysticks, gamepads, and trackballs.

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, than 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:

pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]

The following event types will be generated by the joysticks

JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION

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.

pygame.joystick.init() -> None

Initialize the joystick module.

This function is called automatically by pygame.init().

It initializes the joystick module. This will scan the system for all joystick devices. The module must be initialized before any other functions will work.

It is safe to call this function more than once.

pygame.joystick.quit() -> None

Uninitialize the joystick module.

Uninitialize the joystick module. After you call this any existing joystick objects will no longer work.

It is safe to call this function more than once.

pygame.joystick.get_init() -> bool

Returns True if the joystick module is initialized.

Test if the pygame.joystick.init() function has been called.

pygame.joystick.get_count() -> count

Returns the number of joysticks.

Return the number of joystick devices on the system. The count will be 0 if there are no joysticks on the system.

When you create Joystick objects using Joystick(id), you pass an integer that must be lower than this count.

pygame.joystick.Joystick

Create a new Joystick object.
Joystick(id) -> Joystick

Create a new joystick to access a physical device. The id argument must be a value from 0 to pygame.joystick.get_count()-1.

To access most of the Joystick methods, you'll need to init() the Joystick. This is separate from making sure the joystick module is initialized. When multiple Joysticks objects are created for the same physical joystick device (i.e., they have the same ID number), the state and values for those Joystick objects will be shared.

The Joystick object allows you to get information about the types of controls on a joystick device. Once the device is initialized the pygame event queue will start receiving events about its input.

You can call the Joystick.get_name() and Joystick.get_id() functions without initializing the Joystick object.

init() -> None

initialize the Joystick

The Joystick must be initialized to get most of the information about the controls. While the Joystick is initialized the pygame event queue will receive events from the Joystick input.

It is safe to call this more than once.

quit() -> None

uninitialize the Joystick

This will uninitialize a Joystick. After this the pygame event queue will no longer receive events from the device.

It is safe to call this more than once.

get_init() -> bool

check if the Joystick is initialized

Returns True if the init() method has already been called on this Joystick object.

get_id() -> int

get the Joystick ID

Returns the integer ID that represents 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.

get_name() -> string

get the Joystick system name

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.

get_numaxes() -> int

get the number of axes on a Joystick

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.

get_axis(axis_number) -> float

get the current position of an axis

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 zero to get_numaxes()-1.

get_numballs() -> int

get the number of trackballs on a Joystick

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.

get_ball(ball_number) -> x, y

get the relative position of a trackball

Returns the relative movement of a joystick button. The value is a x, y pair holding the relative movement since the last call to get_ball.

The ball number must be an integer from zero to get_numballs()-1.

get_numbuttons() -> int

get the number of buttons on a Joystick

Returns the number of pushable buttons on the joystick. These buttons have a boolean (on or off) state.

Buttons generate a pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP event when they are pressed and released.

get_button(button) -> bool

get the current button state

Returns the current state of a joystick button.

get_numhats() -> int

get the number of hat controls on a Joystick

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.

get_hat(hat_number) -> x, y

get the position of a joystick hat

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.

joystick module example

Example code for joystick module.

import pygame


# Define some colors.
BLACK = pygame.Color('black')
WHITE = pygame.Color('white')


# 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.
class TextPrint(object):
    def __init__(self):
        self.reset()
        self.font = pygame.font.Font(None, 20)

    def tprint(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, (self.x, self.y))
        self.y += self.line_height

    def reset(self):
        self.x = 10
        self.y = 10
        self.line_height = 15

    def indent(self):
        self.x += 10

    def unindent(self):
        self.x -= 10


pygame.init()

# Set the width and height of the screen (width, height).
screen = pygame.display.set_mode((500, 700))

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates.
clock = pygame.time.Clock()

# Initialize the joysticks.
pygame.joystick.init()

# Get ready to print.
textPrint = TextPrint()

# -------- Main Program Loop -----------
while not done:
    #
    # EVENT PROCESSING STEP
    #
    # Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,
    # JOYBUTTONUP, JOYHATMOTION
    for event in pygame.event.get(): # User did something.
        if event.type == pygame.QUIT: # If user clicked close.
            done = True # Flag that we are done so we exit this loop.
        elif event.type == pygame.JOYBUTTONDOWN:
            print("Joystick button pressed.")
        elif event.type == pygame.JOYBUTTONUP:
            print("Joystick button released.")

    #
    # 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(WHITE)
    textPrint.reset()

    # Get count of joysticks.
    joystick_count = pygame.joystick.get_count()

    textPrint.tprint(screen, "Number of joysticks: {}".format(joystick_count))
    textPrint.indent()

    # For each joystick:
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()

        textPrint.tprint(screen, "Joystick {}".format(i))
        textPrint.indent()

        # Get the name from the OS for the controller/joystick.
        name = joystick.get_name()
        textPrint.tprint(screen, "Joystick name: {}".format(name))

        # Usually axis run in pairs, up/down for one, and left/right for
        # the other.
        axes = joystick.get_numaxes()
        textPrint.tprint(screen, "Number of axes: {}".format(axes))
        textPrint.indent()

        for i in range(axes):
            axis = joystick.get_axis(i)
            textPrint.tprint(screen, "Axis {} value: {:>6.3f}".format(i, axis))
        textPrint.unindent()

        buttons = joystick.get_numbuttons()
        textPrint.tprint(screen, "Number of buttons: {}".format(buttons))
        textPrint.indent()

        for i in range(buttons):
            button = joystick.get_button(i)
            textPrint.tprint(screen,
                             "Button {:>2} value: {}".format(i, button))
        textPrint.unindent()

        hats = joystick.get_numhats()
        textPrint.tprint(screen, "Number of hats: {}".format(hats))
        textPrint.indent()

        # Hat position. All or nothing for direction, not a float like
        # get_axis(). Position is a tuple of int values (x, y).
        for i in range(hats):
            hat = joystick.get_hat(i)
            textPrint.display(screen, "Hat {} value: {}".format(i, str(hat)))
        textPrint.unindent()

        textPrint.unindent()

    #
    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
    #

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 20 frames per second.
    clock.tick(20)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()




Edit on GitHub

© Pygame Developers.
Licensed under the GNU LGPL License version 2.1.
https://www.pygame.org/docs/ref/joystick.html