pygame

 

2023-11-29

macOS 中控制通过蓝牙连接的 Xbox 手柄。

Terminal window
1
import pygame
2
# 先初始化
3
pygame.init()
4
pygame.joystick.init()
5
6
# 获取手柄数量
7
pygame.joystick.get_count()
8
9
# 获取第一个手柄,并初始化
10
joystick = pygame.joystick.Joystick(0)
11
joystick.init()
12
13
# 退出
14
pygame.quit()

joystick

1
# 初始化
2
joystick = pygame.joystick.Joystick(0)
3
joystick.init()
4
5
# 手柄名称
6
joystick.get_name()
7
# 手柄按钮数
8
joystick.get_numbuttons()
9
# 手柄轴数
10
joystick.get_numaxes()

rumble

手柄震动效果设置,如果成功,返回 True。

语法:joystick.rumble(<低频>, <高频>, <持续事件>)

1
for event in pygame.event.get():
2
if event.type == pygame.JOYBUTTONDOWN:
3
print("Joystick button pressed.")
4
if event.button == 0:
5
joystick = joysticks[event.instance_id]
6
if joystick.rumble(0, 0.7, 500):
7
print(f"Rumble effect played on joystick {event.instance_id}")

evenv

手柄事件。

1
pygame.event.wait()
2
pygame.event.get() # 返回 list
1
for event in pygame.event.get():
2
# 获取按钮名称编号
3
if event.type == pygame.JOYBUTTONDOWN:
4
print(f"按下按钮{event.button}") # 输出按钮编号
5
elif event.type == pygame.JOYBUTTONUP:
6
print(f"松开按钮:{event.button}")
7
# 获取摇杆
8
elif event.type == pygame.JOYAXISMOTION:
9
print(event.axis) # 输出摇杆值

硬件映射

XBox

摇杆

  • Left Stick:左摇杆
    • 0: Up -> Down
    • 1: Left -> Right
  • Right Stick:右摇杆
    • 2: Up -> Down
    • 3: Left -> Right

扳机

  • Left Tigger:左扳机键
    • 4: Out -> On
  • Right Tigger:右扳机键
    • 5: Out -> On

按钮

  • 0: A
  • 1: B
  • 2: X
  • 3: Y
  • 4: View button (中间左)
  • 5: Xbox button (西瓜键)
  • 6: Menu button (中间右)
  • 7: L. Stick In (左摇杆按下)
  • 8: R. Stick In (右摇杆按下)
  • 9: Left Bumper (LB 左缓冲键)
  • 10: Right Bumper (RB 右缓冲键)
  • 11: 上 (方向键)
  • 12: 下 (方向键)
  • 13: 左 (方向键)
  • 14: 右 (方向键)
  • 15: 共享按钮 (中间按钮)

参考