1

I'm trying to create a game where keys are randomly selected and appear on the screen, and the player has to click on them. How to implement a check for pressing the desired key ?

unic1=random.randint(0,9)
unic2=random.randint(0,9)
for event in pygame.event.get():
    if event.type == pygame.QUIT:  
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == "pygame.K_"+ str(unic1):
            x2+=10
            unic1=random.randint(0,9)
        elif event.key != "pygame.K_" + str(unic1):
            x2-=10
            unic1=random.randint(0,9)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Serg005
  • 31
  • 2

2 Answers2

0
pygame.key.name(event.key)

will return the key name (a, b, c, 1, 2, 3) etc. You can use this to test for the correct key being pressed:

if pygame.key.name(event.key) == str(unic1):
  # the key was pressed
marienbad
  • 1,461
  • 1
  • 9
  • 19
0

The numpad has the ley cods from pygame.K_KP0 to pygame.K_KP9.

Create a list of the keys:

key_list = [pygame.K_KP0, pygame.K_KP1, pygame.K_KP2, pygame.K_KP3, pygame.K_KP4
            pygame.K_KP5, pygame.K_KP6, pygame.K_KP7, pygame.K_KP8, pygame.K_KP9]

Use random.choice to choose a random key:

random_key = random.choice(key_list)

The keyboard events KEYDOWN and KEYUP (see pygame.event module) create a pygame.event.Event object with additional attributes. The key that was pressed can be obtained from the key attribute (e.g. K_RETURN , K_a) and the mod attribute contains a bitset with additional modifiers (e.g. KMOD_LSHIFT). The unicode attribute provides the Unicode representation of the keyboard input.

for event in pygame.event.get():
    if event.type == pygame.QUIT:  
        running = False
    elif event.type == pygame.KEYDOWN:

        if event.key == random_key:
            print(pygame.key.name(event.key))  
            # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174