문제

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.

도움이 되었습니까?

해결책

don't read three characters. Read one.

If the one character you just read is ESC, read another character or two to see if it was an arrow key or whatever. If it was a q, do the thing for that and then start over.

다른 팁

If you consider developing a full game, PyGame could also be useful (eventually ncurses).

The getch() snippet can be upgraded to read arrow key, but how to make the difference between the first char of an arrow key and the ESC key? If the user press ESC, the solution described will probably wait for the next key press.

I did not find any solution for handling this last case.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top