Python Forum
Handling multiple keyboard entries in Pygame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handling multiple keyboard entries in Pygame
#1
I have some python code that uses a pygame window to establish which key is being pressed. When a key is pressed, the code heads off and does things before coming back to see what the next key pressed might be.
The problem I have is that if the user presses a key repeatedly, even while the 'code heads off and does things', pygame seems to remember what has been pressed rather than waiting for the next keypress. What I want is for the code to ignore any keypresses while the 'go and do stuff' is done then once that's finished, get the next keypress. Hope this makes sense!

import pygame
import time

pygame.init()

screen = pygame.display.set_mode((450,282))
screen.fill((0,0,0))
pygame.display.flip()
clock = pygame.time.Clock()
done = False

def go_and_do_things():
    print("doing things")
    time.sleep(2)
    print("things done")

# Loop as long as done == False
while not done:    
    for event in pygame.event.get():  # User did something
        if event.type == pygame.KEYDOWN:
            keypressedcode = event.key # This is the ASCII code
            print("keypressedcode is " + str(keypressedcode))
            go_and_do_things()


        elif event.type == pygame.QUIT:  # If user clicked close
            done = True  # Flag that we are done so we exit this loop

    clock.tick(60)

time.sleep(4)
pygame.quit()
Reply
#2
Create a boolean flag that toggles on at the start of the function execution and toggles off afterwords. Then only check events when that flag is off.
Recommended Tutorials:
Reply
#3
You could use.
pygame.event.clear(eventtype=pygame.KEYDOWN)
pygame.event.set_blocked(pygame.KEYDOWN)
pygame.event.set_allowed(pygame.KEYDOWN)

Tip: Never use time.sleep. This is a show stopper. Use pygame.time.get_ticks() or delta. You get delta from clock. delta = clock.tick(60)

Here I just ignore keydown. When it doing something. At the same time it clearing it from the buffer.
import pygame
from itertools import count

def add_line(terminal, font, text, color):
    image = font.render(text, 1, color)
    terminal.append(image)
    if len(terminal) > 10:
        return terminal[1:]

    return terminal

def main():
    pygame.init()

    # Basic pygame setup
    pygame.display.set_caption("Example")
    surface = pygame.display.set_mode((450, 282))
    clock = pygame.time.Clock()
    done = False
    delta = 0
    fps = 60

    # Text display
    font = pygame.font.Font(None, 16)
    terminal = []

    # Do something
    ds_sleep = 1000
    ds_start = False
    ds_tick = 0

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if not ds_start:
                    text = "Key: {} -- Unicode: {}".format(event.key, event.unicode)
                    terminal = add_line(terminal, font, text, pygame.Color("white"))
                    ds_start = True
                    terminal = add_line(terminal, font, "Something Started", pygame.Color("dodgerblue"))
            elif event.type == pygame.QUIT:
                done = True

        # Countdown
        if ds_start:
            if ds_tick > ds_sleep:
                ds_start = False
                ds_tick = 0
                terminal = add_line(terminal, font, "Something Done", pygame.Color("dodgerblue"))
            else:
                ds_tick += delta

        # Clear surface
        surface.fill(pygame.Color('black'))

        # Draw code
        y = count(20, 20)
        for text in terminal:
            surface.blit(text, (10, next(y)))

        # Render main surface to screen
        pygame.display.flip()
        delta = clock.tick(fps)

if __name__ == "__main__":
    main()
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basically a Python Tetris game [pygame] rather keyboard arrows can be controlled with lsepolis123 9 5,099 Sep-10-2019, 08:12 PM
Last Post: metulburr
  [pyGame] How do i change text with keyboard ?... JamieVanCadsand 1 4,531 Oct-03-2017, 10:05 AM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020