I’m using this python code https://gist.github.com/seankmartin/f660eff4787b586f94d5f678932bcd27#file-keyboardpress-py to get time for keyboard events. It’s working well, but I need to get KEYDOWN and KEYUP also for capital letters and exclamation point. So I modified it by adding
elif event.key == key and pygame.key.get_mods() & pygame.KMOD_SHIFT: print (f"Pressed SHIFT + key {key_strs[i]} at time {ctr_adj_ms:.0f}ms")
to this part
if event.type == pygame.KEYDOWN: for i, key in enumerate(keys): if event.key == key: counters[i] = time.time() ctr_adj = counters[i] - start_time ctr_adj_ms = ctr_adj * 1000 time_log.append((key_strs[i], ctr_adj_ms)) print(f"Pressed key {key_strs[i]} at time {ctr_adj_ms:.0f}ms")
So now it looks like this
if event.type == pygame.KEYDOWN: for i, key in enumerate(keys): if event.key == key: counters[i] = time.time() ctr_adj = counters[i] - start_time ctr_adj_ms = ctr_adj * 1000 time_log.append((key_strs[i], ctr_adj_ms)) print(f"Pressed key {key_strs[i]} at time {ctr_adj_ms:.0f}ms") elif event.key == key and pygame.key.get_mods() & pygame.KMOD_SHIFT: counters[i] = time.time() ctr_adj = counters[i] - start_time ctr_adj_ms = ctr_adj * 1000 time_log.append((key_strs[i], ctr_adj_ms)) print (f"Pressed SHIFT + key {key_strs[i]} at time {ctr_adj_ms:.0f}ms")
But I still can’t get no capitals letter, no exclamation point. What i’m doing wrong?
Advertisement
Answer
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. e.g.:
for event in pygme.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: if event.mod in [pygame.KMOD_LSHIFT, pygame.KMOD_RSHIFT]: # capital 'A' # ...