Pygame Xbox One 控制器

52
我正在尝试运行一些代码,使用户可以使用Xbox控制器进行控制。我已经使用Pygame使Xbox 360控制器正常工作。然后,当我尝试使用Xbox One控制器时,它能够被识别为"已连接",但无法读取实际的按键操作。
我尝试运行Pygame网站上找到的手柄分析器,它显示已连接,但没有接收到任何按键输入。

enter image description here

这段代码可以在本文档页面底部找到: https://www.pygame.org/docs/ref/joystick.html

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()

        try:
            jid = joystick.get_instance_id()
        except AttributeError:
            # get_instance_id() is an SDL2 method
            jid = joystick.get_id()
        textPrint.tprint(screen, "Joystick {}".format(jid))
        textPrint.indent()

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

        try:
            guid = joystick.get_guid()
        except AttributeError:
            # get_guid() is an SDL2 method
            pass
        else:
            textPrint.tprint(screen, "GUID: {}".format(guid))

        # 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.tprint(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()

有人了解这是为什么吗?


4
你是否已安装 Xbox One 的控制器驱动程序? - Glitch__
@Rjbeckwith 我已经多次在pygame中使用Xbox One控制器。你能显示代码吗? - SamTheProgrammer
1
@PythonProgrammer 这对我来说不再是一个紧急问题了。但是,如果其他人有兴趣获得解决方案,我已经添加了代码。该代码只是我之前提供的链接中的示例代码。 - Rjbeckwith
  1. 它在其他任何上下文中都可以工作吗?
  2. 是USB还是蓝牙?
  3. 连接控制器和启动程序的顺序是什么?
- firelynx
那段代码 中,Xbox One手柄可以工作,使用的类是第147行的JoystickXONE,这可能会很有用。 - Nicola Landro
显示剩余7条评论
3个回答

1

蓝牙可能尚未启用,请尝试启用它或检查控制器电池!


1
我已经尝试过使用Xbox One Series 2手柄运行同样的脚本,并确认它可以完美地工作。我通过充电线将手柄连接到PC上,而不是无线连接(因为我在同一房间里有一个Xbox)。
您应该首先尝试相同的方法,并能够通过按住mainXbutton按钮打开Xbox Game Bar,否则请检查PC上的Xbox设置并从设备管理器中更新驱动程序(有线连接时)。
此外,请确保您拥有最新的Pygame版本,我在Windows 10上尝试了2.1.2版本。
希望这能给您一些提示。

0

如果不起作用,尝试运行控制器测试工具,那么可能是控制器的问题,还应该尝试重新安装pygame并检查是否正确安装了驱动程序


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接