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 コントローラーのボタンです。これらの要素を抽出して変数に配置し、各要素/ボタンに 1 つの変数を配置して、ロボットを制御できるようにします。

どうすればできますか?グローバル変数を使用しようとしましたが、すべてが混乱しました。私はPythonの初心者です。

4

2 に答える 2

1

リストを返すだけで、python のアンパック機能を使用できます。

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

first, second, third, fourth = get()
于 2013-05-17T14:16:03.777 に答える
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 に答える