Python pygame.JOYBUTTONDOWN Examples

The following are 11 code examples of pygame.JOYBUTTONDOWN(). 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 File: core_controls.py    From Retropie-CRT-Edition with 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 File: gamepad.py    From football with 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 #3
Source File: demoSwingJoystick.py    From pyparrot with MIT License 6 votes vote down vote up
def mapping_button(joystick, dict_commands):
    """
    Associating a controller key with a command in dict_commands.

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

    for command in dict_commands:
        print("Press the key", command)
        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.JOYBUTTONDOWN:
                    if event.button not in (value for value in mapping.values()):
                        mapping[command] = event.button
                        done = True

    return mapping 
Example #4
Source File: event_handling.py    From stuntcat with GNU Lesser General Public License v2.1 5 votes vote down vote up
def check_button(self, pg_event):
        try:
            button = self.event_map[pg_event.button]
            if pg_event.type == pg.JOYBUTTONDOWN:
                self.press(button)
            elif pg_event.type == pg.JOYBUTTONUP:
                self.release(button)
        except (KeyError, AttributeError):
            pass 
Example #5
Source File: button.py    From pygame-menu with MIT License 5 votes vote down vote up
def update(self, events):
        updated = False
        for event in events:  # type: pygame.event.Event

            if event.type == pygame.KEYDOWN and event.key == _controls.KEY_APPLY or \
                    self.joystick_enabled and event.type == pygame.JOYBUTTONDOWN and event.button == _controls.JOY_BUTTON_SELECT:
                self.sound.play_open_menu()
                self.apply()
                updated = True

            elif self.mouse_enabled and event.type == pygame.MOUSEBUTTONUP:
                self.sound.play_click_mouse()
                if self._rect.collidepoint(*event.pos):
                    self.apply()
                    updated = True

        return updated 
Example #6
Source File: menubar.py    From pygame-menu with MIT License 5 votes vote down vote up
def update(self, events):
        updated = False
        for event in events:  # type: pygame.event.Event

            if self.mouse_enabled and event.type == pygame.MOUSEBUTTONUP:
                if self._backbox_rect and self._backbox_rect.collidepoint(*event.pos):
                    self.sound.play_click_mouse()
                    self.apply()
                    updated = True

            elif self.joystick_enabled and event.type == pygame.JOYBUTTONDOWN:
                if event.button == _controls.JOY_BUTTON_BACK:
                    self.sound.play_key_del()
                    self.apply()
                    updated = True

        return updated 
Example #7
Source File: selector.py    From pygame-menu with MIT License 5 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 File: controller.py    From universalSmashSystem with 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 #9
Source File: mainMenu.py    From universalSmashSystem with GNU General Public License v3.0 5 votes vote down vote up
def executeMenu(self,_screen):
        clock = pygame.time.Clock()
        while self.status == 0:
            self.update(_screen)
            music = musicManager.getMusicManager()
            music.doMusicEvent()
            
            for event in pygame.event.get():
                if event.type == KEYDOWN or event.type == pygame.JOYBUTTONDOWN:
                    if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
                        self.status = 1
                    else:
                        menu = MainMenu(self._parent)
                        self._parent.music.rollMusic('menu')
                        menu.star_color = self.hsv
                        ret_value = menu.executeMenu(_screen)
                        pygame.mixer.music.fadeout(1000)
                        if ret_value == -1: return -1

                if event.type == QUIT:
                    self.status = -1
                    sys.exit()
            
            
            rgb = tuple(i * 255 for i in colorsys.hsv_to_rgb(self.hsv[0],self.hsv[1],self.hsv[2]))
            _screen.fill(rgb)
            self.logo.draw(_screen, self.logo.rect.topleft, 1.0)
            self.start.draw(_screen, self.start.rect.topleft, 1.0)
            
            clock.tick(60)    
            pygame.display.flip()
        
        return self.status 
Example #10
Source File: games_pi_only.py    From ledmatrix with 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 #11
Source File: pygameJoyDriveInterface.py    From AgileTrainer with 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)