Using PyGame, I want to create a moving square which moves in a grid, controlled by keyboard presses of the arrows. So, pressing the "up" key moves the square to the cell directly upwards, pressing the "right" key moves the square to the cell directly to the right, etc.
In my loop, I use
pygame.time.wait(x), to pause for
x ms. However, choosing the correct value for
x is proving difficult. If
x is too large (e.g. 1000), then the square does not respond immediately, and I actually have to hold down the key to get it to move. But if
x is too small (e.g. 10), then the square will move several times in a row whenever I press a key. But I just want the square to move once for every key press. How can I do this? Thanks!
Below is the important part of my code:
x = 100 current_pos = [0, 0] while True: pygame.event.pump() # process event queue is_key_pressed = pygame.key.get_pressed() if is_key_pressed[pygame.K_UP]: current_pos -= 1 elif is_key_pressed[pygame.K_RIGHT]: current_pos += 1 elif is_key_pressed[pygame.K_DOWN]: current_pos += 1 elif is_key_pressed[pygame.K_LEFT]: current_pos -= 1 show_map(current_pos) pygame.time.wait(x)