python - Pygame击键事件没有发生
问题描述
在带有 python3.7 windows 10 的 pygame 1.9.4 上运行,我在按键时没有收到任何 KEYDOWN 和 KEYUP 事件。
我编写了许多 pygame 程序,并认为我了解事件处理,但这让我很难过。将 event.pump() 添加到循环中没有区别。在使用 ctrl-C 终止后,实际的击键显示在 shell 中。
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
frame = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.KEYDOWN:
print('Keydown')
if event.key == pygame.K_z:
print('z down')
if pygame.key.get_pressed(pygame.K_z):
print('z pressed')
if event.type == pygame.KEYUP:
print('Keyup')
if event.key == pygame.K_z:
print('z up')
pygame.display.flip()
clock.tick(1)
frame +=1
print(frame)
`
解决方案
尝试这种方式让你的玩家移动,我想你可以包括 print('z down') 部分
moving_right = False
moving_left = False
while True:
moving_right == True:
player_location[0] += 4
if moving_left == True:
player_location[0] -= 4
for event in pygame.event.get(): # event loop
if event.type == QUIT: # check for window quit
pygame.quit() # stop pygame
sys.exit() # stop script
if event.type == KEYDOWN:
if event.key == K_RIGHT:
moving_right = True
if event.key == K_LEFT:
moving_left = True
if event.type == KEYUP:
if event.key == K_RIGHT:
moving_right = False
if event.key == K_LEFT:
moving_left = False
推荐阅读
- java - 自动化 Spring Cloud Profile
- reactjs - 命名导出/未命名导出
- javascript - 无法从 Google App Script 中查看对象内的对象值
- php - 即使不在数组中,Twig 也会返回 true(选中字段)
- javascript - 如何在 Bootsrap 中使用多个列而不是从第 1 列开始?
- ios - 如何提高 CMSampleBuffer 中的音频速度
- python - 如何合并列表?(熊猫数据框)
- python - 对于所有缩放级别,将文本标签保持在与主轴相同的相对 x 位置,同时保持绝对 y 位置
- awk - 添加在 2 列中发现时间相同的新列
- csv - 使用 Pig Latin 计算唯一值的出现次数