user12824087
user12824087

Reputation:

How do i detect which specific button in my controller is being released in pygame

i am trying to detect which button is being pressed from my controller and when it is released. This is how far i have managed to get.

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("x")
                elif j.get_button(2):
                    print("a")
            elif event.type == pygame.JOYBUTTONUP:
                print("button released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

i am new to programming and i dont entirely understand this piece of code. this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released. Thanks for reading!

Upvotes: 1

Views: 1830

Answers (1)

user10429212
user10429212

Reputation:

pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP). you can only check if a button is pressed and then see which button is pressed.

                if event.type == pygame.JOYBUTTONDOWN:
                    if j.get_button(1):
                        print("x")
                    elif j.get_button(2):
                        print("a")

to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .

ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
           if ButtonStatus[0]!=get_button(1)
                #status changed do yr code for button release a
                pass;
           if ButtonStatus[1]!=get_button(2)
                #status changed do yr code for button release b
                pass;

above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.

Upvotes: 1

Related Questions