事件處理的時機
在程序主循環開始,我們獲取事件並進行處理:
# 主循環
while True:
# 事件處理
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# 繪製更新圖形
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
事件類型
事件類型有很多種,例如: QUIT 和 MOUSEMOTION 等, 這些預定義的事件類型作爲常量定義在 pygame.local 模塊中,下面這些是最早的事件類型和它們的屬性,後面不同的版本又補充了例如手勢等事件,具體參考官方文檔:
QUIT none
ACTIVEEVENT gain, state
KEYDOWN key, mod, unicode, scancode
KEYUP key, mod
MOUSEMOTION pos, rel, buttons
MOUSEBUTTONUP pos, button
MOUSEBUTTONDOWN pos, button
JOYAXISMOTION joy, axis, value
JOYBALLMOTION joy, ball, rel
JOYHATMOTION joy, hat, value
JOYBUTTONUP joy, button
JOYBUTTONDOWN joy, button
VIDEORESIZE size, w, h
VIDEOEXPOSE none
USEREVENT code
事件處理模式
我們這裏基本的事件處理模式:
# 主循環
while True:
# 事件處理
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# 處理鼠標按下事件
if event.type == pygame.MOUSEBUTTONDOWN:
print("鼠標按鍵", event)
# 處理鼠標釋放
if event.type == pygame.MOUSEBUTTONUP:
print("鼠標t彈起", event)
# 處理鼠標移動
if event.type == pygame.MOUSEMOTION:
print("鼠標移動", event)
# 處理按鍵
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
print("鍵盤按鍵", event)
# 另一種處理按鍵的方式
pressedKeys = pygame.key.get_pressed()
# print("pressed keys is ", pressedKeys)
# 具體某個按鍵的處理
if (pressedKeys[pygame.K_LEFT]):
print("Key Left is pressed")