Jonathan
Jonathan

Reputation: 13

How can I have my program wait for input, without being in a loop

I'm writing a Pygame program that takes user input to write music. It waits for a specific event (ie keyboard or mouse input) and immediately analyzes the input without the user pressing enter with each entry.

while (running == 1):
    for event in pygame.event.get():
# If event is a keypress
        if(event.type == pygame.KEYDOWN):
            key = pygame.key.get_pressed()  # get_pressed returns an boolean array
                                            # of every key showing pressed or not
# Find which key is pressed
            for x in range(len(key)):
                if(key[x] == 1):
                    break
# If a number key is pressed (0-9)
            if(x >= 48 and x <=57):
# Set the octave to keypress
                gui.setOctave(x-48)    # gui is an instance of a class 
                                       # that controlls pygame display

The only way I know to do this is using the infinite while loop. This, however, takes up nearly all CPU power to run. Is there another efficient way to go about this without using the loop?

Upvotes: 1

Views: 2225

Answers (1)

jfs
jfs

Reputation: 414139

You could use event = pygame.event.wait() to wait for an event.

Upvotes: 3

Related Questions