【问题标题】:PyGame - RaspberryPi 3b+ with a ps3 controllerPyGame - 带有 ps3 控制器的 RaspberryPi 3b+
【发布时间】:2020-10-15 11:28:50
【问题描述】:

我正在尝试将 pygame 与树莓派一起使用,以使用 PlayStation 3 控制器作为汽车的输入。 我已经用演示代码测试了控制器,一切正常。然后当我尝试在我的程序中使用它时,当操纵杆移动时,它会读取 0.0 作为输入。附件是我当前的代码:

import pygame

class controller:
        def __init__(self):
                pygame.init()
                pygame.joystick.init()
                global joystick
                joystick = pygame.joystick.Joystick(0)
                joystick.init()

        def get_value(self, axis):
                value = joystick.get_axis(axis)
                return value
control = controller()
val = control.get_value(0)
while True:
        print(val)

我知道这个测试只针对轴 0,但所有轴的输出仍然是 0.0。

下面,我附上了演示代码,其中所有值都已正确读取。

import pygame, sys, time    #Imports Modules
from pygame.locals import *

pygame.init()#Initializes Pygame
pygame.joystick.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()#Initializes Joystick

# get count of joysticks=1, axes=27, buttons=19 for DualShock 3

joystick_count = pygame.joystick.get_count()
print("joystick_count")
print(joystick_count)
print("--------------")

numaxes = joystick.get_numaxes()
print("numaxes")
print(numaxes)
print("--------------")

numbuttons = joystick.get_numbuttons()
print("numbuttons")
print(numbuttons)
print("--------------")

loopQuit = False
while loopQuit == False:

    # test joystick axes and prints values
    outstr = ""
    for i in range(0,4):
        axis = joystick.get_axis(i)
        outstr = outstr + str(i) + ":" + str(axis) + "|"
        print(outstr)

    # test controller buttons
    outstr = ""
    for i in range(0,numbuttons):
           button = joystick.get_button(i)
           outstr = outstr + str(i) + ":" + str(button) + "|"
    print(outstr)

    for event in pygame.event.get():
       if event.type == QUIT:
           loopQuit = True
       elif event.type == pygame.KEYDOWN:
           if event.key == pygame.K_ESCAPE:
               loopQuit = True
             
       # Returns Joystick Button Motion
       if event.type == pygame.JOYBUTTONDOWN:
        print("joy button down")
       if event.type == pygame.JOYBUTTONUP:
        print("joy button up")
       if event.type == pygame.JOYBALLMOTION:
        print("joy ball motion")
       # axis motion is movement of controller
       # dominates events when used
       if event.type == pygame.JOYAXISMOTION:
           # print("joy axis motion")

    time.sleep(0.01)
pygame.quit()
sys.exit()

我们将不胜感激任何反馈。

【问题讨论】:

  • 唯一的区别似乎是这一行:global joystick。你试过删除它吗?
  • 我尝试删除全局,但出现错误,“NameError: global name 'joystick' is not defined

标签: python pygame raspberry-pi3 ps3


【解决方案1】:

代码丢失了对初始化操纵杆的引用。它需要维护到它的内部链接。注意在下面的类中使用self.。这将引用保留在类中,使“self.joystick”成为类的member variable。 Python 类需要 self. 表示法(与许多(所有?)其他面向对象的语言不同)。在编辑时,我更改了一些名称以匹配 Python PEP-8 style guide,我希望没关系;)

class Controller:
    def __init__( self, joy_index=0 ):
        pygame.joystick.init()                # is it OK to keep calling this?
        self.joystick = pygame.joystick.Joystick( joy_index )
        self.joystick.init()

    def getAxisValue( self, axis ):
        value = self.joystick.get_axis( axis )
        return value

也许你没有考虑额外的代码,但是没有事件循环的 PyGame 程序最终会被锁定。

import pygame

# Window size
WINDOW_WIDTH    = 300
WINDOW_HEIGHT   = 300


class Controller:
    """ Class to interface with a Joystick """
    def __init__( self, joy_index=0 ):
        pygame.joystick.init()
        self.joystick = pygame.joystick.Joystick( joy_index )
        self.joystick.init()

    def getAxisValue( self, axis ):
        value = self.joystick.get_axis( axis )
        return value


### initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
clock  = pygame.time.Clock()
pygame.display.set_caption( "Any Joy?" )    

# Talk to the Joystick
control = controller()

# Main loop
done = False
while not done:
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Query the Joystick
    val = control.getAxisValue( 0 )
    print( "Joystick Axis: " + str( val ) )

    # Update the window, but not more than 60fps
    window.fill( (0,0,0) )
    pygame.display.flip()
    clock.tick_busy_loop(60)

pygame.quit()

【讨论】:

  • 感谢您的反馈。我已更改代码以使用 self.在课堂里。仅通过此更改,该值仍为 0.0。我试图理解您提供的代码的第二部分。窗户和时钟有什么作用?我只是使用 pygame 从控制器接收一个数字和轴,它最终会告诉汽车前进和后退。
  • @ShaneCourter - Pygame 使用事件模型。如果您停止处理事件,程序最终将停止。您的操作系统可能会认为它“无响应”。有了窗口,事件循环阻止了这种情况的发生。
  • 太棒了,它现在正在工作。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多