continue loop if arrow keys are not pressed in pygame
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 开发者_JAVA技巧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
I have never used pygame in my life, nor written a single word of python, but here's my guess:
def speed(self, key):
# Figure out if it was an arrow key. If so
# adjust speed
if key == pygame.K_LEFT:
x_speed=-5
y_speed=0
return x_speed, y_speed
if key == pygame.K_RIGHT:
x_speed = 5
y_speed = 0
return x_speed, y_speed
if key == pygame.K_UP:
y_speed = -5
x_speed = 0
return x_speed, y_speed
if key == pygame.K_DOWN:
y_speed = 5
x_speed = 0
return x_speed, y_speed
The reason your code doesn't work is because when an arrow key isn't pressed you are effectively doing this:
n = "go"
while n == "go":
continue
Apologies for syntax errors, and also if I'm wrong, ell.
Observing the following criteria:
The loop will only end when
key
is an arrow, because the onlyreturn
statements andn = 'stop'
statements happen whenkey
is an arrow key.The value of
key
will never change from inside the loop, because the only declaration ofkey
is 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 while
loop isn't anything close to optimal in the middle of your key-detection logic.
精彩评论