简体   繁体   中英

Extract value from a list in another function in Python

I am programming a robot and I want to use an Xbox Controller using pygame. So far this is what I got (original code credits to 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()

Do you see the list called "out"? Each element in it is a button on the Xbox Controller. I want to extract those elements and put them on variables, one variable to each element/button so I can control my robot.

How could I do it? I've tried to use global variables but then everything turned down to a mess. Please note that I am a beginner in Python.

If you want to have out in your program then just return it from your function get :

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

Also change your function test:

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

Then run your program as before. What the function test does is constantly ( while True ) read the keypad. You could for example do:

def test():
    while True:
        out = get()
        LThumbstickX = out[0]
        if LThumbstickX != 0:
            print 'Left button has been pressed'
            # and so on

You can just return the list and use python's unpacking feature:

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

first, second, third, fourth = get()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM