Check number of times **specific** key is pressed - pygame

Viewed 310

I was writing a pygame program and kinda got stuck because I want to check if a specific key, for example K_b was pressed and count how many times, but I cannot figure out a way to do that and only can count how many times keys were pressed in general and that's not what my goal is. To make it more clear my game is hangman with keyboard keys so if a specific key is pressed more than once the game should not go to the next stage of the hangman because in the real game if you guess a wrong letter you cannot guess it again and just infinitely continue on stages. I hope it was clear enough to understand if not I can try to explain even further with more details

2 Answers

A simple way to get the pressed key is to use the unicode attribute of the KEYDOWN event (you could also use key or scancode, but unicode contains the right character instead of an constant).

Then use a dict to count how often each key was pressed. Here's a simple example:

import pygame
import pygame.freetype
from collections import defaultdict

def main():
    pygame.init()
    screen = pygame.display.set_mode((700,700))
    font = pygame.freetype.SysFont('Arial', 32)
    font.origin = True
    d = defaultdict(lambda: 0)
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN:
                d[event.unicode] += 1
        
        screen.fill((10, 10, 10))
        y = 100
        for c in sorted(d):
            font.render_to(screen, (100, y), f'{c}: {d[c]}', 'white')
            y += 30
        pygame.display.flip()

main()

enter image description here

You detect a key press by the following code:

# Initiate key presses
z_presses = 0

# Game loop
while True:

    # Events happening in your GUI
    for event in pygame.event.get():
            
        # Here you detect if a key press is made (any key)
        if event.type == pygame.KEYDOWN:

            # Here you detect specific keys, 'z'-key in this example.
            if event.key == pygame.K_z:
                # Here you do whatever you are supposed to do when 'z'-key is pressed.
                z_presses += 1
Related