簡體   English   中英

從Python中另一個函數的列表中提取值

[英]Extract value from a list in another function in Python

我正在編程一個機器人,我想使用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的初學者。

如果你想有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

您只需返回列表並使用python的解包功能:

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

first, second, third, fourth = get()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM