Pygame 简明教程
Pygame - Keyboard Events
Pygame 识别 KEYUP 和 KEYDOWN 事件。pygame.key 模块定义了用于处理键盘交互的有用函数。当按下并释放键时,pygame.KEYDOWN 和 pygame.KEYUP 事件会插入事件队列。key 属性是表示键盘上每个键的整型 ID。
Pygame recognizes KEYUP and KEYDOWN events. The pygame.key module defines functions useful for handling keyboard interaction. pygame.KEYDOWN and pygame.KEYUP events are inserted in event queue when the keys are pressed and released. key attribute is an integer ID representing every key on the keyboard.
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 控制台上的示例输出。
Run the above code and press various keys while the Pygame window is active. Following is a sample output on Python console.
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 属性返回与每个键关联的唯一标识符。箭头键左、右、上和下在游戏情境中非常常用。如果检测到特定的按键,我们可以编写适当的逻辑。
As we see, event.key attribute returns a unique identifier associated with each key. The arrow keys left, right, up and down are used very often in a game situation. We can right appropriate logic if a particular key press is detected.
pygame.key 模块中的其他有用属性如下所示:
Other useful attributes in pygame.key module are listed below −
pygame.key.get_pressed |
get the state of all keyboard buttons |
pygame.key.get_mods |
determine which modifier keys are being held |
pygame.key.set_repeat |
control how held keys are repeated |
pygame.key.get_repeat |
see how held keys are repeated |
pygame.key.name |
get the name of a key identifier |
pygame.key.key_code |
get the key identifier from a key name |
pygame.key.start_text_input |
start handling Unicode text input events |
pygame.key.stop_text_input |
stop handling Unicode text input events |