Python pygame.JOYAXISMOTION Examples

The following are 10 code examples of pygame.JOYAXISMOTION(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source Project: Retropie-CRT-Edition   Author: krahsdevil   File: core_controls.py    License: GNU General Public License v3.0 6 votes vote down vote up
def event_wait(self):
        while True:
            for event in pygame.event.get():
                if self.m_bUnload: break
                if event.type == pygame.KEYDOWN:
                    input = self.get_key(event.key)
                    if input: return input
                elif event.type == pygame.JOYBUTTONDOWN:
                    input = self.get_button(event.joy, event.button)
                    if input: return input
                elif event.type == pygame.JOYHATMOTION:
                    input = self.get_hat(event.value)
                    if input: return input
                elif event.type == pygame.JOYAXISMOTION:
                    input = self.get_axis(event.joy, event.axis, event.value)
                    if input: return input
            self.m_oClock.tick(20)
            pygame.time.wait(0) 
Example #2
Source Project: stuntcat   Author: pygame   File: event_handling.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def check_axis(self, pg_event):
        if pg_event.type == pg.JOYAXISMOTION:
            value = pg_event.value

            if pg_event.axis == 0:
                if abs(value) >= self.deadzone:
                    if value < 0:
                        self.press(actions.LEFT, value * -1)
                    else:
                        self.press(actions.RIGHT, value)
                else:
                    self.release(actions.LEFT)
                    self.release(actions.RIGHT)

            elif pg_event.axis == 1:
                if abs(value) >= self.deadzone:
                    if value < 0:
                        self.press(actions.UP, value * -1)
                    else:
                        self.press(actions.DOWN, value)
                else:
                    self.release(actions.UP)
                    self.release(actions.DOWN) 
Example #3
Source Project: football   Author: google-research   File: gamepad.py    License: Apache License 2.0 6 votes vote down vote up
def take_action(self, observations):
    assert len(observations) == 1, 'Gamepad does not support multiple player control'
    x_axis = self._joystick.get_axis(0)
    y_axis = self._joystick.get_axis(1)
    left = x_axis < -0.5
    right = x_axis > 0.5
    top = y_axis < -0.5
    bottom = y_axis > 0.5
    active_buttons = {}
    for event in event_queue.get('gamepad', self._index):
      if event.type == pygame.JOYBUTTONDOWN:
        actions = BUTTON_TO_ACTIONS.get(event.button, [])
        for a in actions:
          active_buttons[a] = 1
      if (event.type == pygame.JOYAXISMOTION and event.axis == 5 and
          event.value > 0):
        active_buttons[football_action_set.action_sprint] = 1

    for button, actions in BUTTON_TO_ACTIONS.items():
      if self._joystick.get_button(button):
        for a in actions:
          active_buttons[a] = 1
    if self._joystick.get_axis(5) > 0:
      active_buttons[football_action_set.action_sprint] = 1
    return self.get_env_action(left, right, top, bottom, active_buttons) 
Example #4
Source Project: pyparrot   Author: amymcgovern   File: demoSwingJoystick.py    License: MIT License 6 votes vote down vote up
def mapping_axis(joystick, axes=["pitch", "roll", "yaw", "vertical"]):
    """
    Associating the analog thumbsticks of the controller with a command in dict commands

    :param joystick, dict_commands:
    :return mapping:
    """
    mapping = {}

    for i in axes:
        print("Push the", i, "axis")
        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.JOYAXISMOTION:
                    if event.axis not in (value for value in mapping.values()):
                        mapping[i] = event.axis
                        done = True

    return mapping 
Example #5
Source Project: pygame-menu   Author: ppizarror   File: _utils.py    License: MIT License 5 votes vote down vote up
def joy_motion(x=0.0, y=0.0, inlist=True, testmode=True):
        """
        Create a pygame joy controller motion event.

        :param x: X axis movement
        :type x: float
        :param y: Y axis movement
        :type y: float
        :param inlist: Return event in a list
        :type inlist: bool
        :param testmode: Key event is in test mode
        :type testmode: bool
        :return: Event
        :rtype: :py:class:`pygame.event.Event`
        """
        if x != 0 and y != 0:
            return [PygameUtils.joy_motion(x=x, y=0, inlist=False, testmode=testmode),
                    PygameUtils.joy_motion(x=0, y=y, inlist=False, testmode=testmode)]
        event_obj = None
        if x != 0:
            event_obj = pygame.event.Event(pygame.JOYAXISMOTION,
                                           {'value': x,
                                            'axis': pygame_menu.controls.JOY_AXIS_X,
                                            'test': testmode
                                            })
        if y != 0:
            event_obj = pygame.event.Event(pygame.JOYAXISMOTION,
                                           {'value': y,
                                            'axis': pygame_menu.controls.JOY_AXIS_Y,
                                            'test': testmode
                                            })
        if inlist:
            event_obj = [event_obj]
        return event_obj 
Example #6
Source Project: universalSmashSystem   Author: digiholic   File: controller.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getInputs(self,_event,_push = True, _outputOnRelease = True):
        if _event.type not in [pygame.JOYAXISMOTION, pygame.JOYBUTTONDOWN, pygame.JOYBUTTONUP]:
            return None
        k = None
        output = True
        if _event.type == pygame.JOYAXISMOTION:
            #getJoystickInput will get a pad and an axis, and return the value of that stick
            #by checking it along with the other axis of that joystick, if there is one.
            k = self.key_bindings.getJoystickInput(_event.joy,_event.axis,_event.value)
            if k and k in self.keys_held: k = None
            if k and k not in self.keys_held:
                self.keys_held.append(k)
            if k and _push:
                self.keys_to_pass.append(k)
                
            if k == 0:
                output = output and _outputOnRelease
                a, b = self.key_bindings.axis_bindings.get(_event.axis)
                if a in self.keys_held: self.keys_held.remove(a)
                if b in self.keys_held: self.keys_held.remove(b)
                if _push:
                    self.keys_to_release.extend([a,b])
        elif _event.type == pygame.JOYBUTTONDOWN:
            #getButtonInput is much more simple. It gets the key that button is mapped to
            k = self.key_bindings.getButtonInput(_event.joy,_event.button)
        elif _event.type == pygame.JOYBUTTONUP:
            output = output and _outputOnRelease
            k = self.key_bindings.getButtonInput(_event.joy,_event.button)
        
        if k:
            if _event.type == pygame.JOYBUTTONDOWN:
                if k not in self.keys_held: self.keys_held.append(k)
                if _push: self.keys_to_pass.append(k)
                
            elif _event.type == pygame.JOYBUTTONUP:
                if k in self.keys_held: self.keys_held.remove(k)
                if _push: self.keys_to_release.append(k)
        if output: return k
        return None 
Example #7
Source Project: pygame-menu   Author: ppizarror   File: selector.py    License: MIT License 4 votes vote down vote up
def update(self, events):
        updated = False
        for event in events:  # type: pygame.event.Event

            if event.type == pygame.KEYDOWN:  # Check key is valid
                if not check_key_pressed_valid(event):
                    continue

            # Events
            keydown = event.type == pygame.KEYDOWN
            joy_hatmotion = self.joystick_enabled and event.type == pygame.JOYHATMOTION
            joy_axismotion = self.joystick_enabled and event.type == pygame.JOYAXISMOTION
            joy_button_down = self.joystick_enabled and event.type == pygame.JOYBUTTONDOWN

            if keydown and event.key == _controls.KEY_LEFT or \
                    joy_hatmotion and event.value == _controls.JOY_LEFT or \
                    joy_axismotion and event.axis == _controls.JOY_AXIS_X and event.value < _controls.JOY_DEADZONE:
                self.sound.play_key_add()
                self.left()
                updated = True

            elif keydown and event.key == _controls.KEY_RIGHT or \
                    joy_hatmotion and event.value == _controls.JOY_RIGHT or \
                    joy_axismotion and event.axis == _controls.JOY_AXIS_X and event.value > -_controls.JOY_DEADZONE:
                self.sound.play_key_add()
                self.right()
                updated = True

            elif keydown and event.key == _controls.KEY_APPLY or \
                    joy_button_down and event.button == _controls.JOY_BUTTON_SELECT:
                self.sound.play_open_menu()
                self.apply(*self._elements[self._index][1:])
                updated = True

            elif self.mouse_enabled and event.type == pygame.MOUSEBUTTONUP:
                if self._rect.collidepoint(*event.pos):
                    # Check if mouse collides left or right as percentage, use only X coordinate
                    mousex, _ = event.pos
                    topleft, _ = self._rect.topleft
                    topright, _ = self._rect.topright
                    dist = mousex - (topleft + self._title_size)  # Distance from label
                    if dist > 0:  # User clicked the options, not label

                        # Position in percentage, if <0.5 user clicked left
                        pos = dist / float(topright - topleft - self._title_size)
                        if pos <= 0.5:
                            self.left()
                        else:
                            self.right()
                        updated = True

        return updated 
Example #8
Source Project: universalSmashSystem   Author: digiholic   File: controller_test.py    License: GNU General Public License v3.0 4 votes vote down vote up
def main():
    pygame.init()
    pygame.joystick.init()
    
    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption('Joystick Test')
        
    joystick_count = pygame.joystick.get_count()
    
    joysticks = []
    
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()
        offset = 0
        for i in range(joystick.get_numaxes() / 2):
            joysticks.append(JoystickMonitor(offset))
            offset += 200
    
    clock = pygame.time.Clock()
    status = True
    while status:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.JOYAXISMOTION:
                joystick = pygame.joystick.Joystick(event.joy)
                if event.axis == 0 or event.axis == 1:
                    xaxis = 0
                    yaxis = 1
                    stick = 0
                    x, y = (joystick.get_axis(xaxis) * 100,joystick.get_axis(yaxis) * 100)
                    joysticks[stick].relocateJoystick(x,y)    
                elif event.axis == 3 or event.axis == 4:
                    xaxis = 4
                    yaxis = 3
                    stick = 1
                    x, y = (joystick.get_axis(xaxis) * 100,joystick.get_axis(yaxis) * 100)
                    joysticks[stick].relocateJoystick(x,y)    
                    
        screen.fill([100,100,100])
        for monitor in joysticks:
            monitor.draw(screen,monitor.rect.topleft,1.0)
            
        pygame.display.flip()
        clock.tick(60) 
Example #9
Source Project: ledmatrix   Author: makeTVee   File: games_pi_only.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def shutdownScreen():
        
    if PI:
        device.clear();
        device.show();
        drawImage('/home/pi/shutdown.bmp')
        show_message(device,"Press Select to shutdown!",fill="white", font=proportional(CP437_FONT), scroll_delay=0.01)
    else:
        drawImage('shutdown.bmp')
       
    while True:

        pygame.event.pump()
        for event in pygame.event.get(): # User did something
            # print("event detected {}".format(event))
            # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
            if event.type == pygame.JOYBUTTONDOWN or event.type == KEYDOWN:
                if event.type == pygame.JOYBUTTONDOWN:
                    myevent = event.button
                else:
                    if event.key in mykeys:
                        myevent = mykeys[event.key]
                    else:
                        myevent = -1
                # print("Joystick button pressed: {}".format(event.button))
                if (myevent!=JKEY_SEL):
                    # print("exiting clock")
                    clearScreen()
                    updateScreen()
                    return
                else: 
                    if not PI:
                        terminate()
                    else:
                        clearScreen()
                        updateScreen()
                        show_message(device,"Shutdown...",fill="white", font=proportional(CP437_FONT), scroll_delay=0.01)
                        subprocess.Popen(['shutdown','-h','now'])
                        #call("sudo nohup shutdown -h now", shell=True)
                        terminate()
            if event.type == pygame.QUIT: # get all the QUIT events
                terminate() # terminate if any QUIT events are present

        updateScreen()
        time.sleep(.2) 
Example #10
Source Project: AgileTrainer   Author: diyjac   File: pygameJoyDriveInterface.py    License: MIT License 4 votes vote down vote up
def telemetry(sid, data):
    # The current steering angle of the car
    steering_angle = data["steering_angle"]
    # The current throttle of the car
    throttle = data["throttle"]
    # The current speed of the car
    speed = data["speed"]
    # The current image from the center camera of the car
    imgString = data["image"]
    image = Image.open(BytesIO(base64.b64decode(imgString)))
    image_prep = np.asarray(image)
    image_array = preprocess(image_prep)

    ### Maybe use recording flag to start image data collection?
    recording = False
    for event in pygame.event.get():
        if event.type == pygame.JOYAXISMOTION:
            print("Joystick moved")
        if event.type == pygame.JOYBUTTONDOWN:
            print("Joystick button pressed.")

    ### Get joystick and initialize
    ### Modify/Add here for keyboard interface
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

    # We are using PS3 left joystick: so axis (0,1) run in pairs, left/right for 2, up/down for 3
    # Change this if you want to switch to another axis on your joystick!
    # Normally they are centered on (0,0)
    leftright = joystick.get_axis(0)/2.0
    updown = joystick.get_axis(1)

    ### Again - may want to try using "recording" flag here to gather images and steering angles for training.
    if leftright < -0.01 or leftright > 0.01:
        if joystick.get_button(0) == 0:
            recording = True
    if recording:
        print("Recording: ")
        print("Right Stick Left|Right Axis value {:>6.3f}".format(leftright) )
        print("Right Stick Up|Down Axis value {:>6.3f}".format(updown) )

    transformed_image_array = image_array[None, :, :, :]
    # This model currently assumes that the features of the model are just the images. Feel free to change this.
    steering_angle = float(model.predict(transformed_image_array, batch_size=1)) + leftright
    # The driving model currently just outputs a constant throttle. Feel free to edit this.

    ### we can force the car to slow down using the up joystick movement.
    throttle = 0.5 + updown
    print(steering_angle, throttle)
    send_control(steering_angle, throttle)