Pygame 键盘事件
Pygame识别KEYUP和KEYDOWN事件。pygame.key模块定义了处理键盘交互的有用函数。当按下和释放键时,pygame.KEYDOWN和pygame.KEYUP事件将插入事件队列中。key属性是表示键盘上每个键的整数ID。
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Hello World")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
key=pygame.key.name(event.key)
print (key, "Key is pressed")
if event.type == pygame.KEYUP:
key=pygame.key.name(event.key)
print (key, "Key is released")
运行上述代码并在Pygame窗口处于活动状态时按下各种键。以下是Python控制台上的示例输出。
q Key is pressed
q Key is released
right shift Key is released
1 Key is pressed
1 Key is released
enter Key is pressed
enter Key is released
backspace Key is pressed
backspace Key is released
x Key is pressed
x Key is released
home Key is pressed
home Key is released
f1 Key is pressed
f1 Key is released
left Key is pressed
left Key is released
right Key is pressed
right Key is released
up Key is pressed
up Key is released
down Key is pressed
down Key is released
如我们所见,event.key属性返回与每个按键相关联的唯一标识符。在游戏情境中,左、右、上和下箭头键经常被使用。如果检测到特定的按键按下,我们可以编写适当的逻辑。
pygame.key模块中的其他有用属性如下所示:
pygame.key.get_pressed | 获取所有键盘按钮的状态 |
---|---|
pygame.key.get_mods | 判断正在按下的修饰键 |
pygame.key.set_repeat | 控制按下的键的重复 |
pygame.key.get_repeat | 查看按下的键如何重复 |
pygame.key.name | 获取键盘标识符的名称 |
pygame.key.key_code | 通过键名获取键盘标识符 |
pygame.key.start_text_input | 开始处理Unicode文本输入事件 |
pygame.key.stop_text_input | 停止处理Unicode文本输入事件 |