I’m trying create this function such that if any key besides any of the arrow keys are pressed, the loop continues until an arrow key is pressed. The program crashes every time and doesn’t display the error. Any idea why?
def speed(self, key):
# Figure out if it was an arrow key. If so
# adjust speed
n = 'go'
while n == 'go':
if key == pygame.K_LEFT:
x_speed=-5
y_speed=0
return x_speed, y_speed
n = 'stop'
if key == pygame.K_RIGHT:
x_speed = 5
y_speed = 0
return x_speed, y_speed
n = 'stop'
if key == pygame.K_UP:
y_speed = -5
x_speed = 0
return x_speed, y_speed
n = 'stop'
if key == pygame.K_DOWN:
y_speed = 5
x_speed = 0
return x_speed, y_speed
n = 'stop'
else:
continue
Observing the following criteria:
The loop will only end when
keyis an arrow, because the onlyreturnstatements andn = 'stop'statements happen whenkeyis an arrow key.The value of
keywill never change from inside the loop, because the only declaration ofkeyis in the definition ofspeed()We determine: if we call speed() with a non-arrow
key, the loop will never finish. When you hit an infinite loop in the main execution thread of a program, it has a habit of freezing everything and eating delicious CPU cycles.The solution is to implement your logic asynchronously. If you press a key, it should observe the state of the system, change whatever it needs to trigger actions, then quickly return so as to not slow the program. A never-ending
whileloop isn’t anything close to optimal in the middle of your key-detection logic.