问题描述
我正在 pygame 中制作一个 Asteroidz 克隆,并且有两个 for event in pygame.event.get()
循环,一个用于检查退出请求以及游戏是否应该通过按空格键开始,然后在游戏中进一步尝试限制玩家按住空格键并连续射击.我的 check_input
函数的相关代码(每个循环运行一次)如下;
I'm making an Asteroidz clone in pygame and have two for event in pygame.event.get()
loops, one for checking an exit request and wether the game should have started by pressing spacebar, then further in the game as to try and limit the player from holding spacebar down and continuously shooting. The relevent code for my check_input
function, which is run once every loop, is below;
def check_input(self):
for event in pygame.event.get(): #NOT CHECKING THIS FAST ENOUGH, WHOLE PROCESS IS TOO SLOW
if (event.type == pygame.KEYUP) and (event.key == pygame.K_SPACE):
print ('boop')
self.shootThrottle = 0
if self.shootThrottle == 0:
self.shootThrottle += 1
bullets.add(Bullet(self.shape[0][0],self.shape[0][1], self.angle))
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.angle -= 7
self.rotate(-7)
elif key[pygame.K_RIGHT]:
self.angle += 7
self.rotate(7)
if self.angle > 360:
self.angle -= 360
elif self.angle < 0:
self.angle += 360
if key[pygame.K_UP]:
self.accelerate()
elif key[pygame.K_DOWN]:
self.decelerate()
我使用 shootThrottle
作为尝试阻止子弹射出的方法,直到松开空格键.这个系统可以工作,但是由于 pygame.event.get() 中的 for 事件太慢,它不能正常工作.
I am using shootThrottle
as a means to try stop bullets from being shot until spacebar has been let go. This system works, but due to the for event in pygame.event.get()
being too slow, it doesn't function properly.
非常感谢任何帮助!
推荐答案
这就是问题所在.pygame.event.get()
获取所有消息并将它们从队列中删除.请参阅文档:
That's the issue. pygame.event.get()
get all the messages and remove them from the queue. See the documentation:
这将获取所有消息并将它们从队列中删除.[...]
如果 pygame.event.get()
在多个事件循环中被调用,只有一个循环接收事件,但不会所有循环都接收所有事件.结果,似乎错过了一些事件.
If pygame.event.get()
is called in multiple event loops, only one loop receives the events, but never all loops receive all events. As a result, some events appear to be missed.
每帧获取一次事件并在多个循环中使用它们或将列表或事件传递给处理它们的函数和方法:
Get the events once per frame and use them in multiple loops or pass the list or events to functions and methods where they are handled:
def handle_events(events):
for event in events:
# [...]
while run:
event_list = pygame.event.get()
# [...]
# 1st event loop
for event in event_list:
# [...]
# [...]
# 2nd event loop
for event in event_list:
# [...]
# [...]
# function which handles events
handle_events(event_list)
这篇关于'pygame.event.get()' 的更快版本.为什么会错过事件,为什么会延迟事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!