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文本输入事件 |