I am making a game with snake-like movement. I think, that the best way to achieve a good result, is to make separate thread for handling user's keyboard input. Here is my function that i want to run in separate thread:
def _handle_keyboard_input(self):
while self.is_running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self._set_velocity(-1, 0)
elif event.key == pygame.K_RIGHT:
self._set_velocity(1, 0)
elif event.key == pygame.K_UP:
self._set_velocity(0, -1)
elif event.key == pygame.K_DOWN:
self._set_velocity(0, 1)
def _set_velocity(self, x, y):
self._velocity_x = x
self._velocity_y = y
Although i worry, whether constantly looping through that while will load the CPU too much. I thought about adding pygame.time.delay()
delays, but then I'm not sure if i will "hit" the right moment for the KEYDOWN event (graphic that i found on this site below).
I don't want to use pygame.key.get_pressed()
because i don't want to prioritize any keys (in example if left and up arrow were pressed at the same time, I would have to choose one of them).
What is the best approach to this?