Skip to content

Instantly share code, notes, and snippets.

@goedel-gang
Last active June 16, 2018 08:45
Show Gist options
  • Save goedel-gang/40db626cb43e679b51a0bf3c5e1eace3 to your computer and use it in GitHub Desktop.
Save goedel-gang/40db626cb43e679b51a0bf3c5e1eace3 to your computer and use it in GitHub Desktop.
# this works quite nicely in a terminal, and can be more easily extended
from curses import wrapper
def main(stdscr):
ch = ''
while ch != 'q':
# getch returns codepoint, so convert to chr
# this makes things like [Left] behave strangely - if you want to
# capture those, don't call chr but instead look at which number is
# produced by the key and test against that
ch = chr(stdscr.getch())
stdscr.clear()
stdscr.addstr("Key {!r} pressed".format(ch))
if __name__ == "__main__":
wrapper(main)
# https://stackoverflow.com/a/21659588
# barebones approach in terminal
import termios
import sys, tty
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
# you can also do `from keypress import getch`, and this part of the code won't
# run
if __name__ == "__main__":
ch = ''
while ch != 'q':
ch = getch()
print("\nEntered {!r}".format(ch))
# https://stackoverflow.com/a/27732925
# this approach allows you to continuously query if a key is down. this is only
# really possible with something like pygame.
# this method will tell you exactly which keys are currently pressed, probably
# well over several hundred times per second, as opposed to telling you when a
# key is pressed, once per press, like all the other methods
import pygame
import sys
pygame.init()
pygame.display.set_mode((100, 100))
while True:
keys = pygame.key.get_pressed()
print("Keys pressed: {}".format([chr(i) for i, p in enumerate(keys) if p]), end=" ")
if keys[pygame.K_LEFT]:
print("going left")
elif keys[pygame.K_RIGHT]:
print("going right")
elif keys[pygame.K_UP]:
print("going up")
elif keys[pygame.K_DOWN]:
print("going down")
elif keys[pygame.K_q]:
sys.exit()
else:
print("nothing to see here")
pygame.event.pump()
# https://stackoverflow.com/a/27732925
# this approach will work in both idle and terminal, *if you have pygame
# installed*
# if not installed, you may try some variation of
# pip install pygame
#or pip install --user pygame
# (commands to be executed at command line)
# These do require pip, and an internet connection
import pygame
import sys
pygame.init()
pygame.display.set_mode((100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
# the chr thing is similar to curses
print("Key {!r} pressed".format(chr(event.key)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment