반응형

컴퓨터에 연결된 조이스틱을 조사하고 각 버튼의 상태를 확인해 보자.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import pygame
 
pygame.init()
 
def main():
    clock = pygame.time.Clock()
 
    joysticks = {}
    # 조이스틱을 관리하기 위한 딕셔너리.
 
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
 
            if event.type == pygame.JOYBUTTONDOWN:
                print("Joystick button pressed.")
                            
            if event.type == pygame.JOYBUTTONUP:
                print("Joystick button released.")
 
            if event.type == pygame.JOYAXISMOTION:
                print("Joystick axis motion detected.")
                
            if event.type == pygame.JOYDEVICEADDED:
                joy = pygame.joystick.Joystick(event.device_index)
                # 컴퓨터에 연결된 물리적 조이스틱에 접근하기 위한 Joystick 클래스 생성.
                # Joystick 클래스 생성자 인수에는 0 부터 pygame.joystick.get_count()-1 까지 대입한다.
                # event.device_index는 0부터 연결된 조이스틱의 숫자 -1 까지 증가하는거 같다.
                joysticks[joy.get_instance_id()] = joy
                # joysticks 딕셔너리에 새로 생성된 Joystick 클래스를 추가한다.
                # joy.get_instance_id() 는 joystick의 instance ID를 반환한다. 이 값은 Joystick 클래스
                # 생성자 인수로 넣은 값과 같은거 같다. event.instance_id 와 같은 값을 가진다.
                print(f"Joystick #{joy.get_instance_id()} connencted")
 
            if event.type == pygame.JOYDEVICEREMOVED:
                del joysticks[event.instance_id]
                # 조이스틱을 분리하면 joysticks 딕셔너리에서 분리된 조이스틱을 삭제한다.
                print(f"Joystick #{event.instance_id} disconnected")
 
        for joystick in joysticks.values():
        # dictionary.values() 는 dict_values라는 리스트 객체를 리턴하며 이 안에는 값의 목록만 들어 있다.
            jid = joystick.get_instance_id()
            name = joystick.get_name()
            guid = joystick.get_guid()
 
            axes = joystick.get_numaxes()
            for i in range(axes):
                axis = joystick.get_axis(i)
                if axis > 0.1 or axis < -0.1:
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Axis #{i}, Value: {axis:>6.3f}")
 
            buttons = joystick.get_numbuttons()
            for i in range(buttons):
                button = joystick.get_button(i)
                if button != 0:
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Button #{i:>2} Value: {button}")
                    
    clock.tick(30)
 
if __name__ == "__main__":
    main()
    pygame.quit()
 

 

조이스틱이 하나만 연결되어 있다면 조금 더 간단히 상태를 확인 할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import pygame
 
pygame.init()
 
joy = None
jid = None
name = None
guid = None
 
def main():
    clock = pygame.time.Clock()
    done = False
 
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
 
            if event.type == pygame.JOYBUTTONDOWN:
                print("Joystick button pressed.")
                buttons = joy.get_numbuttons()
                for i in range(buttons):
                    button = joy.get_button(i)
                    if button != 0:
                        print(f"ID: {jid} Name: {name}, GUID: {guid}, Button #{i:>2} Value: {button}")
                            
            if event.type == pygame.JOYBUTTONUP:
                print("Joystick button released.")
 
            if event.type == pygame.JOYAXISMOTION:
                print("Joystick axis motion detected.")
                # 방향 버튼을 눌렀을 때 -1, 0, 1 같은 정수가 나오지 않을 수 도 있다.
                if joy.get_axis(0> 0.5:                    
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Axis: L/R Value: RIGHT")
                if joy.get_axis(0< -0.5:
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Axis: L/R, Value: LEFT")
                if joy.get_axis(1> 0.5:
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Axis: U/D, Value: DOWN")
                if joy.get_axis(1< -0.5:
                    print(f"ID: {jid} Name: {name}, GUID: {guid}, Axis: U/D, Value: UP")
 
            if event.type == pygame.JOYDEVICEADDED:
                joy = pygame.joystick.Joystick(event.device_index)
                jid = joy.get_instance_id()
                name = joy.get_name()
                guid = joy.get_guid()
                print(f"Joystick #{joy.get_instance_id()} connencted")
 
            if event.type == pygame.JOYDEVICEREMOVED:
                print(f"Joystick #{event.instance_id} disconnected")
 
    clock.tick(30)
 
if __name__ == "__main__":
    main()
    pygame.quit()
 

 

 

버튼을 누를때 마다 상태를 표시한다.

 

반응형
Posted by J-sean
: