Reputation: 95
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()
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.
Any help is massively appreciated!
Upvotes: 4
Views: 1479
Reputation: 210909
[...] and have two for event in
pygame.event.get()
loops [..]"
That's the issue. pygame.event.get()
get all the messages and remove them from the queue. See the documentation:
This will get all the messages and remove them from the queue. [...]
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)
Upvotes: 6