Coding-robot-手柄按键检测

检测按下的手柄按键序号

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
import pygame
import sys

# 初始化pygame
pygame.init()

# 设置手柄
pygame.joystick.init()

# 检查是否有手柄连接
if pygame.joystick.get_count() == 0:
print("没有检测到手柄。")
sys.exit()

# 获取手柄对象
joystick = pygame.joystick.Joystick(0)
joystick.init()

print(f"已连接手柄: {joystick.get_name()}")

# 主循环
try:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

# 检测手柄按钮按下
if event.type == pygame.JOYBUTTONDOWN:
print(f"按钮 {event.button} 被按下")

# 检测手柄按钮释放
elif event.type == pygame.JOYBUTTONUP:
print(f"按钮 {event.button} 被释放")

# 检测手柄轴移动
elif event.type == pygame.JOYAXISMOTION:
print(f"轴 {event.axis} 移动到 {event.value}")

except KeyboardInterrupt:
pygame.quit()