0

我正在为机器人编程,我想通过 pygame 使用 Xbox 控制器。到目前为止,这就是我得到的(原始代码归功于 Daniel J. Gonzalez):

"""
Gamepad Module
Daniel J. Gonzalez
dgonz@mit.edu

Based off code from: http://robots.dacloughb.com/project-1/logitech-game-pad/
"""

import pygame


"""
Returns a vector of the following form:
[LThumbstickX, LThumbstickY, Unknown Coupled Axis???, 
RThumbstickX, RThumbstickY, 
Button 1/X, Button 2/A, Button 3/B, Button 4/Y, 
Left Bumper, Right Bumper, Left Trigger, Right Triller,
Select, Start, Left Thumb Press, Right Thumb Press]

Note:
No D-Pad.
Triggers are switches, not variable. 
Your controller may be different
"""

def get():

    out = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    it = 0 #iterator
    pygame.event.pump()

    #Read input from the two joysticks       
    for i in range(0, j.get_numaxes()):
        out[it] = j.get_axis(i)
        it+=1
    #Read input from buttons
    for i in range(0, j.get_numbuttons()):
        out[it] = j.get_button(i)
        it+=1
    first = out[1]
    second = out[2]
    third = out[3]
    fourth = out[4]

    return first, second, third, fourth

def test():
    while True:
        first, second, third, fourth = get()

pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
print 'Initialized Joystick : %s' % j.get_name()
test()

你看到名为“out”的列表了吗?其中的每个元素都是 Xbox 控制器上的一个按钮。我想提取这些元素并将它们放在变量上,每个元素/按钮一个变量,这样我就可以控制我的机器人。

我怎么能做到?我曾尝试使用全局变量,但后来一切都变得一团糟。请注意,我是 Python 的初学者。

4

2 回答 2

1

如果你想out在你的程序中,那么只需从你的函数中返回它get

def get():
  # rest of the code ...
  return out

还要改变你的功能测试:

def test():
    while True:
        out = get()
        LThumbstickX = out[0]
        LThumbstickY = out[1]
        # and so on

然后像以前一样运行你的程序。该函数的test作用是不断地 ( while True) 读取键盘。例如,您可以这样做:

def test():
    while True:
        out = get()
        LThumbstickX = out[0]
        if LThumbstickX != 0:
            print 'Left button has been pressed'
            # and so on
于 2013-05-17T14:13:21.003 回答
1

您可以只返回列表并使用 python 的解包功能:

def get():
    out = [1,2,3,4]
    return out

first, second, third, fourth = get()
于 2013-05-17T14:16:03.777 回答