user637965
user637965

Reputation:

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 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

Upvotes: 2

Views: 666

Answers (2)

lunixbochs
lunixbochs

Reputation: 22415

Observing the following criteria:

  • The loop will only end when key is an arrow, because the only return statements and n = 'stop' statements happen when key is an arrow key.

  • The value of key will never change from inside the loop, because the only declaration of key is in the definition of speed()

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.

Upvotes: 2

Ell
Ell

Reputation: 4358

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.

Upvotes: 5

Related Questions