簡體   English   中英

從 function 獲取多個變量值或信息的最佳方法

[英]Best way to get multiple variable values or information from a function

我對 python 相當陌生,並且正在嘗試創建一個自定義模塊,我可以使用 evdev 為我的樹莓派導入該模塊(不是那么重要)。 我的問題是我需要一個好方法來知道何時按下給定按鈕,最好使用 True/False。 如果我要導入此模塊並使用 read_stream() function,那么能夠收集多種類型的輸入的最簡單方法是什么。 (只是為了澄清,gamepad.read_loop() 每次迭代只返回一個值。

from evdev import InputDevice, categorize, ecodes

aBtn = 304
bBtn = 305
xBtn = 307
yBtn = 308

LBmper = 310
RBmper = 311

MenuBtn = 315
WindowBtn = 314
XboxBtn = 316

HorizontalDp = 16
VerticalDp = 17

RightT = 5
LeftT = 2

LeftStickClick = 317
RightStickClick = 318

Ls_X = 0
Ls_Y = 1
Rs_X = 3
Rs_Y = 4

def read_stream(input_path, trigger_deadzone):
    '''Begins the loop that reads all of the incoming events.'''
    button_list = ['aBtn_pressed', 'bBtn_pressed', 'xBtn_pressed', 'yBtn_pressed', 'lBmper_pressed', 'rBmper_pressed', 'mBtn_pressed', 'wBtn_pressed', 'xbxBtn_pressed', 'rDp_pressed', 'lDp_pressed', 'dDp_pressed', 'uDp_pressed', 'Ls_clicked', 'Rs_clicked', 'Ls_right', 'Ls_left', 'Ls_down', 'Ls_up', 'Rs_right', 'Rs_left', 'Rs_down', 'Rs_up', 'Lt_custom', 'Rt_custom']
    for button in button_list:
        button = False
    gamepad = InputDevice(input_path)
    if (not "Microsoft X-Box One S pad" in str(gamepad)):
        raise Exception("Invalid input device, please make sure you are using an Xbox One S controller.\nAlso make sure that the correct input path is set.")
    print("Stream is reading: ", gamepad)
    for event in gamepad.read_loop():
        value = event.value
        code = event.code
        if (code == aBtn):
        #if (304 <= code <= 308):
            if (code == aBtn):
                if (value == 1):
                    aBtn_pressed = True
                else:
                    aBtn_pressed = False
            elif (code == bBtn):
                if (value == 1):
                    bBtn_pressed = True
                else:
                    bBtn_pressed = False
            elif (code == xBtn):
                if (value == 1):
                    xBtn_pressed = True
                else:
                    xBtn_pressed = False
            else:
                if (value == 1):
                    yBtn_pressed = True
                else:
                    yBtn_pressed = False
        else:
            print("Unfiltered stream input.")

很難確切地確定您要問什么,但是如果您每次調用 function 時都想要每個按鈕的 state,一種方法是每次都在字典中返回當前值。

例如:

buttons = {
   304:"A",
   305:"B",
   307:"X",
   308:"Y" )

# and then your read stream function would be modified to look like

pressed = dict()
for event in gamepad.read_loop():
   btn = buttons[event.code]
   pressed[btn] = bool(event.value)
return pressed

暫無
暫無

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

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