Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65894150/check-number-of-times-specific-key-is-pressed-pygame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...