I've taken up the adventure of creating a relatively small command-line RPG to flex my newfound Python muscles, but I've already run into a conundrum. I'm using this implementation of getch():
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin.fileno())
key = sys.stdin.read(3)
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
I have key
set to read in 3 characters to capture arrow keys. Up, for example, is read in as ESC[A
; with this method, I can use key[2]
to determine if an arrow key was pressed and which one. All well and good, except that I'd also like to capture all sorts of other keys; q
for quest log, wasd
for movement (pressing the arrows in various orders will be the method of attack), and many others. The problem is instantly clear; if getch()
only returns a single character, arrow functionality is lost entirely.
I'm contemplating rethinking the arrow system altogether if there is no simple solution, but I'm almost certain there must be. Admittedly, I know little of what is going on within tty
, but I read somewhere that if you only read in 1 character, the excess characters from an arrow press are retained in the buffer. How might I go about accessing said buffer? Alternatively, is there some clever way to tell stdin
to expect input of variable length?
Thank you in advance for any and all assistance.