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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…